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,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/LogMessage.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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// log message that can generate string lazily /// </summary> internal abstract class LogMessage { public LogLevel LogLevel { get; protected set; } = LogLevel.Debug; public static LogMessage Create(string message, LogLevel logLevel) => StaticLogMessage.Construct(message, logLevel); public static LogMessage Create(Func<string> messageGetter, LogLevel logLevel) => LazyLogMessage.Construct(messageGetter, logLevel); public static LogMessage Create<TArg>(Func<TArg, string> messageGetter, TArg arg, LogLevel logLevel) => LazyLogMessage<TArg>.Construct(messageGetter, arg, logLevel); public static LogMessage Create<TArg0, TArg1>(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1>.Construct(messageGetter, arg0, arg1, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2>(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2>.Construct(messageGetter, arg0, arg1, arg2, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2, TArg3>(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2, TArg3>.Construct(messageGetter, arg0, arg1, arg2, arg3, logLevel); // message will be either initially set or lazily set by caller private string? _message; protected abstract string CreateMessage(); /// <summary> /// Logger will call this to return LogMessage to its pool /// </summary> protected abstract void FreeCore(); public string GetMessage() { if (_message == null) { _message = CreateMessage(); } return _message; } public void Free() { _message = null; FreeCore(); } private sealed class StaticLogMessage : LogMessage { private static readonly ObjectPool<StaticLogMessage> s_pool = SharedPools.Default<StaticLogMessage>(); public static LogMessage Construct(string message, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._message = message; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _message!; protected override void FreeCore() { if (_message == null) { return; } _message = null; s_pool.Free(this); } } private sealed class LazyLogMessage : LogMessage { private static readonly ObjectPool<LazyLogMessage> s_pool = SharedPools.Default<LazyLogMessage>(); private Func<string>? _messageGetter; public static LogMessage Construct(Func<string> messageGetter, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0>> s_pool = SharedPools.Default<LazyLogMessage<TArg0>>(); private Func<TArg0, string>? _messageGetter; private TArg0? _arg; public static LogMessage Construct(Func<TArg0, string> messageGetter, TArg0 arg, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg = arg; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1>>(); private Func<TArg0, TArg1, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; internal static LogMessage Construct(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2>>(); private Func<TArg0, TArg1, TArg2, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2, TArg3> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>>(); private Func<TArg0, TArg1, TArg2, TArg3, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; private TArg3? _arg3; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage._arg3 = arg3; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!, _arg3!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; _arg3 = default; s_pool.Free(this); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// log message that can generate string lazily /// </summary> internal abstract class LogMessage { public LogLevel LogLevel { get; protected set; } = LogLevel.Debug; public static LogMessage Create(string message, LogLevel logLevel) => StaticLogMessage.Construct(message, logLevel); public static LogMessage Create(Func<string> messageGetter, LogLevel logLevel) => LazyLogMessage.Construct(messageGetter, logLevel); public static LogMessage Create<TArg>(Func<TArg, string> messageGetter, TArg arg, LogLevel logLevel) => LazyLogMessage<TArg>.Construct(messageGetter, arg, logLevel); public static LogMessage Create<TArg0, TArg1>(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1>.Construct(messageGetter, arg0, arg1, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2>(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2>.Construct(messageGetter, arg0, arg1, arg2, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2, TArg3>(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2, TArg3>.Construct(messageGetter, arg0, arg1, arg2, arg3, logLevel); // message will be either initially set or lazily set by caller private string? _message; protected abstract string CreateMessage(); /// <summary> /// Logger will call this to return LogMessage to its pool /// </summary> protected abstract void FreeCore(); public string GetMessage() { if (_message == null) { _message = CreateMessage(); } return _message; } public void Free() { _message = null; FreeCore(); } private sealed class StaticLogMessage : LogMessage { private static readonly ObjectPool<StaticLogMessage> s_pool = SharedPools.Default<StaticLogMessage>(); public static LogMessage Construct(string message, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._message = message; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _message!; protected override void FreeCore() { if (_message == null) { return; } _message = null; s_pool.Free(this); } } private sealed class LazyLogMessage : LogMessage { private static readonly ObjectPool<LazyLogMessage> s_pool = SharedPools.Default<LazyLogMessage>(); private Func<string>? _messageGetter; public static LogMessage Construct(Func<string> messageGetter, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0>> s_pool = SharedPools.Default<LazyLogMessage<TArg0>>(); private Func<TArg0, string>? _messageGetter; private TArg0? _arg; public static LogMessage Construct(Func<TArg0, string> messageGetter, TArg0 arg, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg = arg; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1>>(); private Func<TArg0, TArg1, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; internal static LogMessage Construct(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2>>(); private Func<TArg0, TArg1, TArg2, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2, TArg3> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>>(); private Func<TArg0, TArg1, TArg2, TArg3, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; private TArg3? _arg3; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage._arg3 = arg3; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!, _arg3!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; _arg3 = default; s_pool.Free(this); } } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/Interop/ICodeElements.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; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { /// <summary> /// A redefinition of the EnvDTE.CodeElements interface. The interface, as defined in the PIA does not do /// PreserveSig for the Item function. WinForms, specifically, uses the Item property when generating methods to see /// if a method already exists. The only way it sees if something exists is if the call returns E_INVALIDARG. With /// the normal PIAs though, this would result in a first-chance exception. Therefore, the WinForms team has their /// own definition for CodeElements which also [PreserveSig]s Item. We do this here to make their work still /// worthwhile. /// </summary> [ComImport] [Guid("0CFBC2B5-0D4E-11D3-8997-00C04F688DDE")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] internal interface ICodeElements : IEnumerable { [DispId(-4)] [TypeLibFunc(TypeLibFuncFlags.FRestricted)] new IEnumerator GetEnumerator(); [DispId(1)] EnvDTE.DTE DTE { [return: MarshalAs(UnmanagedType.Interface)] get; } [DispId(2)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0)] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int Item(object index, [MarshalAs(UnmanagedType.Interface)] out EnvDTE.CodeElement element); [DispId(3)] int Count { get; } [TypeLibFunc(TypeLibFuncFlags.FHidden | TypeLibFuncFlags.FRestricted)] [DispId(4)] void Reserved1(object element); [DispId(5)] bool CreateUniqueID([MarshalAs(UnmanagedType.BStr)] string prefix, [MarshalAs(UnmanagedType.BStr)] ref string newName); } }
// Licensed to the .NET Foundation under one or more 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; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { /// <summary> /// A redefinition of the EnvDTE.CodeElements interface. The interface, as defined in the PIA does not do /// PreserveSig for the Item function. WinForms, specifically, uses the Item property when generating methods to see /// if a method already exists. The only way it sees if something exists is if the call returns E_INVALIDARG. With /// the normal PIAs though, this would result in a first-chance exception. Therefore, the WinForms team has their /// own definition for CodeElements which also [PreserveSig]s Item. We do this here to make their work still /// worthwhile. /// </summary> [ComImport] [Guid("0CFBC2B5-0D4E-11D3-8997-00C04F688DDE")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] internal interface ICodeElements : IEnumerable { [DispId(-4)] [TypeLibFunc(TypeLibFuncFlags.FRestricted)] new IEnumerator GetEnumerator(); [DispId(1)] EnvDTE.DTE DTE { [return: MarshalAs(UnmanagedType.Interface)] get; } [DispId(2)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0)] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int Item(object index, [MarshalAs(UnmanagedType.Interface)] out EnvDTE.CodeElement element); [DispId(3)] int Count { get; } [TypeLibFunc(TypeLibFuncFlags.FHidden | TypeLibFuncFlags.FRestricted)] [DispId(4)] void Reserved1(object element); [DispId(5)] bool CreateUniqueID([MarshalAs(UnmanagedType.BStr)] string prefix, [MarshalAs(UnmanagedType.BStr)] ref string newName); } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListenerProvider+NullOperationListener.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.CompilerServices; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.TestHooks { internal sealed partial class AsynchronousOperationListenerProvider { private sealed class NullOperationListener : IAsynchronousOperationListener { public IAsyncToken BeginAsyncOperation( string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) => EmptyAsyncToken.Instance; public Task<bool> Delay(TimeSpan delay, CancellationToken cancellationToken) { // This could be as simple as: // await Task.Delay(delay, cancellationToken).ConfigureAwait(false); // return true; // However, whereas in general cancellation is expected to be rare and thus throwing // an exception in response isn't very impactful, here it's expected to be the case // more often than not as the operation is being used to delay an operation because // it's expected something else is going to happen to obviate the need for that // operation. Thus, we can spend a little more code avoiding the additional throw // for the common case of an exception occurring. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<bool>(cancellationToken); } var t = Task.Delay(delay, cancellationToken); if (t.IsCompleted) { // Avoid ContinueWith overheads for a 0 delay or if race conditions resulted // in the delay task being complete by the time we checked. return t.Status == TaskStatus.RanToCompletion ? SpecializedTasks.True : Task.FromCanceled<bool>(cancellationToken); } return t.ContinueWith( _ => true, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default); // Note the above passes CancellationToken.None and TaskContinuationOptions.NotOnCanceled. // That's cheaper than passing cancellationToken and with the same semantics except // that if the returned task does end up being canceled, any operation canceled exception // thrown won't contain the cancellationToken. If that ends up being impactful, it can // be switched to use `cancellationToken, TaskContinuationOptions.ExecuteSynchronously`. } } } }
// Licensed to the .NET Foundation under one or more 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.CompilerServices; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.TestHooks { internal sealed partial class AsynchronousOperationListenerProvider { private sealed class NullOperationListener : IAsynchronousOperationListener { public IAsyncToken BeginAsyncOperation( string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) => EmptyAsyncToken.Instance; public Task<bool> Delay(TimeSpan delay, CancellationToken cancellationToken) { // This could be as simple as: // await Task.Delay(delay, cancellationToken).ConfigureAwait(false); // return true; // However, whereas in general cancellation is expected to be rare and thus throwing // an exception in response isn't very impactful, here it's expected to be the case // more often than not as the operation is being used to delay an operation because // it's expected something else is going to happen to obviate the need for that // operation. Thus, we can spend a little more code avoiding the additional throw // for the common case of an exception occurring. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<bool>(cancellationToken); } var t = Task.Delay(delay, cancellationToken); if (t.IsCompleted) { // Avoid ContinueWith overheads for a 0 delay or if race conditions resulted // in the delay task being complete by the time we checked. return t.Status == TaskStatus.RanToCompletion ? SpecializedTasks.True : Task.FromCanceled<bool>(cancellationToken); } return t.ContinueWith( _ => true, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default); // Note the above passes CancellationToken.None and TaskContinuationOptions.NotOnCanceled. // That's cheaper than passing cancellationToken and with the same semantics except // that if the returned task does end up being canceled, any operation canceled exception // thrown won't contain the cancellationToken. If that ends up being impactful, it can // be switched to use `cancellationToken, TaskContinuationOptions.ExecuteSynchronously`. } } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/LanguageService/CSharpCodeCleanupFixerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.CodeCleanUp; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeCleanup; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeCleanup { [Export(typeof(ICodeCleanUpFixerProvider))] [AppliesToProject("CSharp")] [ContentType(ContentTypeNames.CSharpContentType)] internal class CSharpCodeCleanUpFixerProvider : AbstractCodeCleanUpFixerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeCleanUpFixerProvider( [ImportMany] IEnumerable<Lazy<AbstractCodeCleanUpFixer, ContentTypeMetadata>> codeCleanUpFixers) : base(codeCleanUpFixers) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Language.CodeCleanUp; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeCleanup; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeCleanup { [Export(typeof(ICodeCleanUpFixerProvider))] [AppliesToProject("CSharp")] [ContentType(ContentTypeNames.CSharpContentType)] internal class CSharpCodeCleanUpFixerProvider : AbstractCodeCleanUpFixerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeCleanUpFixerProvider( [ImportMany] IEnumerable<Lazy<AbstractCodeCleanUpFixer, ContentTypeMetadata>> codeCleanUpFixers) : base(codeCleanUpFixers) { } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Shared/Extensions/INamespaceSymbolExtensions.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.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamespaceSymbolExtensions { private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap = new(); public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo; public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer(); private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol) { var result = new List<string>(); GetNameParts(namespaceSymbol, result); return result; } private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result) { if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace) { return; } GetNameParts(namespaceSymbol.ContainingNamespace, result); result.Add(namespaceSymbol.Name); } public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2) { var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts); var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts); for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++) { var comp = names1[i].CompareTo(names2[i]); if (comp != 0) { return comp; } } return names1.Count - names2.Count; } public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceOrTypeSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetMembers().AsEnumerable()); yield return childNamespace; } else { var child = (INamedTypeSymbol)current; stack.Push(child.GetTypeMembers()); yield return child; } } } public static IEnumerable<INamespaceSymbol> GetAllNamespaces( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetNamespaceMembers()); yield return childNamespace; } } } public static IEnumerable<INamedTypeSymbol> GetAllTypes( this IEnumerable<INamespaceSymbol> namespaceSymbols, CancellationToken cancellationToken) { return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken)); } /// <summary> /// Searches the namespace for namespaces with the provided name. /// </summary> public static IEnumerable<INamespaceSymbol> FindNamespaces( this INamespaceSymbol namespaceSymbol, string namespaceName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>(); foreach (var child in matchingChildren) { yield return child; } stack.Push(current.GetNamespaceMembers()); } } public static bool ContainsAccessibleTypesOrNamespaces( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly) { using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject(); return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object); } public static INamespaceSymbol? GetQualifiedNamespace( this INamespaceSymbol globalNamespace, string namespaceName) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Count() == 1 ? members.First() as INamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool ContainsAccessibleTypesOrNamespacesWorker( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly, Queue<INamespaceOrTypeSymbol> namespaceQueue) { // Note: we only store INamespaceSymbols in here, even though we type it as // INamespaceOrTypeSymbol. This is because when we call GetMembers below we // want it to return an ImmutableArray so we don't incur any costs to iterate // over it. foreach (var constituent in namespaceSymbol.ConstituentNamespaces) { // Assume that any namespace in our own assembly is accessible to us. This saves a // lot of cpu time checking namespaces. if (Equals(constituent.ContainingAssembly, assembly)) { return true; } namespaceQueue.Enqueue(constituent); } while (namespaceQueue.Count > 0) { var ns = namespaceQueue.Dequeue(); // Upcast so we call the 'GetMembers' method that returns an ImmutableArray. var members = ns.GetMembers(); foreach (var namespaceOrType in members) { if (namespaceOrType.Kind == SymbolKind.NamedType) { if (namespaceOrType.IsAccessibleWithin(assembly)) { return true; } } else { namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType); } } } 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; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamespaceSymbolExtensions { private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap = new(); public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo; public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer(); private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol) { var result = new List<string>(); GetNameParts(namespaceSymbol, result); return result; } private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result) { if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace) { return; } GetNameParts(namespaceSymbol.ContainingNamespace, result); result.Add(namespaceSymbol.Name); } public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2) { var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts); var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts); for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++) { var comp = names1[i].CompareTo(names2[i]); if (comp != 0) { return comp; } } return names1.Count - names2.Count; } public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceOrTypeSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetMembers().AsEnumerable()); yield return childNamespace; } else { var child = (INamedTypeSymbol)current; stack.Push(child.GetTypeMembers()); yield return child; } } } public static IEnumerable<INamespaceSymbol> GetAllNamespaces( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetNamespaceMembers()); yield return childNamespace; } } } public static IEnumerable<INamedTypeSymbol> GetAllTypes( this IEnumerable<INamespaceSymbol> namespaceSymbols, CancellationToken cancellationToken) { return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken)); } /// <summary> /// Searches the namespace for namespaces with the provided name. /// </summary> public static IEnumerable<INamespaceSymbol> FindNamespaces( this INamespaceSymbol namespaceSymbol, string namespaceName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>(); foreach (var child in matchingChildren) { yield return child; } stack.Push(current.GetNamespaceMembers()); } } public static bool ContainsAccessibleTypesOrNamespaces( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly) { using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject(); return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object); } public static INamespaceSymbol? GetQualifiedNamespace( this INamespaceSymbol globalNamespace, string namespaceName) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Count() == 1 ? members.First() as INamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool ContainsAccessibleTypesOrNamespacesWorker( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly, Queue<INamespaceOrTypeSymbol> namespaceQueue) { // Note: we only store INamespaceSymbols in here, even though we type it as // INamespaceOrTypeSymbol. This is because when we call GetMembers below we // want it to return an ImmutableArray so we don't incur any costs to iterate // over it. foreach (var constituent in namespaceSymbol.ConstituentNamespaces) { // Assume that any namespace in our own assembly is accessible to us. This saves a // lot of cpu time checking namespaces. if (Equals(constituent.ContainingAssembly, assembly)) { return true; } namespaceQueue.Enqueue(constituent); } while (namespaceQueue.Count > 0) { var ns = namespaceQueue.Dequeue(); // Upcast so we call the 'GetMembers' method that returns an ImmutableArray. var members = ns.GetMembers(); foreach (var namespaceOrType in members) { if (namespaceOrType.Kind == SymbolKind.NamedType) { if (namespaceOrType.IsAccessibleWithin(assembly)) { return true; } } else { namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType); } } } return false; } } }
-1
dotnet/roslyn
55,027
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-21T22:19:50Z
2021-07-21T23:08:52Z
dff569c162ab629ab598e2a458b3c1eabcd31b57
3345d9cdff847536cd42369fd2a7529066078ee7
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Core/MarkedSource/SourceWithMarkedNodes.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.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Roslyn.Test.Utilities { internal sealed partial class SourceWithMarkedNodes { /// <summary> /// The source with markers stripped out, that was used to produce the tree /// </summary> public readonly string Source; /// <summary> /// The original input source, with markers in tact /// </summary> public readonly string Input; public readonly SyntaxTree Tree; public readonly ImmutableArray<MarkedSpan> MarkedSpans; public readonly ImmutableArray<ValueTuple<TextSpan, int, int>> SpansAndKindsAndIds; /// <summary> /// Parses source code with markers for further processing /// </summary> /// <param name="markedSource">The marked source</param> /// <param name="parser">Delegate to turn source code into a syntax tree</param> /// <param name="getSyntaxKind">Delegate to turn a marker into a syntax kind</param> /// <param name="removeTags">Whether to remove tags from the source, as distinct from replacing them with whitespace. Note that if this /// value is true then any marked node other than the first, will have an incorrect offset.</param> public SourceWithMarkedNodes(string markedSource, Func<string, SyntaxTree> parser, Func<string, int> getSyntaxKind, bool removeTags = false) { Source = removeTags ? RemoveTags(markedSource) : ClearTags(markedSource); Input = markedSource; Tree = parser(Source); MarkedSpans = ImmutableArray.CreateRange(GetSpansRecursive(markedSource, 0, getSyntaxKind)); SpansAndKindsAndIds = ImmutableArray.CreateRange(MarkedSpans.Select(s => (s.MarkedSyntax, s.SyntaxKind, s.Id))); } private static IEnumerable<MarkedSpan> GetSpansRecursive(string markedSource, int offset, Func<string, int> getSyntaxKind) { foreach (var match in s_markerPattern.Matches(markedSource).ToEnumerable()) { var tagName = match.Groups["TagName"]; var markedSyntax = match.Groups["MarkedSyntax"]; var syntaxKindOpt = match.Groups["SyntaxKind"].Value; var idOpt = match.Groups["Id"].Value; var id = string.IsNullOrEmpty(idOpt) ? 0 : int.Parse(idOpt); var parentIdOpt = match.Groups["ParentId"].Value; var parentId = string.IsNullOrEmpty(parentIdOpt) ? 0 : int.Parse(parentIdOpt); var parsedKind = string.IsNullOrEmpty(syntaxKindOpt) ? 0 : getSyntaxKind(syntaxKindOpt); int absoluteOffset = offset + markedSyntax.Index; yield return new MarkedSpan(new TextSpan(absoluteOffset, markedSyntax.Length), new TextSpan(match.Index, match.Length), tagName.Value, parsedKind, id, parentId); foreach (var nestedSpan in GetSpansRecursive(markedSyntax.Value, absoluteOffset, getSyntaxKind)) { yield return nestedSpan; } } } internal static string RemoveTags(string source) { return s_tags.Replace(source, ""); } internal static string ClearTags(string source) { return s_tags.Replace(source, m => new string(' ', m.Length)); } private static readonly Regex s_tags = new Regex( @"[<][/]?[NMCL][:]?[:\.A-Za-z0-9]*[>]", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); private static readonly Regex s_markerPattern = new Regex( @"[<] # Open tag (?<TagName>[NMCL]) # The actual tag name can be any of these letters ( # Start a group so that everything after the tag can be optional [:] # A colon (?<Id>[0-9]+) # The first number after the colon is the Id ([.](?<ParentId>[0-9]+))? # Digits after a decimal point are the parent Id ([:](?<SyntaxKind>[A-Za-z]+))? # A second colon separates the syntax kind )? # Close the group for the things after the tag name [>] # Close tag ( # Start a group so that the closing tag is optional (?<MarkedSyntax>.*) # This matches the source within the tags [<][/][NMCL][:]?(\k<Id>)* [>] # The closing tag with its optional Id )? # End of the group for the closing tag", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); public ImmutableDictionary<SyntaxNode, int> MapSyntaxNodesToMarks() { var root = Tree.GetRoot(); var builder = ImmutableDictionary.CreateBuilder<SyntaxNode, int>(); for (int i = 0; i < SpansAndKindsAndIds.Length; i++) { var node = GetNode(root, SpansAndKindsAndIds[i]); builder.Add(node, SpansAndKindsAndIds[i].Item3); } return builder.ToImmutableDictionary(); } private SyntaxNode GetNode(SyntaxNode root, ValueTuple<TextSpan, int, int> spanAndKindAndId) { var node = root.FindNode(spanAndKindAndId.Item1, getInnermostNodeForTie: true); if (spanAndKindAndId.Item2 == 0) { return node; } var nodeOfKind = node.FirstAncestorOrSelf<SyntaxNode>(n => n.RawKind == spanAndKindAndId.Item2); Assert.NotNull(nodeOfKind); return nodeOfKind; } public ImmutableDictionary<int, SyntaxNode> MapMarksToSyntaxNodes() { var root = Tree.GetRoot(); var builder = ImmutableDictionary.CreateBuilder<int, SyntaxNode>(); for (int i = 0; i < SpansAndKindsAndIds.Length; i++) { builder.Add(SpansAndKindsAndIds[i].Item3, GetNode(root, SpansAndKindsAndIds[i])); } return builder.ToImmutableDictionary(); } public static Func<SyntaxNode, SyntaxNode> GetSyntaxMap(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1) { var map0 = source0.MapMarksToSyntaxNodes(); var map1 = source1.MapSyntaxNodesToMarks(); #if DUMP Console.WriteLine("========"); #endif return new Func<SyntaxNode, SyntaxNode>(node1 => { if (map1.TryGetValue(node1, out var mark) && map0.TryGetValue(mark, out var result)) { return result; } #if DUMP Console.WriteLine($"? {node1.RawKind} [[{node1}]]"); #endif 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.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Roslyn.Test.Utilities { internal sealed partial class SourceWithMarkedNodes { /// <summary> /// The source with markers stripped out, that was used to produce the tree /// </summary> public readonly string Source; /// <summary> /// The original input source, with markers in tact /// </summary> public readonly string Input; public readonly SyntaxTree Tree; public readonly ImmutableArray<MarkedSpan> MarkedSpans; public readonly ImmutableArray<ValueTuple<TextSpan, int, int>> SpansAndKindsAndIds; /// <summary> /// Parses source code with markers for further processing /// </summary> /// <param name="markedSource">The marked source</param> /// <param name="parser">Delegate to turn source code into a syntax tree</param> /// <param name="getSyntaxKind">Delegate to turn a marker into a syntax kind</param> /// <param name="removeTags">Whether to remove tags from the source, as distinct from replacing them with whitespace. Note that if this /// value is true then any marked node other than the first, will have an incorrect offset.</param> public SourceWithMarkedNodes(string markedSource, Func<string, SyntaxTree> parser, Func<string, int> getSyntaxKind, bool removeTags = false) { Source = removeTags ? RemoveTags(markedSource) : ClearTags(markedSource); Input = markedSource; Tree = parser(Source); MarkedSpans = ImmutableArray.CreateRange(GetSpansRecursive(markedSource, 0, getSyntaxKind)); SpansAndKindsAndIds = ImmutableArray.CreateRange(MarkedSpans.Select(s => (s.MarkedSyntax, s.SyntaxKind, s.Id))); } private static IEnumerable<MarkedSpan> GetSpansRecursive(string markedSource, int offset, Func<string, int> getSyntaxKind) { foreach (var match in s_markerPattern.Matches(markedSource).ToEnumerable()) { var tagName = match.Groups["TagName"]; var markedSyntax = match.Groups["MarkedSyntax"]; var syntaxKindOpt = match.Groups["SyntaxKind"].Value; var idOpt = match.Groups["Id"].Value; var id = string.IsNullOrEmpty(idOpt) ? 0 : int.Parse(idOpt); var parentIdOpt = match.Groups["ParentId"].Value; var parentId = string.IsNullOrEmpty(parentIdOpt) ? 0 : int.Parse(parentIdOpt); var parsedKind = string.IsNullOrEmpty(syntaxKindOpt) ? 0 : getSyntaxKind(syntaxKindOpt); int absoluteOffset = offset + markedSyntax.Index; yield return new MarkedSpan(new TextSpan(absoluteOffset, markedSyntax.Length), new TextSpan(match.Index, match.Length), tagName.Value, parsedKind, id, parentId); foreach (var nestedSpan in GetSpansRecursive(markedSyntax.Value, absoluteOffset, getSyntaxKind)) { yield return nestedSpan; } } } internal static string RemoveTags(string source) { return s_tags.Replace(source, ""); } internal static string ClearTags(string source) { return s_tags.Replace(source, m => new string(' ', m.Length)); } private static readonly Regex s_tags = new Regex( @"[<][/]?[NMCL][:]?[:\.A-Za-z0-9]*[>]", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); private static readonly Regex s_markerPattern = new Regex( @"[<] # Open tag (?<TagName>[NMCL]) # The actual tag name can be any of these letters ( # Start a group so that everything after the tag can be optional [:] # A colon (?<Id>[0-9]+) # The first number after the colon is the Id ([.](?<ParentId>[0-9]+))? # Digits after a decimal point are the parent Id ([:](?<SyntaxKind>[A-Za-z]+))? # A second colon separates the syntax kind )? # Close the group for the things after the tag name [>] # Close tag ( # Start a group so that the closing tag is optional (?<MarkedSyntax>.*) # This matches the source within the tags [<][/][NMCL][:]?(\k<Id>)* [>] # The closing tag with its optional Id )? # End of the group for the closing tag", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); public ImmutableDictionary<SyntaxNode, int> MapSyntaxNodesToMarks() { var root = Tree.GetRoot(); var builder = ImmutableDictionary.CreateBuilder<SyntaxNode, int>(); for (int i = 0; i < SpansAndKindsAndIds.Length; i++) { var node = GetNode(root, SpansAndKindsAndIds[i]); builder.Add(node, SpansAndKindsAndIds[i].Item3); } return builder.ToImmutableDictionary(); } private SyntaxNode GetNode(SyntaxNode root, ValueTuple<TextSpan, int, int> spanAndKindAndId) { var node = root.FindNode(spanAndKindAndId.Item1, getInnermostNodeForTie: true); if (spanAndKindAndId.Item2 == 0) { return node; } var nodeOfKind = node.FirstAncestorOrSelf<SyntaxNode>(n => n.RawKind == spanAndKindAndId.Item2); Assert.NotNull(nodeOfKind); return nodeOfKind; } public ImmutableDictionary<int, SyntaxNode> MapMarksToSyntaxNodes() { var root = Tree.GetRoot(); var builder = ImmutableDictionary.CreateBuilder<int, SyntaxNode>(); for (int i = 0; i < SpansAndKindsAndIds.Length; i++) { builder.Add(SpansAndKindsAndIds[i].Item3, GetNode(root, SpansAndKindsAndIds[i])); } return builder.ToImmutableDictionary(); } public static Func<SyntaxNode, SyntaxNode> GetSyntaxMap(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1) { var map0 = source0.MapMarksToSyntaxNodes(); var map1 = source1.MapSyntaxNodesToMarks(); #if DUMP Console.WriteLine("========"); #endif return new Func<SyntaxNode, SyntaxNode>(node1 => { if (map1.TryGetValue(node1, out var mark) && map0.TryGetValue(mark, out var result)) { return result; } #if DUMP Console.WriteLine($"? {node1.RawKind} [[{node1}]]"); #endif return null; }); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Portable/CommandLine/CSharpCompiler.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.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpCompiler : CommonCompiler { internal const string ResponseFileName = "csc.rsp"; private readonly CommandLineDiagnosticFormatter _diagnosticFormatter; private readonly string? _tempDirectory; protected CSharpCompiler(CSharpCommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader) : base(parser, responseFile, args, buildPaths, additionalReferenceDirectories, assemblyLoader) { _diagnosticFormatter = new CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, Arguments.PrintFullPaths, Arguments.ShouldIncludeErrorEndLocation); _tempDirectory = buildPaths.TempDirectory; } public override DiagnosticFormatter DiagnosticFormatter { get { return _diagnosticFormatter; } } protected internal new CSharpCommandLineArguments Arguments { get { return (CSharpCommandLineArguments)base.Arguments; } } public override Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions) { var parseOptions = Arguments.ParseOptions; // We compute script parse options once so we don't have to do it repeatedly in // case there are many script files. var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); bool hadErrors = false; var sourceFiles = Arguments.SourceFiles; var trees = new SyntaxTree?[sourceFiles.Length]; var normalizedFilePaths = new string?[sourceFiles.Length]; var diagnosticBag = DiagnosticBag.GetInstance(); if (Arguments.CompilationOptions.ConcurrentBuild) { RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture<int>(i => { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); }), CancellationToken.None); } else { for (int i = 0; i < sourceFiles.Length; i++) { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); } } // If errors had been reported in ParseFile, while trying to read files, then we should simply exit. if (ReportDiagnostics(diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger, compilation: null)) { Debug.Assert(hadErrors); return null; } var diagnostics = new List<DiagnosticInfo>(); var uniqueFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < sourceFiles.Length; i++) { var normalizedFilePath = normalizedFilePaths[i]; Debug.Assert(normalizedFilePath != null); Debug.Assert(sourceFiles[i].IsInputRedirected || PathUtilities.IsAbsolute(normalizedFilePath)); if (!uniqueFilePaths.Add(normalizedFilePath)) { // warning CS2002: Source file '{0}' specified multiple times diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded, Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath))); trees[i] = null; } } if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger is object); foreach (var path in uniqueFilePaths) { touchedFilesLogger.AddRead(path); } } var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default; var appConfigPath = this.Arguments.AppConfigPath; if (appConfigPath != null) { try { using (var appConfigStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read)) { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream); } if (touchedFilesLogger != null) { touchedFilesLogger.AddRead(appConfigPath); } } catch (Exception ex) { diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message)); } } var xmlFileResolver = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger); var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray<string>.Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger); MetadataReferenceResolver referenceDirectiveResolver; var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null)) { return null; } var loggingFileSystem = new LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory); var optionsProvider = new CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalConfigOptions); return CSharpCompilation.Create( Arguments.CompilationName, trees.WhereNotNull(), resolvedReferences, Arguments.CompilationOptions .WithMetadataReferenceResolver(referenceDirectiveResolver) .WithAssemblyIdentityComparer(assemblyIdentityComparer) .WithXmlReferenceResolver(xmlFileResolver) .WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)) .WithSourceReferenceResolver(sourceFileResolver) .WithSyntaxTreeOptionsProvider(optionsProvider)); } private SyntaxTree? ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, ref bool addedDiagnostics, CommandLineSourceFile file, DiagnosticBag diagnostics, out string? normalizedFilePath) { var fileDiagnostics = new List<DiagnosticInfo>(); var content = TryReadFileContent(file, fileDiagnostics, out normalizedFilePath); if (content == null) { foreach (var info in fileDiagnostics) { diagnostics.Add(MessageProvider.CreateDiagnostic(info)); } fileDiagnostics.Clear(); addedDiagnostics = true; return null; } else { Debug.Assert(fileDiagnostics.Count == 0); return ParseFile(parseOptions, scriptParseOptions, content, file); } } private static SyntaxTree ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, SourceText content, CommandLineSourceFile file) { var tree = SyntaxFactory.ParseSyntaxTree( content, file.IsScript ? scriptParseOptions : parseOptions, file.Path); // prepopulate line tables. // we will need line tables anyways and it is better to not wait until we are in emit // where things run sequentially. bool isHiddenDummy; tree.GetMappedLineSpanAndVisibility(default(TextSpan), out isHiddenDummy); return tree; } /// <summary> /// Given a compilation and a destination directory, determine three names: /// 1) The name with which the assembly should be output. /// 2) The path of the assembly/module file. /// 3) The path of the pdb file. /// /// When csc produces an executable, but the name of the resulting assembly /// is not specified using the "/out" switch, the name is taken from the name /// of the file (note: file, not class) containing the assembly entrypoint /// (as determined by binding and the "/main" switch). /// /// For example, if the command is "csc /target:exe a.cs b.cs" and b.cs contains the /// entrypoint, then csc will produce "b.exe" and "b.pdb" in the output directory, /// with assembly name "b" and module name "b.exe" embedded in the file. /// </summary> protected override string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken) { if (Arguments.OutputFileName is object) { return Arguments.OutputFileName; } Debug.Assert(Arguments.CompilationOptions.OutputKind.IsApplication()); var comp = (CSharpCompilation)compilation; Symbol? entryPoint = comp.ScriptClass; if (entryPoint is null) { var method = comp.GetEntryPoint(cancellationToken); if (method is object) { entryPoint = method.PartialImplementationPart ?? method; } else { // no entrypoint found - an error will be reported and the compilation won't be emitted return "error"; } } string entryPointFileName = PathUtilities.GetFileName(entryPoint.Locations.First().SourceTree!.FilePath); return Path.ChangeExtension(entryPointFileName, ".exe"); } internal override bool SuppressDefaultResponseFile(IEnumerable<string> args) { return args.Any(arg => new[] { "/noconfig", "-noconfig" }.Contains(arg.ToLowerInvariant())); } /// <summary> /// Print compiler logo /// </summary> /// <param name="consoleOutput"></param> public override void PrintLogo(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()); consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine2, Culture)); consoleOutput.WriteLine(); } public override void PrintLangVersions(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LangVersions, Culture)); var defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); var latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); foreach (var v in (LanguageVersion[])Enum.GetValues(typeof(LanguageVersion))) { if (v == defaultVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (default)"); } else if (v == latestVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)"); } else { consoleOutput.WriteLine(v.ToDisplayString()); } } consoleOutput.WriteLine(); } internal override Type Type { get { // We do not use this.GetType() so that we don't break mock subtypes return typeof(CSharpCompiler); } } internal override string GetToolName() { return ErrorFacts.GetMessage(MessageID.IDS_ToolName, Culture); } /// <summary> /// Print Commandline help message (up to 80 English characters per line) /// </summary> /// <param name="consoleOutput"></param> public override void PrintHelp(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_CSCHelp, Culture)); } protected override bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code) { return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); } protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { Arguments.ResolveAnalyzersFromArguments(LanguageNames.CSharp, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, out analyzers, out generators); } protected override void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics) { foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot().GetDirectives( d => d.IsActive && !d.HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia)) { var path = (string?)directive.File.Value; if (path == null) { continue; } string? resolvedPath = resolver.ResolveReference(path, tree.FilePath); if (resolvedPath == null) { diagnostics.Add( MessageProvider.CreateDiagnostic( (int)ErrorCode.ERR_NoSourceFile, directive.File.GetLocation(), path, CSharpResources.CouldNotFindFile)); continue; } embeddedFiles.Add(resolvedPath); } } private protected override Compilation RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigProvider, ImmutableArray<AdditionalText> additionalTexts, DiagnosticBag diagnostics) { var driver = CSharpGeneratorDriver.Create(generators, additionalTexts, (CSharpParseOptions)parseOptions, analyzerConfigProvider); driver.RunGeneratorsAndUpdateCompilation(input, out var compilationOut, out var generatorDiagnostics); diagnostics.AddRange(generatorDiagnostics); return compilationOut; } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpCompiler : CommonCompiler { internal const string ResponseFileName = "csc.rsp"; private readonly CommandLineDiagnosticFormatter _diagnosticFormatter; private readonly string? _tempDirectory; protected CSharpCompiler(CSharpCommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader, GeneratorDriverCache? driverCache = null) : base(parser, responseFile, args, buildPaths, additionalReferenceDirectories, assemblyLoader, driverCache) { _diagnosticFormatter = new CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, Arguments.PrintFullPaths, Arguments.ShouldIncludeErrorEndLocation); _tempDirectory = buildPaths.TempDirectory; } public override DiagnosticFormatter DiagnosticFormatter { get { return _diagnosticFormatter; } } protected internal new CSharpCommandLineArguments Arguments { get { return (CSharpCommandLineArguments)base.Arguments; } } public override Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions) { var parseOptions = Arguments.ParseOptions; // We compute script parse options once so we don't have to do it repeatedly in // case there are many script files. var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); bool hadErrors = false; var sourceFiles = Arguments.SourceFiles; var trees = new SyntaxTree?[sourceFiles.Length]; var normalizedFilePaths = new string?[sourceFiles.Length]; var diagnosticBag = DiagnosticBag.GetInstance(); if (Arguments.CompilationOptions.ConcurrentBuild) { RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture<int>(i => { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); }), CancellationToken.None); } else { for (int i = 0; i < sourceFiles.Length; i++) { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); } } // If errors had been reported in ParseFile, while trying to read files, then we should simply exit. if (ReportDiagnostics(diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger, compilation: null)) { Debug.Assert(hadErrors); return null; } var diagnostics = new List<DiagnosticInfo>(); var uniqueFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < sourceFiles.Length; i++) { var normalizedFilePath = normalizedFilePaths[i]; Debug.Assert(normalizedFilePath != null); Debug.Assert(sourceFiles[i].IsInputRedirected || PathUtilities.IsAbsolute(normalizedFilePath)); if (!uniqueFilePaths.Add(normalizedFilePath)) { // warning CS2002: Source file '{0}' specified multiple times diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded, Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath))); trees[i] = null; } } if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger is object); foreach (var path in uniqueFilePaths) { touchedFilesLogger.AddRead(path); } } var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default; var appConfigPath = this.Arguments.AppConfigPath; if (appConfigPath != null) { try { using (var appConfigStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read)) { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream); } if (touchedFilesLogger != null) { touchedFilesLogger.AddRead(appConfigPath); } } catch (Exception ex) { diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message)); } } var xmlFileResolver = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger); var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray<string>.Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger); MetadataReferenceResolver referenceDirectiveResolver; var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null)) { return null; } var loggingFileSystem = new LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory); var optionsProvider = new CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalConfigOptions); return CSharpCompilation.Create( Arguments.CompilationName, trees.WhereNotNull(), resolvedReferences, Arguments.CompilationOptions .WithMetadataReferenceResolver(referenceDirectiveResolver) .WithAssemblyIdentityComparer(assemblyIdentityComparer) .WithXmlReferenceResolver(xmlFileResolver) .WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)) .WithSourceReferenceResolver(sourceFileResolver) .WithSyntaxTreeOptionsProvider(optionsProvider)); } private SyntaxTree? ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, ref bool addedDiagnostics, CommandLineSourceFile file, DiagnosticBag diagnostics, out string? normalizedFilePath) { var fileDiagnostics = new List<DiagnosticInfo>(); var content = TryReadFileContent(file, fileDiagnostics, out normalizedFilePath); if (content == null) { foreach (var info in fileDiagnostics) { diagnostics.Add(MessageProvider.CreateDiagnostic(info)); } fileDiagnostics.Clear(); addedDiagnostics = true; return null; } else { Debug.Assert(fileDiagnostics.Count == 0); return ParseFile(parseOptions, scriptParseOptions, content, file); } } private static SyntaxTree ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, SourceText content, CommandLineSourceFile file) { var tree = SyntaxFactory.ParseSyntaxTree( content, file.IsScript ? scriptParseOptions : parseOptions, file.Path); // prepopulate line tables. // we will need line tables anyways and it is better to not wait until we are in emit // where things run sequentially. bool isHiddenDummy; tree.GetMappedLineSpanAndVisibility(default(TextSpan), out isHiddenDummy); return tree; } /// <summary> /// Given a compilation and a destination directory, determine three names: /// 1) The name with which the assembly should be output. /// 2) The path of the assembly/module file. /// 3) The path of the pdb file. /// /// When csc produces an executable, but the name of the resulting assembly /// is not specified using the "/out" switch, the name is taken from the name /// of the file (note: file, not class) containing the assembly entrypoint /// (as determined by binding and the "/main" switch). /// /// For example, if the command is "csc /target:exe a.cs b.cs" and b.cs contains the /// entrypoint, then csc will produce "b.exe" and "b.pdb" in the output directory, /// with assembly name "b" and module name "b.exe" embedded in the file. /// </summary> protected override string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken) { if (Arguments.OutputFileName is object) { return Arguments.OutputFileName; } Debug.Assert(Arguments.CompilationOptions.OutputKind.IsApplication()); var comp = (CSharpCompilation)compilation; Symbol? entryPoint = comp.ScriptClass; if (entryPoint is null) { var method = comp.GetEntryPoint(cancellationToken); if (method is object) { entryPoint = method.PartialImplementationPart ?? method; } else { // no entrypoint found - an error will be reported and the compilation won't be emitted return "error"; } } string entryPointFileName = PathUtilities.GetFileName(entryPoint.Locations.First().SourceTree!.FilePath); return Path.ChangeExtension(entryPointFileName, ".exe"); } internal override bool SuppressDefaultResponseFile(IEnumerable<string> args) { return args.Any(arg => new[] { "/noconfig", "-noconfig" }.Contains(arg.ToLowerInvariant())); } /// <summary> /// Print compiler logo /// </summary> /// <param name="consoleOutput"></param> public override void PrintLogo(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()); consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine2, Culture)); consoleOutput.WriteLine(); } public override void PrintLangVersions(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LangVersions, Culture)); var defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); var latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); foreach (var v in (LanguageVersion[])Enum.GetValues(typeof(LanguageVersion))) { if (v == defaultVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (default)"); } else if (v == latestVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)"); } else { consoleOutput.WriteLine(v.ToDisplayString()); } } consoleOutput.WriteLine(); } internal override Type Type { get { // We do not use this.GetType() so that we don't break mock subtypes return typeof(CSharpCompiler); } } internal override string GetToolName() { return ErrorFacts.GetMessage(MessageID.IDS_ToolName, Culture); } /// <summary> /// Print Commandline help message (up to 80 English characters per line) /// </summary> /// <param name="consoleOutput"></param> public override void PrintHelp(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_CSCHelp, Culture)); } protected override bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code) { return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); } protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { Arguments.ResolveAnalyzersFromArguments(LanguageNames.CSharp, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, out analyzers, out generators); } protected override void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics) { foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot().GetDirectives( d => d.IsActive && !d.HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia)) { var path = (string?)directive.File.Value; if (path == null) { continue; } string? resolvedPath = resolver.ResolveReference(path, tree.FilePath); if (resolvedPath == null) { diagnostics.Add( MessageProvider.CreateDiagnostic( (int)ErrorCode.ERR_NoSourceFile, directive.File.GetLocation(), path, CSharpResources.CouldNotFindFile)); continue; } embeddedFiles.Add(resolvedPath); } } private protected override GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts) { return CSharpGeneratorDriver.Create(generators, additionalTexts, (CSharpParseOptions)parseOptions, analyzerConfigOptionsProvider); } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Test/CommandLine/CommandLineTestBase.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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class CommandLineTestBase : CSharpTestBase { public string WorkingDirectory { get; } public string SdkDirectory { get; } public string MscorlibFullPath { get; } public CommandLineTestBase() { WorkingDirectory = TempRoot.Root; SdkDirectory = getSdkDirectory(Temp); MscorlibFullPath = Path.Combine(SdkDirectory, "mscorlib.dll"); // This will return a directory which contains mscorlib for use in the compiler instances created for // this set of tests string getSdkDirectory(TempRoot temp) { if (ExecutionConditionUtil.IsCoreClr) { var dir = temp.CreateDirectory(); File.WriteAllBytes(Path.Combine(dir.Path, "mscorlib.dll"), ResourcesNet461.mscorlib); return dir.Path; } return RuntimeEnvironment.GetRuntimeDirectory(); } } internal CSharpCommandLineArguments DefaultParse(IEnumerable<string> args, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } internal MockCSharpCompiler CreateCSharpCompiler(string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) { return CreateCSharpCompiler(null, WorkingDirectory, args, analyzers, generators, loader); } internal MockCSharpCompiler CreateCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) { var buildPaths = RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory: SdkDirectory); return new MockCSharpCompiler(responseFile, buildPaths, args, analyzers, generators, loader); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class CommandLineTestBase : CSharpTestBase { public string WorkingDirectory { get; } public string SdkDirectory { get; } public string MscorlibFullPath { get; } public CommandLineTestBase() { WorkingDirectory = TempRoot.Root; SdkDirectory = getSdkDirectory(Temp); MscorlibFullPath = Path.Combine(SdkDirectory, "mscorlib.dll"); // This will return a directory which contains mscorlib for use in the compiler instances created for // this set of tests string getSdkDirectory(TempRoot temp) { if (ExecutionConditionUtil.IsCoreClr) { var dir = temp.CreateDirectory(); File.WriteAllBytes(Path.Combine(dir.Path, "mscorlib.dll"), ResourcesNet461.mscorlib); return dir.Path; } return RuntimeEnvironment.GetRuntimeDirectory(); } } internal CSharpCommandLineArguments DefaultParse(IEnumerable<string> args, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } internal MockCSharpCompiler CreateCSharpCompiler(string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null, GeneratorDriverCache driverCache = null) { return CreateCSharpCompiler(null, WorkingDirectory, args, analyzers, generators, loader, driverCache); } internal MockCSharpCompiler CreateCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null, GeneratorDriverCache driverCache = null) { var buildPaths = RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory: SdkDirectory); return new MockCSharpCompiler(responseFile, buildPaths, args, analyzers, generators, loader, driverCache); } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./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", 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); }; } [Fact] public void Compiler_Uses_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // with no cache, we'll see the callback execute multiple times RunWithNoCache(); Assert.Equal(1, sourceCallbackCount); RunWithNoCache(); Assert.Equal(2, sourceCallbackCount); RunWithNoCache(); Assert.Equal(3, sourceCallbackCount); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithNoCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, analyzers: null); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Doesnt_Use_Cache_From_Other_Compilation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); // now emulate a new compilation, and check we were invoked, but only once RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); // now re-run our first compilation RunWithCache("1.dll"); Assert.Equal(2, sourceCallbackCount); // a new one RunWithCache("3.dll"); Assert.Equal(3, sourceCallbackCount); // and another old one RunWithCache("2.dll"); Assert.Equal(3, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(3, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache(string outputPath) => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:" + outputPath }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Can_Disable_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // now re-run with the cache disabled sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); // now clear the cache as well as disabling, and verify we don't put any entries into it either cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithCacheDisabled() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:disable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Adding_Or_Removing_A_Generator_Invalidates_Cache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; int sourceCallbackCount2 = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); var generator2 = new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount2++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); // this seems counterintuitive, but when the only thing to change is the generator, we end up back at the state of the project when // we just ran a single generator. Thus we already have an entry in the cache we can use (the one created by the original call to // RunWithOneGenerator above) meaning we can use the previously cached results and not run. RunWithOneGenerator(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); void RunWithOneGenerator() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithTwoGenerators() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator(), generator2.AsSourceGenerator() }, driverCache: cache, analyzers: null); } 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, GeneratorDriverCache driverCache = 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(), driverCache: driverCache); 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,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal readonly struct BuildPaths { /// <summary> /// The path which contains the compiler binaries and response files. /// </summary> internal string ClientDirectory { get; } /// <summary> /// The path in which the compilation takes place. /// </summary> internal string WorkingDirectory { get; } /// <summary> /// The path which contains mscorlib. This can be null when specified by the user or running in a /// CoreClr environment. /// </summary> internal string? SdkDirectory { get; } /// <summary> /// The temporary directory a compilation should use instead of <see cref="Path.GetTempPath"/>. The latter /// relies on global state individual compilations should ignore. /// </summary> internal string? TempDirectory { get; } internal BuildPaths(string clientDir, string workingDir, string? sdkDir, string? tempDir) { ClientDirectory = clientDir; WorkingDirectory = workingDir; SdkDirectory = sdkDir; TempDirectory = tempDir; } } /// <summary> /// Base class for csc.exe, csi.exe, vbc.exe and vbi.exe implementations. /// </summary> internal abstract partial class CommonCompiler { internal const int Failed = 1; internal const int Succeeded = 0; /// <summary> /// Fallback encoding that is lazily retrieved if needed. If <see cref="EncodedStringText.CreateFallbackEncoding"/> is /// evaluated and stored, the value is used if a PDB is created for this compilation. /// </summary> private readonly Lazy<Encoding> _fallbackEncoding = new Lazy<Encoding>(EncodedStringText.CreateFallbackEncoding); public CommonMessageProvider MessageProvider { get; } public CommandLineArguments Arguments { get; } public IAnalyzerAssemblyLoader AssemblyLoader { get; private set; } public abstract DiagnosticFormatter DiagnosticFormatter { get; } /// <summary> /// The set of source file paths that are in the set of embedded paths. /// This is used to prevent reading source files that are embedded twice. /// </summary> public IReadOnlySet<string> EmbeddedSourcePaths { get; } /// <summary> /// The <see cref="ICommonCompilerFileSystem"/> used to access the file system inside this instance. /// </summary> internal ICommonCompilerFileSystem FileSystem { get; set; } = StandardFileSystem.Instance; private readonly HashSet<Diagnostic> _reportedDiagnostics = new HashSet<Diagnostic>(); public abstract Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLoggerOpt, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions); public abstract void PrintLogo(TextWriter consoleOutput); public abstract void PrintHelp(TextWriter consoleOutput); public abstract void PrintLangVersions(TextWriter consoleOutput); /// <summary> /// Print compiler version /// </summary> /// <param name="consoleOutput"></param> public virtual void PrintVersion(TextWriter consoleOutput) { consoleOutput.WriteLine(GetCompilerVersion()); } protected abstract bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code); protected abstract void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators); public CommonCompiler(CommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader) { IEnumerable<string> allArgs = args; Debug.Assert(null == responseFile || PathUtilities.IsAbsolute(responseFile)); if (!SuppressDefaultResponseFile(args) && File.Exists(responseFile)) { allArgs = new[] { "@" + responseFile }.Concat(allArgs); } this.Arguments = parser.Parse(allArgs, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, additionalReferenceDirectories); this.MessageProvider = parser.MessageProvider; this.AssemblyLoader = assemblyLoader; this.EmbeddedSourcePaths = GetEmbeddedSourcePaths(Arguments); if (Arguments.ParseOptions.Features.ContainsKey("debug-determinism")) { EmitDeterminismKey(Arguments, args, buildPaths.WorkingDirectory, parser); } } internal abstract bool SuppressDefaultResponseFile(IEnumerable<string> args); /// <summary> /// The type of the compiler class for version information in /help and /version. /// We don't simply use this.GetType() because that would break mock subclasses. /// </summary> internal abstract Type Type { get; } /// <summary> /// The version of this compiler with commit hash, used in logo and /version output. /// </summary> internal string GetCompilerVersion() { return GetProductVersion(Type); } internal static string GetProductVersion(Type type) { string? assemblyVersion = GetInformationalVersionWithoutHash(type); string? hash = GetShortCommitHash(type); return $"{assemblyVersion} ({hash})"; } [return: NotNullIfNotNull("hash")] internal static string? ExtractShortCommitHash(string? hash) { // leave "<developer build>" alone, but truncate SHA to 8 characters if (hash != null && hash.Length >= 8 && hash[0] != '<') { return hash.Substring(0, 8); } return hash; } private static string? GetInformationalVersionWithoutHash(Type type) { // The attribute stores a SemVer2-formatted string: `A.B.C(-...)?(+...)?` // We remove the section after the + (if any is present) return type.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+')[0]; } private static string? GetShortCommitHash(Type type) { var hash = type.Assembly.GetCustomAttribute<CommitHashAttribute>()?.Hash; return ExtractShortCommitHash(hash); } /// <summary> /// Tool name used, along with assembly version, for error logging. /// </summary> internal abstract string GetToolName(); /// <summary> /// Tool version identifier used for error logging. /// </summary> internal Version? GetAssemblyVersion() { return Type.GetTypeInfo().Assembly.GetName().Version; } internal string GetCultureName() { return Culture.Name; } internal virtual Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return (path, properties) => { var peStream = FileSystem.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read); return MetadataReference.CreateFromFile(peStream, path, properties); }; } internal virtual MetadataReferenceResolver GetCommandLineMetadataReferenceResolver(TouchedFileLogger? loggerOpt) { var pathResolver = new CompilerRelativePathResolver(FileSystem, Arguments.ReferencePaths, Arguments.BaseDirectory!); return new LoggingMetadataFileReferenceResolver(pathResolver, GetMetadataProvider(), loggerOpt); } /// <summary> /// Resolves metadata references stored in command line arguments and reports errors for those that can't be resolved. /// </summary> internal List<MetadataReference> ResolveMetadataReferences( List<DiagnosticInfo> diagnostics, TouchedFileLogger? touchedFiles, out MetadataReferenceResolver referenceDirectiveResolver) { var commandLineReferenceResolver = GetCommandLineMetadataReferenceResolver(touchedFiles); List<MetadataReference> resolved = new List<MetadataReference>(); Arguments.ResolveMetadataReferences(commandLineReferenceResolver, diagnostics, this.MessageProvider, resolved); if (Arguments.IsScriptRunner) { referenceDirectiveResolver = commandLineReferenceResolver; } else { // when compiling into an assembly (csc/vbc) we only allow #r that match references given on command line: referenceDirectiveResolver = new ExistingReferencesResolver(commandLineReferenceResolver, resolved.ToImmutableArray()); } return resolved; } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics) { return TryReadFileContent(file, diagnostics, out _); } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <param name="normalizedFilePath">If given <paramref name="file"/> opens successfully, set to normalized absolute path of the file, null otherwise.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics, out string? normalizedFilePath) { var filePath = file.Path; try { if (file.IsInputRedirected) { using var data = Console.OpenStandardInput(); normalizedFilePath = filePath; return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } else { using var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedFilePath); return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } } catch (Exception e) { diagnostics.Add(ToFileReadDiagnostics(this.MessageProvider, e, filePath)); normalizedFilePath = null; return null; } } /// <summary> /// Read all analyzer config files from the given paths. /// </summary> internal bool TryGetAnalyzerConfigSet( ImmutableArray<string> analyzerConfigPaths, DiagnosticBag diagnostics, [NotNullWhen(true)] out AnalyzerConfigSet? analyzerConfigSet) { var configs = ArrayBuilder<AnalyzerConfig>.GetInstance(analyzerConfigPaths.Length); var processedDirs = PooledHashSet<string>.GetInstance(); foreach (var configPath in analyzerConfigPaths) { // The editorconfig spec requires all paths use '/' as the directory separator. // Since no known system allows directory separators as part of the file name, // we can replace every instance of the directory separator with a '/' string? fileContent = TryReadFileContent(configPath, diagnostics, out string? normalizedPath); if (fileContent is null) { // Error reading a file. Bail out and report error. break; } Debug.Assert(normalizedPath is object); var directory = Path.GetDirectoryName(normalizedPath) ?? normalizedPath; var editorConfig = AnalyzerConfig.Parse(fileContent, normalizedPath); if (!editorConfig.IsGlobal) { if (processedDirs.Contains(directory)) { diagnostics.Add(Diagnostic.Create( MessageProvider, MessageProvider.ERR_MultipleAnalyzerConfigsInSameDir, directory)); break; } processedDirs.Add(directory); } configs.Add(editorConfig); } processedDirs.Free(); if (diagnostics.HasAnyErrors()) { configs.Free(); analyzerConfigSet = null; return false; } analyzerConfigSet = AnalyzerConfigSet.Create(configs, out var setDiagnostics); diagnostics.AddRange(setDiagnostics); return true; } /// <summary> /// Returns the fallback encoding for parsing source files, if used, or null /// if not used /// </summary> internal Encoding? GetFallbackEncoding() { if (_fallbackEncoding.IsValueCreated) { return _fallbackEncoding.Value; } return null; } /// <summary> /// Read a UTF-8 encoded file and return the text as a string. /// </summary> private string? TryReadFileContent(string filePath, DiagnosticBag diagnostics, out string? normalizedPath) { try { var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedPath); using (var reader = new StreamReader(data, Encoding.UTF8)) { return reader.ReadToEnd(); } } catch (Exception e) { diagnostics.Add(Diagnostic.Create(ToFileReadDiagnostics(MessageProvider, e, filePath))); normalizedPath = null; return null; } } private Stream OpenFileForReadWithSmallBufferOptimization(string filePath, out string normalizedFilePath) // PERF: Using a very small buffer size for the FileStream opens up an optimization within EncodedStringText/EmbeddedText where // we read the entire FileStream into a byte array in one shot. For files that are actually smaller than the buffer // size, FileStream.Read still allocates the internal buffer. => FileSystem.OpenFileEx( filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 1, options: FileOptions.None, out normalizedFilePath); internal EmbeddedText? TryReadEmbeddedFileContent(string filePath, DiagnosticBag diagnostics) { try { using (var stream = OpenFileForReadWithSmallBufferOptimization(filePath, out _)) { const int LargeObjectHeapLimit = 80 * 1024; if (stream.Length < LargeObjectHeapLimit) { ArraySegment<byte> bytes; if (EncodedStringText.TryGetBytesFromStream(stream, out bytes)) { return EmbeddedText.FromBytes(filePath, bytes, Arguments.ChecksumAlgorithm); } } return EmbeddedText.FromStream(filePath, stream, Arguments.ChecksumAlgorithm); } } catch (Exception e) { diagnostics.Add(MessageProvider.CreateDiagnostic(ToFileReadDiagnostics(this.MessageProvider, e, filePath))); return null; } } private ImmutableArray<EmbeddedText?> AcquireEmbeddedTexts(Compilation compilation, DiagnosticBag diagnostics) { Debug.Assert(compilation.Options.SourceReferenceResolver is object); if (Arguments.EmbeddedFiles.IsEmpty) { return ImmutableArray<EmbeddedText?>.Empty; } var embeddedTreeMap = new Dictionary<string, SyntaxTree>(Arguments.EmbeddedFiles.Length); var embeddedFileOrderedSet = new OrderedSet<string>(Arguments.EmbeddedFiles.Select(e => e.Path)); foreach (var tree in compilation.SyntaxTrees) { // Skip trees that will not have their text embedded. if (!EmbeddedSourcePaths.Contains(tree.FilePath)) { continue; } // Skip trees with duplicated paths. (VB allows this and "first tree wins" is same as PDB emit policy.) if (embeddedTreeMap.ContainsKey(tree.FilePath)) { continue; } // map embedded file path to corresponding source tree embeddedTreeMap.Add(tree.FilePath, tree); // also embed the text of any #line directive targets of embedded tree ResolveEmbeddedFilesFromExternalSourceDirectives(tree, compilation.Options.SourceReferenceResolver, embeddedFileOrderedSet, diagnostics); } var embeddedTextBuilder = ImmutableArray.CreateBuilder<EmbeddedText?>(embeddedFileOrderedSet.Count); foreach (var path in embeddedFileOrderedSet) { SyntaxTree? tree; EmbeddedText? text; if (embeddedTreeMap.TryGetValue(path, out tree)) { text = EmbeddedText.FromSource(path, tree.GetText()); Debug.Assert(text != null); } else { text = TryReadEmbeddedFileContent(path, diagnostics); Debug.Assert(text != null || diagnostics.HasAnyErrors()); } // We can safely add nulls because result will be ignored if any error is produced. // This allows the MoveToImmutable to work below in all cases. embeddedTextBuilder.Add(text); } return embeddedTextBuilder.MoveToImmutable(); } protected abstract void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics); private static IReadOnlySet<string> GetEmbeddedSourcePaths(CommandLineArguments arguments) { if (arguments.EmbeddedFiles.IsEmpty) { return SpecializedCollections.EmptyReadOnlySet<string>(); } // Note that we require an exact match between source and embedded file paths (case-sensitive // and without normalization). If two files are the same but spelled differently, they will // be handled as separate files, meaning the embedding pass will read the content a second // time. This can also lead to more than one document entry in the PDB for the same document // if the PDB document de-duping policy in emit (normalize + case-sensitive in C#, // normalize + case-insensitive in VB) is not enough to converge them. var set = new HashSet<string>(arguments.EmbeddedFiles.Select(f => f.Path)); set.IntersectWith(arguments.SourceFiles.Select(f => f.Path)); return SpecializedCollections.StronglyTypedReadOnlySet(set); } internal static DiagnosticInfo ToFileReadDiagnostics(CommonMessageProvider messageProvider, Exception e, string filePath) { DiagnosticInfo diagnosticInfo; if (e is FileNotFoundException || e is DirectoryNotFoundException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_FileNotFound, filePath); } else if (e is InvalidDataException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_BinaryFile, filePath); } else { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_NoSourceFile, filePath, e.Message); } return diagnosticInfo; } /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<Diagnostic> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) { bool hasErrors = false; foreach (var diag in diagnostics) { reportDiagnostic(diag, compilation == null ? null : diag.GetSuppressionInfo(compilation)); } return hasErrors; // Local functions void reportDiagnostic(Diagnostic diag, SuppressionInfo? suppressionInfo) { if (_reportedDiagnostics.Contains(diag)) { // TODO: This invariant fails (at least) in the case where we see a member declaration "x = 1;". // First we attempt to parse a member declaration starting at "x". When we see the "=", we // create an IncompleteMemberSyntax with return type "x" and an error at the location of the "x". // Then we parse a member declaration starting at "=". This is an invalid member declaration start // so we attach an error to the "=" and attach it (plus following tokens) to the IncompleteMemberSyntax // we previously created. //this assert isn't valid if we change the design to not bail out after each phase. //System.Diagnostics.Debug.Assert(diag.Severity != DiagnosticSeverity.Error); return; } else if (diag.Severity == DiagnosticSeverity.Hidden) { // Not reported from the command-line compiler. return; } // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics should not be reported on the console output. errorLoggerOpt?.LogDiagnostic(diag, suppressionInfo); // If the diagnostic was suppressed by one or more DiagnosticSuppressor(s), then we report info diagnostics for each suppression // so that the suppression information is available in the binary logs and verbose build logs. if (diag.ProgrammaticSuppressionInfo != null) { foreach (var (id, justification) in diag.ProgrammaticSuppressionInfo.Suppressions) { var suppressionDiag = new SuppressionDiagnostic(diag, id, justification); if (_reportedDiagnostics.Add(suppressionDiag)) { PrintError(suppressionDiag, consoleOutput); } } _reportedDiagnostics.Add(diag); return; } if (diag.IsSuppressed) { return; } // Diagnostics that aren't suppressed will be reported to the console output and, if they are errors, // they should fail the run if (diag.Severity == DiagnosticSeverity.Error) { hasErrors = true; } PrintError(diag, consoleOutput); _reportedDiagnostics.Add(diag); } } /// <summary>Returns true if there were any errors, false otherwise.</summary> private bool ReportDiagnostics(DiagnosticBag diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.ToReadOnly(), consoleOutput, errorLoggerOpt, compilation); /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<DiagnosticInfo> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.Select(info => Diagnostic.Create(info)), consoleOutput, errorLoggerOpt, compilation); /// <summary> /// Returns true if there are any error diagnostics in the bag which cannot be suppressed and /// are guaranteed to break the build. /// Only diagnostics which have default severity error and are tagged as NotConfigurable fall in this bucket. /// This includes all compiler error diagnostics and specific analyzer error diagnostics that are marked as not configurable by the analyzer author. /// </summary> internal static bool HasUnsuppressableErrors(DiagnosticBag diagnostics) { foreach (var diag in diagnostics.AsEnumerable()) { if (diag.IsUnsuppressableError()) { return true; } } return false; } /// <summary> /// Returns true if the bag has any diagnostics with effective Severity=Error. Also returns true for warnings or informationals /// or warnings promoted to error via /warnaserror which are not suppressed. /// </summary> internal static bool HasUnsuppressedErrors(DiagnosticBag diagnostics) { foreach (Diagnostic diagnostic in diagnostics.AsEnumerable()) { if (diagnostic.IsUnsuppressedError) { return true; } } return false; } protected virtual void PrintError(Diagnostic diagnostic, TextWriter consoleOutput) { consoleOutput.WriteLine(DiagnosticFormatter.Format(diagnostic, Culture)); } public SarifErrorLogger? GetErrorLogger(TextWriter consoleOutput, CancellationToken cancellationToken) { Debug.Assert(Arguments.ErrorLogOptions?.Path != null); var diagnostics = DiagnosticBag.GetInstance(); var errorLog = OpenFile(Arguments.ErrorLogOptions.Path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); SarifErrorLogger? logger; if (errorLog == null) { Debug.Assert(diagnostics.HasAnyErrors()); logger = null; } else { string toolName = GetToolName(); string compilerVersion = GetCompilerVersion(); Version assemblyVersion = GetAssemblyVersion() ?? new Version(); if (Arguments.ErrorLogOptions.SarifVersion == SarifVersion.Sarif1) { logger = new SarifV1ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } else { logger = new SarifV2ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } } ReportDiagnostics(diagnostics.ToReadOnlyAndFree(), consoleOutput, errorLoggerOpt: logger, compilation: null); return logger; } /// <summary> /// csc.exe and vbc.exe entry point. /// </summary> public virtual int Run(TextWriter consoleOutput, CancellationToken cancellationToken = default) { var saveUICulture = CultureInfo.CurrentUICulture; SarifErrorLogger? errorLogger = null; try { // Messages from exceptions can be used as arguments for errors and they are often localized. // Ensure they are localized to the right language. var culture = this.Culture; if (culture != null) { CultureInfo.CurrentUICulture = culture; } if (Arguments.ErrorLogOptions?.Path != null) { errorLogger = GetErrorLogger(consoleOutput, cancellationToken); if (errorLogger == null) { return Failed; } } return RunCore(consoleOutput, errorLogger, cancellationToken); } catch (OperationCanceledException) { var errorCode = MessageProvider.ERR_CompileCancelled; if (errorCode > 0) { var diag = new DiagnosticInfo(MessageProvider, errorCode); ReportDiagnostics(new[] { diag }, consoleOutput, errorLogger, compilation: null); } return Failed; } finally { CultureInfo.CurrentUICulture = saveUICulture; errorLogger?.Dispose(); } } /// <summary> /// Perform source generation, if the compiler supports it. /// </summary> /// <param name="input">The compilation before any source generation has occurred.</param> /// <param name="parseOptions">The <see cref="ParseOptions"/> to use when parsing any generated sources.</param> /// <param name="generators">The generators to run</param> /// <param name="analyzerConfigOptionsProvider">A provider that returns analyzer config options</param> /// <param name="additionalTexts">Any additional texts that should be passed to the generators when run.</param> /// <param name="generatorDiagnostics">Any diagnostics that were produced during generation</param> /// <returns>A compilation that represents the original compilation with any additional, generated texts added to it.</returns> private protected virtual Compilation RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts, DiagnosticBag generatorDiagnostics) { return input; } private int RunCore(TextWriter consoleOutput, ErrorLogger? errorLogger, CancellationToken cancellationToken) { Debug.Assert(!Arguments.IsScriptRunner); cancellationToken.ThrowIfCancellationRequested(); if (Arguments.DisplayVersion) { PrintVersion(consoleOutput); return Succeeded; } if (Arguments.DisplayLangVersions) { PrintLangVersions(consoleOutput); return Succeeded; } if (Arguments.DisplayLogo) { PrintLogo(consoleOutput); } if (Arguments.DisplayHelp) { PrintHelp(consoleOutput); return Succeeded; } if (ReportDiagnostics(Arguments.Errors, consoleOutput, errorLogger, compilation: null)) { return Failed; } var touchedFilesLogger = (Arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null; var diagnostics = DiagnosticBag.GetInstance(); AnalyzerConfigSet? analyzerConfigSet = null; ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions = default; AnalyzerConfigOptionsResult globalConfigOptions = default; if (Arguments.AnalyzerConfigPaths.Length > 0) { if (!TryGetAnalyzerConfigSet(Arguments.AnalyzerConfigPaths, diagnostics, out analyzerConfigSet)) { var hadErrors = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null); Debug.Assert(hadErrors); return Failed; } globalConfigOptions = analyzerConfigSet.GlobalConfigOptions; sourceFileAnalyzerConfigOptions = Arguments.SourceFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var sourceFileAnalyzerConfigOption in sourceFileAnalyzerConfigOptions) { diagnostics.AddRange(sourceFileAnalyzerConfigOption.Diagnostics); } } Compilation? compilation = CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, sourceFileAnalyzerConfigOptions, globalConfigOptions); if (compilation == null) { return Failed; } var diagnosticInfos = new List<DiagnosticInfo>(); ResolveAnalyzersFromArguments(diagnosticInfos, MessageProvider, Arguments.SkipAnalyzers, out var analyzers, out var generators); var additionalTextFiles = ResolveAdditionalFilesFromArguments(diagnosticInfos, MessageProvider, touchedFilesLogger); if (ReportDiagnostics(diagnosticInfos, consoleOutput, errorLogger, compilation)) { return Failed; } ImmutableArray<EmbeddedText?> embeddedTexts = AcquireEmbeddedTexts(compilation, diagnostics); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation)) { return Failed; } var additionalTexts = ImmutableArray<AdditionalText>.CastUp(additionalTextFiles); CompileAndEmit( touchedFilesLogger, ref compilation, analyzers, generators, additionalTexts, analyzerConfigSet, sourceFileAnalyzerConfigOptions, embeddedTexts, diagnostics, cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out var analyzerDriver); // At this point analyzers are already complete in which case this is a no-op. Or they are // still running because the compilation failed before all of the compilation events were // raised. In the latter case the driver, and all its associated state, will be waiting around // for events that are never coming. Cancel now and let the clean up process begin. if (analyzerCts != null) { analyzerCts.Cancel(); } var exitCode = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation) ? Failed : Succeeded; // The act of reporting errors can cause more errors to appear in // additional files due to forcing all additional files to fetch text foreach (var additionalFile in additionalTextFiles) { if (ReportDiagnostics(additionalFile.Diagnostics, consoleOutput, errorLogger, compilation)) { exitCode = Failed; } } diagnostics.Free(); if (reportAnalyzer) { Debug.Assert(analyzerDriver is object); ReportAnalyzerExecutionTime(consoleOutput, analyzerDriver, Culture, compilation.Options.ConcurrentBuild); } return exitCode; } private static CompilerAnalyzerConfigOptionsProvider UpdateAnalyzerConfigOptionsProvider( CompilerAnalyzerConfigOptionsProvider existing, IEnumerable<SyntaxTree> syntaxTrees, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<AdditionalText> additionalFiles = default, ImmutableArray<AnalyzerConfigOptionsResult> additionalFileOptions = default) { var builder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); int i = 0; foreach (var syntaxTree in syntaxTrees) { var options = sourceFileAnalyzerConfigOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(syntaxTree) == CompilerAnalyzerConfigOptions.Empty); builder.Add(syntaxTree, new CompilerAnalyzerConfigOptions(options)); } i++; } if (!additionalFiles.IsDefault) { for (i = 0; i < additionalFiles.Length; i++) { var options = additionalFileOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(additionalFiles[i]) == CompilerAnalyzerConfigOptions.Empty); builder.Add(additionalFiles[i], new CompilerAnalyzerConfigOptions(options)); } } } return existing.WithAdditionalTreeOptions(builder.ToImmutable()); } /// <summary> /// Perform all the work associated with actual compilation /// (parsing, binding, compile, emit), resulting in diagnostics /// and analyzer output. /// </summary> private void CompileAndEmit( TouchedFileLogger? touchedFilesLogger, ref Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<ISourceGenerator> generators, ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigSet? analyzerConfigSet, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<EmbeddedText?> embeddedTexts, DiagnosticBag diagnostics, CancellationToken cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out AnalyzerDriver? analyzerDriver) { analyzerCts = null; reportAnalyzer = false; analyzerDriver = null; // Print the diagnostics produced during the parsing stage and exit if there were any errors. compilation.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } DiagnosticBag? analyzerExceptionDiagnostics = null; if (!analyzers.IsEmpty || !generators.IsEmpty) { var analyzerConfigProvider = CompilerAnalyzerConfigOptionsProvider.Empty; if (Arguments.AnalyzerConfigPaths.Length > 0) { Debug.Assert(analyzerConfigSet is object); analyzerConfigProvider = analyzerConfigProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(analyzerConfigSet.GetOptionsForSourcePath(string.Empty).AnalyzerOptions)); // TODO(https://github.com/dotnet/roslyn/issues/31916): The compiler currently doesn't support // configuring diagnostic reporting on additional text files individually. ImmutableArray<AnalyzerConfigOptionsResult> additionalFileAnalyzerOptions = additionalTextFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var result in additionalFileAnalyzerOptions) { diagnostics.AddRange(result.Diagnostics); } analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, compilation.SyntaxTrees, sourceFileAnalyzerConfigOptions, additionalTextFiles, additionalFileAnalyzerOptions); } if (!generators.IsEmpty) { // At this point we have a compilation with nothing yet computed. // We pass it to the generators, which will realize any symbols they require. compilation = RunGenerators(compilation, Arguments.ParseOptions, generators, analyzerConfigProvider, additionalTextFiles, diagnostics); bool hasAnalyzerConfigs = !Arguments.AnalyzerConfigPaths.IsEmpty; bool hasGeneratedOutputPath = !string.IsNullOrWhiteSpace(Arguments.GeneratedFilesOutputDirectory); var generatedSyntaxTrees = compilation.SyntaxTrees.Skip(Arguments.SourceFiles.Length).ToList(); var analyzerOptionsBuilder = hasAnalyzerConfigs ? ArrayBuilder<AnalyzerConfigOptionsResult>.GetInstance(generatedSyntaxTrees.Count) : null; var embeddedTextBuilder = ArrayBuilder<EmbeddedText>.GetInstance(generatedSyntaxTrees.Count); try { foreach (var tree in generatedSyntaxTrees) { Debug.Assert(!string.IsNullOrWhiteSpace(tree.FilePath)); cancellationToken.ThrowIfCancellationRequested(); var sourceText = tree.GetText(cancellationToken); // embed the generated text and get analyzer options for it if needed embeddedTextBuilder.Add(EmbeddedText.FromSource(tree.FilePath, sourceText)); if (analyzerOptionsBuilder is object) { analyzerOptionsBuilder.Add(analyzerConfigSet!.GetOptionsForSourcePath(tree.FilePath)); } // write out the file if we have an output path if (hasGeneratedOutputPath) { var path = Path.Combine(Arguments.GeneratedFilesOutputDirectory!, tree.FilePath); if (Directory.Exists(Arguments.GeneratedFilesOutputDirectory)) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); } var fileStream = OpenFile(path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (fileStream is object) { Debug.Assert(tree.Encoding is object); using var disposer = new NoThrowStreamDisposer(fileStream, path, diagnostics, MessageProvider); using var writer = new StreamWriter(fileStream, tree.Encoding); sourceText.Write(writer, cancellationToken); touchedFilesLogger?.AddWritten(path); } } } embeddedTexts = embeddedTexts.AddRange(embeddedTextBuilder); if (analyzerOptionsBuilder is object) { analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, generatedSyntaxTrees, analyzerOptionsBuilder.ToImmutable()); } } finally { analyzerOptionsBuilder?.Free(); embeddedTextBuilder.Free(); } } AnalyzerOptions analyzerOptions = CreateAnalyzerOptions( additionalTextFiles, analyzerConfigProvider); if (!analyzers.IsEmpty) { analyzerCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); analyzerExceptionDiagnostics = new DiagnosticBag(); // PERF: Avoid executing analyzers that report only Hidden and/or Info diagnostics, which don't appear in the build output. // 1. Always filter out 'Hidden' analyzer diagnostics in build. // 2. Filter out 'Info' analyzer diagnostics if they are not required to be logged in errorlog. var severityFilter = SeverityFilter.Hidden; if (Arguments.ErrorLogPath == null) severityFilter |= SeverityFilter.Info; analyzerDriver = AnalyzerDriver.CreateAndAttachToCompilation( compilation, analyzers, analyzerOptions, new AnalyzerManager(analyzers), analyzerExceptionDiagnostics.Add, Arguments.ReportAnalyzer, severityFilter, out compilation, analyzerCts.Token); reportAnalyzer = Arguments.ReportAnalyzer && !analyzers.IsEmpty; } } compilation.GetDiagnostics(CompilationStage.Declare, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } cancellationToken.ThrowIfCancellationRequested(); // Given a compilation and a destination directory, determine three names: // 1) The name with which the assembly should be output. // 2) The path of the assembly/module file (default = destination directory + compilation output name). // 3) The path of the pdb file (default = assembly/module path with ".pdb" extension). string outputName = GetOutputFileName(compilation, cancellationToken)!; var finalPeFilePath = Arguments.GetOutputFilePath(outputName); var finalPdbFilePath = Arguments.GetPdbFilePath(outputName); var finalXmlFilePath = Arguments.DocumentationPath; NoThrowStreamDisposer? sourceLinkStreamDisposerOpt = null; try { // NOTE: Unlike the PDB path, the XML doc path is not embedded in the assembly, so we don't need to pass it to emit. var emitOptions = Arguments.EmitOptions. WithOutputNameOverride(outputName). WithPdbFilePath(PathUtilities.NormalizePathPrefix(finalPdbFilePath, Arguments.PathMap)); // TODO(https://github.com/dotnet/roslyn/issues/19592): // This feature flag is being maintained until our next major release to avoid unnecessary // compat breaks with customers. if (Arguments.ParseOptions.Features.ContainsKey("pdb-path-determinism") && !string.IsNullOrEmpty(emitOptions.PdbFilePath)) { emitOptions = emitOptions.WithPdbFilePath(Path.GetFileName(emitOptions.PdbFilePath)); } if (Arguments.SourceLink != null) { var sourceLinkStreamOpt = OpenFile( Arguments.SourceLink, diagnostics, FileMode.Open, FileAccess.Read, FileShare.Read); if (sourceLinkStreamOpt != null) { sourceLinkStreamDisposerOpt = new NoThrowStreamDisposer( sourceLinkStreamOpt, Arguments.SourceLink, diagnostics, MessageProvider); } } // Need to ensure the PDB file path validation is done on the original path as that is the // file we will write out to disk, there is no guarantee that the file paths emitted into // the PE / PDB are valid file paths because pathmap can be used to create deliberately // illegal names if (!PathUtilities.IsValidFilePath(finalPdbFilePath)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.FTL_InvalidInputFileName, Location.None, finalPdbFilePath)); } var moduleBeingBuilt = compilation.CheckOptionsAndCreateModuleBuilder( diagnostics, Arguments.ManifestResources, emitOptions, debugEntryPoint: null, sourceLinkStream: sourceLinkStreamDisposerOpt?.Stream, embeddedTexts: embeddedTexts, testData: null, cancellationToken: cancellationToken); if (moduleBeingBuilt != null) { bool success; try { success = compilation.CompileMethods( moduleBeingBuilt, Arguments.EmitPdb, emitOptions.EmitMetadataOnly, emitOptions.EmitTestCoverageData, diagnostics, filterOpt: null, cancellationToken: cancellationToken); // Prior to generating the xml documentation file, // we apply programmatic suppressions for compiler warnings from diagnostic suppressors. // If there are still any unsuppressed errors or warnings escalated to errors // then we bail out from generating the documentation file. // This maintains the compiler invariant that xml documentation file should not be // generated in presence of diagnostics that break the build. if (analyzerDriver != null && !diagnostics.IsEmptyWithoutResolution) { analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { // NOTE: as native compiler does, we generate the documentation file // NOTE: 'in place', replacing the contents of the file if it exists NoThrowStreamDisposer? xmlStreamDisposerOpt = null; if (finalXmlFilePath != null) { var xmlStreamOpt = OpenFile(finalXmlFilePath, diagnostics, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (xmlStreamOpt == null) { return; } try { xmlStreamOpt.SetLength(0); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, finalXmlFilePath, diagnostics); return; } xmlStreamDisposerOpt = new NoThrowStreamDisposer( xmlStreamOpt, finalXmlFilePath, diagnostics, MessageProvider); } using (xmlStreamDisposerOpt) { using (var win32ResourceStreamOpt = GetWin32Resources(FileSystem, MessageProvider, Arguments, compilation, diagnostics)) { if (HasUnsuppressableErrors(diagnostics)) { return; } success = compilation.GenerateResourcesAndDocumentationComments( moduleBeingBuilt, xmlStreamDisposerOpt?.Stream, win32ResourceStreamOpt, useRawWin32Resources: false, emitOptions.OutputNameOverride, diagnostics, cancellationToken); } } if (xmlStreamDisposerOpt?.HasFailedToDispose == true) { return; } // only report unused usings if we have success. if (success) { compilation.ReportUnusedImports(diagnostics, cancellationToken); } } compilation.CompleteTrees(null); if (analyzerDriver != null) { // GetDiagnosticsAsync is called after ReportUnusedImports // since that method calls EventQueue.TryComplete. Without // TryComplete, we may miss diagnostics. var hostDiagnostics = analyzerDriver.GetDiagnosticsAsync(compilation).Result; diagnostics.AddRange(hostDiagnostics); if (!diagnostics.IsEmptyWithoutResolution) { // Apply diagnostic suppressions for analyzer and/or compiler diagnostics from diagnostic suppressors. analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } } } finally { moduleBeingBuilt.CompilationFinished(); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { var peStreamProvider = new CompilerEmitStreamProvider(this, finalPeFilePath); var pdbStreamProviderOpt = Arguments.EmitPdbFile ? new CompilerEmitStreamProvider(this, finalPdbFilePath) : null; string? finalRefPeFilePath = Arguments.OutputRefFilePath; var refPeStreamProviderOpt = finalRefPeFilePath != null ? new CompilerEmitStreamProvider(this, finalRefPeFilePath) : null; RSAParameters? privateKeyOpt = null; if (compilation.Options.StrongNameProvider != null && compilation.SignUsingBuilder && !compilation.Options.PublicSign) { privateKeyOpt = compilation.StrongNameKeys.PrivateKey; } // If we serialize to a PE stream we need to record the fallback encoding if it was used // so the compilation can be recreated. emitOptions = emitOptions.WithFallbackSourceFileEncoding(GetFallbackEncoding()); success = compilation.SerializeToPeStream( moduleBeingBuilt, peStreamProvider, refPeStreamProviderOpt, pdbStreamProviderOpt, rebuildData: null, testSymWriterFactory: null, diagnostics: diagnostics, emitOptions: emitOptions, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken); peStreamProvider.Close(diagnostics); refPeStreamProviderOpt?.Close(diagnostics); pdbStreamProviderOpt?.Close(diagnostics); if (success && touchedFilesLogger != null) { if (pdbStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalPdbFilePath); } if (refPeStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalRefPeFilePath!); } touchedFilesLogger.AddWritten(finalPeFilePath); } } } if (HasUnsuppressableErrors(diagnostics)) { return; } } finally { sourceLinkStreamDisposerOpt?.Dispose(); } if (sourceLinkStreamDisposerOpt?.HasFailedToDispose == true) { return; } cancellationToken.ThrowIfCancellationRequested(); if (analyzerExceptionDiagnostics != null) { diagnostics.AddRange(analyzerExceptionDiagnostics); if (HasUnsuppressableErrors(analyzerExceptionDiagnostics)) { return; } } cancellationToken.ThrowIfCancellationRequested(); if (!WriteTouchedFiles(diagnostics, touchedFilesLogger, finalXmlFilePath)) { return; } } // virtual for testing protected virtual Diagnostics.AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) => new Diagnostics.AnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); private bool WriteTouchedFiles(DiagnosticBag diagnostics, TouchedFileLogger? touchedFilesLogger, string? finalXmlFilePath) { if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger != null); if (finalXmlFilePath != null) { touchedFilesLogger.AddWritten(finalXmlFilePath); } string readFilesPath = Arguments.TouchedFilesPath + ".read"; string writtenFilesPath = Arguments.TouchedFilesPath + ".write"; var readStream = OpenFile(readFilesPath, diagnostics, mode: FileMode.OpenOrCreate); var writtenStream = OpenFile(writtenFilesPath, diagnostics, mode: FileMode.OpenOrCreate); if (readStream == null || writtenStream == null) { return false; } string? filePath = null; try { filePath = readFilesPath; using (var writer = new StreamWriter(readStream)) { touchedFilesLogger.WriteReadPaths(writer); } filePath = writtenFilesPath; using (var writer = new StreamWriter(writtenStream)) { touchedFilesLogger.WriteWrittenPaths(writer); } } catch (Exception e) { Debug.Assert(filePath != null); MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return false; } } return true; } protected virtual ImmutableArray<AdditionalTextFile> ResolveAdditionalFilesFromArguments(List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, TouchedFileLogger? touchedFilesLogger) { var builder = ImmutableArray.CreateBuilder<AdditionalTextFile>(); foreach (var file in Arguments.AdditionalFiles) { builder.Add(new AdditionalTextFile(file, this)); } return builder.ToImmutableArray(); } private static void ReportAnalyzerExecutionTime(TextWriter consoleOutput, AnalyzerDriver analyzerDriver, CultureInfo culture, bool isConcurrentBuild) { Debug.Assert(analyzerDriver.AnalyzerExecutionTimes != null); if (analyzerDriver.AnalyzerExecutionTimes.IsEmpty) { return; } var totalAnalyzerExecutionTime = analyzerDriver.AnalyzerExecutionTimes.Sum(kvp => kvp.Value.TotalSeconds); Func<double, string> getFormattedTime = d => d.ToString("##0.000", culture); consoleOutput.WriteLine(); consoleOutput.WriteLine(string.Format(CodeAnalysisResources.AnalyzerTotalExecutionTime, getFormattedTime(totalAnalyzerExecutionTime))); if (isConcurrentBuild) { consoleOutput.WriteLine(CodeAnalysisResources.MultithreadedAnalyzerExecutionNote); } var analyzersByAssembly = analyzerDriver.AnalyzerExecutionTimes .GroupBy(kvp => kvp.Key.GetType().GetTypeInfo().Assembly) .OrderByDescending(kvp => kvp.Sum(entry => entry.Value.Ticks)); consoleOutput.WriteLine(); getFormattedTime = d => d < 0.001 ? string.Format(culture, "{0,8:<0.000}", 0.001) : string.Format(culture, "{0,8:##0.000}", d); Func<int, string> getFormattedPercentage = i => string.Format("{0,5}", i < 1 ? "<1" : i.ToString()); Func<string?, string> getFormattedAnalyzerName = s => " " + s; // Table header var analyzerTimeColumn = string.Format("{0,8}", CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader); var analyzerPercentageColumn = string.Format("{0,5}", "%"); var analyzerNameColumn = getFormattedAnalyzerName(CodeAnalysisResources.AnalyzerNameColumnHeader); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Table rows grouped by assembly. foreach (var analyzerGroup in analyzersByAssembly) { var executionTime = analyzerGroup.Sum(kvp => kvp.Value.TotalSeconds); var percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); analyzerNameColumn = getFormattedAnalyzerName(analyzerGroup.Key.FullName); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Rows for each diagnostic analyzer in the assembly. foreach (var kvp in analyzerGroup.OrderByDescending(kvp => kvp.Value)) { executionTime = kvp.Value.TotalSeconds; percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); var analyzerIds = string.Join(", ", kvp.Key.SupportedDiagnostics.Select(d => d.Id).Distinct().OrderBy(id => id)); analyzerNameColumn = getFormattedAnalyzerName($" {kvp.Key} ({analyzerIds})"); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); } consoleOutput.WriteLine(); } } /// <summary> /// Returns the name with which the assembly should be output /// </summary> protected abstract string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken); private Stream? OpenFile( string filePath, DiagnosticBag diagnostics, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.None) { try { return FileSystem.OpenFile(filePath, mode, access, share); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return null; } } // internal for testing internal static Stream? GetWin32ResourcesInternal( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, out IEnumerable<DiagnosticInfo> errors) { var diagnostics = DiagnosticBag.GetInstance(); var stream = GetWin32Resources(fileSystem, messageProvider, arguments, compilation, diagnostics); errors = diagnostics.ToReadOnlyAndFree().SelectAsArray(diag => new DiagnosticInfo(messageProvider, diag.IsWarningAsError, diag.Code, (object[])diag.Arguments)); return stream; } private static Stream? GetWin32Resources( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, DiagnosticBag diagnostics) { if (arguments.Win32ResourceFile != null) { return OpenStream(fileSystem, messageProvider, arguments.Win32ResourceFile, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Resource, diagnostics); } using (Stream? manifestStream = OpenManifestStream(fileSystem, messageProvider, compilation.Options.OutputKind, arguments, diagnostics)) { using (Stream? iconStream = OpenStream(fileSystem, messageProvider, arguments.Win32Icon, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Icon, diagnostics)) { try { return compilation.CreateDefaultWin32Resources(true, arguments.NoWin32Manifest, manifestStream, iconStream); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_ErrorBuildingWin32Resource, Location.None, ex.Message)); } } } return null; } private static Stream? OpenManifestStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, OutputKind outputKind, CommandLineArguments arguments, DiagnosticBag diagnostics) { return outputKind.IsNetModule() ? null : OpenStream(fileSystem, messageProvider, arguments.Win32Manifest, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Manifest, diagnostics); } private static Stream? OpenStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, string? path, string? baseDirectory, int errorCode, DiagnosticBag diagnostics) { if (path == null) { return null; } string? fullPath = ResolveRelativePath(messageProvider, path, baseDirectory, diagnostics); if (fullPath == null) { return null; } try { return fileSystem.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(errorCode, Location.None, fullPath, ex.Message)); } return null; } private static string? ResolveRelativePath(CommonMessageProvider messageProvider, string path, string? baseDirectory, DiagnosticBag diagnostics) { string? fullPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (fullPath == null) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.FTL_InvalidInputFileName, Location.None, path ?? "")); } return fullPath; } internal static bool TryGetCompilerDiagnosticCode(string diagnosticId, string expectedPrefix, out uint code) { code = 0; return diagnosticId.StartsWith(expectedPrefix, StringComparison.Ordinal) && uint.TryParse(diagnosticId.Substring(expectedPrefix.Length), out code); } /// <summary> /// When overridden by a derived class, this property can override the current thread's /// CurrentUICulture property for diagnostic message resource lookups. /// </summary> protected virtual CultureInfo Culture { get { return Arguments.PreferredUILang ?? CultureInfo.CurrentUICulture; } } private static void EmitDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { var key = CreateDeterminismKey(args, rawArgs, baseDirectory, parser); var filePath = Path.Combine(args.OutputDirectory, args.OutputFileName + ".key"); using (var stream = File.Create(filePath)) { var bytes = Encoding.UTF8.GetBytes(key); stream.Write(bytes, 0, bytes.Length); } } /// <summary> /// The string returned from this function represents the inputs to the compiler which impact determinism. It is /// meant to be inline with the specification here: /// /// - https://github.com/dotnet/roslyn/blob/main/docs/compilers/Deterministic%20Inputs.md /// /// Issue #8193 tracks filling this out to the full specification. /// /// https://github.com/dotnet/roslyn/issues/8193 /// </summary> private static string CreateDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { List<Diagnostic> diagnostics = new List<Diagnostic>(); var flattenedArgs = ArrayBuilder<string>.GetInstance(); parser.FlattenArgs(rawArgs, diagnostics, flattenedArgs, null, baseDirectory); var builder = new StringBuilder(); var name = !string.IsNullOrEmpty(args.OutputFileName) ? Path.GetFileNameWithoutExtension(Path.GetFileName(args.OutputFileName)) : $"no-output-name-{Guid.NewGuid().ToString()}"; builder.AppendLine($"{name}"); builder.AppendLine($"Command Line:"); foreach (var current in flattenedArgs) { builder.AppendLine($"\t{current}"); } builder.AppendLine("Source Files:"); var hash = MD5.Create(); foreach (var sourceFile in args.SourceFiles) { var sourceFileName = Path.GetFileName(sourceFile.Path); string hashValue; try { var bytes = File.ReadAllBytes(sourceFile.Path); var hashBytes = hash.ComputeHash(bytes); var data = BitConverter.ToString(hashBytes); hashValue = data.Replace("-", ""); } catch (Exception ex) { hashValue = $"Could not compute {ex.Message}"; } builder.AppendLine($"\t{sourceFileName} - {hashValue}"); } flattenedArgs.Free(); return builder.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal readonly struct BuildPaths { /// <summary> /// The path which contains the compiler binaries and response files. /// </summary> internal string ClientDirectory { get; } /// <summary> /// The path in which the compilation takes place. /// </summary> internal string WorkingDirectory { get; } /// <summary> /// The path which contains mscorlib. This can be null when specified by the user or running in a /// CoreClr environment. /// </summary> internal string? SdkDirectory { get; } /// <summary> /// The temporary directory a compilation should use instead of <see cref="Path.GetTempPath"/>. The latter /// relies on global state individual compilations should ignore. /// </summary> internal string? TempDirectory { get; } internal BuildPaths(string clientDir, string workingDir, string? sdkDir, string? tempDir) { ClientDirectory = clientDir; WorkingDirectory = workingDir; SdkDirectory = sdkDir; TempDirectory = tempDir; } } /// <summary> /// Base class for csc.exe, csi.exe, vbc.exe and vbi.exe implementations. /// </summary> internal abstract partial class CommonCompiler { internal const int Failed = 1; internal const int Succeeded = 0; /// <summary> /// Fallback encoding that is lazily retrieved if needed. If <see cref="EncodedStringText.CreateFallbackEncoding"/> is /// evaluated and stored, the value is used if a PDB is created for this compilation. /// </summary> private readonly Lazy<Encoding> _fallbackEncoding = new Lazy<Encoding>(EncodedStringText.CreateFallbackEncoding); public CommonMessageProvider MessageProvider { get; } public CommandLineArguments Arguments { get; } public IAnalyzerAssemblyLoader AssemblyLoader { get; private set; } public GeneratorDriverCache? GeneratorDriverCache { get; } public abstract DiagnosticFormatter DiagnosticFormatter { get; } /// <summary> /// The set of source file paths that are in the set of embedded paths. /// This is used to prevent reading source files that are embedded twice. /// </summary> public IReadOnlySet<string> EmbeddedSourcePaths { get; } /// <summary> /// The <see cref="ICommonCompilerFileSystem"/> used to access the file system inside this instance. /// </summary> internal ICommonCompilerFileSystem FileSystem { get; set; } = StandardFileSystem.Instance; private readonly HashSet<Diagnostic> _reportedDiagnostics = new HashSet<Diagnostic>(); public abstract Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLoggerOpt, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions); public abstract void PrintLogo(TextWriter consoleOutput); public abstract void PrintHelp(TextWriter consoleOutput); public abstract void PrintLangVersions(TextWriter consoleOutput); /// <summary> /// Print compiler version /// </summary> /// <param name="consoleOutput"></param> public virtual void PrintVersion(TextWriter consoleOutput) { consoleOutput.WriteLine(GetCompilerVersion()); } protected abstract bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code); protected abstract void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators); public CommonCompiler(CommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader, GeneratorDriverCache? driverCache) { IEnumerable<string> allArgs = args; Debug.Assert(null == responseFile || PathUtilities.IsAbsolute(responseFile)); if (!SuppressDefaultResponseFile(args) && File.Exists(responseFile)) { allArgs = new[] { "@" + responseFile }.Concat(allArgs); } this.Arguments = parser.Parse(allArgs, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, additionalReferenceDirectories); this.MessageProvider = parser.MessageProvider; this.AssemblyLoader = assemblyLoader; this.GeneratorDriverCache = driverCache; this.EmbeddedSourcePaths = GetEmbeddedSourcePaths(Arguments); if (Arguments.ParseOptions.Features.ContainsKey("debug-determinism")) { EmitDeterminismKey(Arguments, args, buildPaths.WorkingDirectory, parser); } } internal abstract bool SuppressDefaultResponseFile(IEnumerable<string> args); /// <summary> /// The type of the compiler class for version information in /help and /version. /// We don't simply use this.GetType() because that would break mock subclasses. /// </summary> internal abstract Type Type { get; } /// <summary> /// The version of this compiler with commit hash, used in logo and /version output. /// </summary> internal string GetCompilerVersion() { return GetProductVersion(Type); } internal static string GetProductVersion(Type type) { string? assemblyVersion = GetInformationalVersionWithoutHash(type); string? hash = GetShortCommitHash(type); return $"{assemblyVersion} ({hash})"; } [return: NotNullIfNotNull("hash")] internal static string? ExtractShortCommitHash(string? hash) { // leave "<developer build>" alone, but truncate SHA to 8 characters if (hash != null && hash.Length >= 8 && hash[0] != '<') { return hash.Substring(0, 8); } return hash; } private static string? GetInformationalVersionWithoutHash(Type type) { // The attribute stores a SemVer2-formatted string: `A.B.C(-...)?(+...)?` // We remove the section after the + (if any is present) return type.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+')[0]; } private static string? GetShortCommitHash(Type type) { var hash = type.Assembly.GetCustomAttribute<CommitHashAttribute>()?.Hash; return ExtractShortCommitHash(hash); } /// <summary> /// Tool name used, along with assembly version, for error logging. /// </summary> internal abstract string GetToolName(); /// <summary> /// Tool version identifier used for error logging. /// </summary> internal Version? GetAssemblyVersion() { return Type.GetTypeInfo().Assembly.GetName().Version; } internal string GetCultureName() { return Culture.Name; } internal virtual Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return (path, properties) => { var peStream = FileSystem.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read); return MetadataReference.CreateFromFile(peStream, path, properties); }; } internal virtual MetadataReferenceResolver GetCommandLineMetadataReferenceResolver(TouchedFileLogger? loggerOpt) { var pathResolver = new CompilerRelativePathResolver(FileSystem, Arguments.ReferencePaths, Arguments.BaseDirectory!); return new LoggingMetadataFileReferenceResolver(pathResolver, GetMetadataProvider(), loggerOpt); } /// <summary> /// Resolves metadata references stored in command line arguments and reports errors for those that can't be resolved. /// </summary> internal List<MetadataReference> ResolveMetadataReferences( List<DiagnosticInfo> diagnostics, TouchedFileLogger? touchedFiles, out MetadataReferenceResolver referenceDirectiveResolver) { var commandLineReferenceResolver = GetCommandLineMetadataReferenceResolver(touchedFiles); List<MetadataReference> resolved = new List<MetadataReference>(); Arguments.ResolveMetadataReferences(commandLineReferenceResolver, diagnostics, this.MessageProvider, resolved); if (Arguments.IsScriptRunner) { referenceDirectiveResolver = commandLineReferenceResolver; } else { // when compiling into an assembly (csc/vbc) we only allow #r that match references given on command line: referenceDirectiveResolver = new ExistingReferencesResolver(commandLineReferenceResolver, resolved.ToImmutableArray()); } return resolved; } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics) { return TryReadFileContent(file, diagnostics, out _); } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <param name="normalizedFilePath">If given <paramref name="file"/> opens successfully, set to normalized absolute path of the file, null otherwise.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics, out string? normalizedFilePath) { var filePath = file.Path; try { if (file.IsInputRedirected) { using var data = Console.OpenStandardInput(); normalizedFilePath = filePath; return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } else { using var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedFilePath); return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } } catch (Exception e) { diagnostics.Add(ToFileReadDiagnostics(this.MessageProvider, e, filePath)); normalizedFilePath = null; return null; } } /// <summary> /// Read all analyzer config files from the given paths. /// </summary> internal bool TryGetAnalyzerConfigSet( ImmutableArray<string> analyzerConfigPaths, DiagnosticBag diagnostics, [NotNullWhen(true)] out AnalyzerConfigSet? analyzerConfigSet) { var configs = ArrayBuilder<AnalyzerConfig>.GetInstance(analyzerConfigPaths.Length); var processedDirs = PooledHashSet<string>.GetInstance(); foreach (var configPath in analyzerConfigPaths) { // The editorconfig spec requires all paths use '/' as the directory separator. // Since no known system allows directory separators as part of the file name, // we can replace every instance of the directory separator with a '/' string? fileContent = TryReadFileContent(configPath, diagnostics, out string? normalizedPath); if (fileContent is null) { // Error reading a file. Bail out and report error. break; } Debug.Assert(normalizedPath is object); var directory = Path.GetDirectoryName(normalizedPath) ?? normalizedPath; var editorConfig = AnalyzerConfig.Parse(fileContent, normalizedPath); if (!editorConfig.IsGlobal) { if (processedDirs.Contains(directory)) { diagnostics.Add(Diagnostic.Create( MessageProvider, MessageProvider.ERR_MultipleAnalyzerConfigsInSameDir, directory)); break; } processedDirs.Add(directory); } configs.Add(editorConfig); } processedDirs.Free(); if (diagnostics.HasAnyErrors()) { configs.Free(); analyzerConfigSet = null; return false; } analyzerConfigSet = AnalyzerConfigSet.Create(configs, out var setDiagnostics); diagnostics.AddRange(setDiagnostics); return true; } /// <summary> /// Returns the fallback encoding for parsing source files, if used, or null /// if not used /// </summary> internal Encoding? GetFallbackEncoding() { if (_fallbackEncoding.IsValueCreated) { return _fallbackEncoding.Value; } return null; } /// <summary> /// Read a UTF-8 encoded file and return the text as a string. /// </summary> private string? TryReadFileContent(string filePath, DiagnosticBag diagnostics, out string? normalizedPath) { try { var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedPath); using (var reader = new StreamReader(data, Encoding.UTF8)) { return reader.ReadToEnd(); } } catch (Exception e) { diagnostics.Add(Diagnostic.Create(ToFileReadDiagnostics(MessageProvider, e, filePath))); normalizedPath = null; return null; } } private Stream OpenFileForReadWithSmallBufferOptimization(string filePath, out string normalizedFilePath) // PERF: Using a very small buffer size for the FileStream opens up an optimization within EncodedStringText/EmbeddedText where // we read the entire FileStream into a byte array in one shot. For files that are actually smaller than the buffer // size, FileStream.Read still allocates the internal buffer. => FileSystem.OpenFileEx( filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 1, options: FileOptions.None, out normalizedFilePath); internal EmbeddedText? TryReadEmbeddedFileContent(string filePath, DiagnosticBag diagnostics) { try { using (var stream = OpenFileForReadWithSmallBufferOptimization(filePath, out _)) { const int LargeObjectHeapLimit = 80 * 1024; if (stream.Length < LargeObjectHeapLimit) { ArraySegment<byte> bytes; if (EncodedStringText.TryGetBytesFromStream(stream, out bytes)) { return EmbeddedText.FromBytes(filePath, bytes, Arguments.ChecksumAlgorithm); } } return EmbeddedText.FromStream(filePath, stream, Arguments.ChecksumAlgorithm); } } catch (Exception e) { diagnostics.Add(MessageProvider.CreateDiagnostic(ToFileReadDiagnostics(this.MessageProvider, e, filePath))); return null; } } private ImmutableArray<EmbeddedText?> AcquireEmbeddedTexts(Compilation compilation, DiagnosticBag diagnostics) { Debug.Assert(compilation.Options.SourceReferenceResolver is object); if (Arguments.EmbeddedFiles.IsEmpty) { return ImmutableArray<EmbeddedText?>.Empty; } var embeddedTreeMap = new Dictionary<string, SyntaxTree>(Arguments.EmbeddedFiles.Length); var embeddedFileOrderedSet = new OrderedSet<string>(Arguments.EmbeddedFiles.Select(e => e.Path)); foreach (var tree in compilation.SyntaxTrees) { // Skip trees that will not have their text embedded. if (!EmbeddedSourcePaths.Contains(tree.FilePath)) { continue; } // Skip trees with duplicated paths. (VB allows this and "first tree wins" is same as PDB emit policy.) if (embeddedTreeMap.ContainsKey(tree.FilePath)) { continue; } // map embedded file path to corresponding source tree embeddedTreeMap.Add(tree.FilePath, tree); // also embed the text of any #line directive targets of embedded tree ResolveEmbeddedFilesFromExternalSourceDirectives(tree, compilation.Options.SourceReferenceResolver, embeddedFileOrderedSet, diagnostics); } var embeddedTextBuilder = ImmutableArray.CreateBuilder<EmbeddedText?>(embeddedFileOrderedSet.Count); foreach (var path in embeddedFileOrderedSet) { SyntaxTree? tree; EmbeddedText? text; if (embeddedTreeMap.TryGetValue(path, out tree)) { text = EmbeddedText.FromSource(path, tree.GetText()); Debug.Assert(text != null); } else { text = TryReadEmbeddedFileContent(path, diagnostics); Debug.Assert(text != null || diagnostics.HasAnyErrors()); } // We can safely add nulls because result will be ignored if any error is produced. // This allows the MoveToImmutable to work below in all cases. embeddedTextBuilder.Add(text); } return embeddedTextBuilder.MoveToImmutable(); } protected abstract void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics); private static IReadOnlySet<string> GetEmbeddedSourcePaths(CommandLineArguments arguments) { if (arguments.EmbeddedFiles.IsEmpty) { return SpecializedCollections.EmptyReadOnlySet<string>(); } // Note that we require an exact match between source and embedded file paths (case-sensitive // and without normalization). If two files are the same but spelled differently, they will // be handled as separate files, meaning the embedding pass will read the content a second // time. This can also lead to more than one document entry in the PDB for the same document // if the PDB document de-duping policy in emit (normalize + case-sensitive in C#, // normalize + case-insensitive in VB) is not enough to converge them. var set = new HashSet<string>(arguments.EmbeddedFiles.Select(f => f.Path)); set.IntersectWith(arguments.SourceFiles.Select(f => f.Path)); return SpecializedCollections.StronglyTypedReadOnlySet(set); } internal static DiagnosticInfo ToFileReadDiagnostics(CommonMessageProvider messageProvider, Exception e, string filePath) { DiagnosticInfo diagnosticInfo; if (e is FileNotFoundException || e is DirectoryNotFoundException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_FileNotFound, filePath); } else if (e is InvalidDataException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_BinaryFile, filePath); } else { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_NoSourceFile, filePath, e.Message); } return diagnosticInfo; } /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<Diagnostic> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) { bool hasErrors = false; foreach (var diag in diagnostics) { reportDiagnostic(diag, compilation == null ? null : diag.GetSuppressionInfo(compilation)); } return hasErrors; // Local functions void reportDiagnostic(Diagnostic diag, SuppressionInfo? suppressionInfo) { if (_reportedDiagnostics.Contains(diag)) { // TODO: This invariant fails (at least) in the case where we see a member declaration "x = 1;". // First we attempt to parse a member declaration starting at "x". When we see the "=", we // create an IncompleteMemberSyntax with return type "x" and an error at the location of the "x". // Then we parse a member declaration starting at "=". This is an invalid member declaration start // so we attach an error to the "=" and attach it (plus following tokens) to the IncompleteMemberSyntax // we previously created. //this assert isn't valid if we change the design to not bail out after each phase. //System.Diagnostics.Debug.Assert(diag.Severity != DiagnosticSeverity.Error); return; } else if (diag.Severity == DiagnosticSeverity.Hidden) { // Not reported from the command-line compiler. return; } // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics should not be reported on the console output. errorLoggerOpt?.LogDiagnostic(diag, suppressionInfo); // If the diagnostic was suppressed by one or more DiagnosticSuppressor(s), then we report info diagnostics for each suppression // so that the suppression information is available in the binary logs and verbose build logs. if (diag.ProgrammaticSuppressionInfo != null) { foreach (var (id, justification) in diag.ProgrammaticSuppressionInfo.Suppressions) { var suppressionDiag = new SuppressionDiagnostic(diag, id, justification); if (_reportedDiagnostics.Add(suppressionDiag)) { PrintError(suppressionDiag, consoleOutput); } } _reportedDiagnostics.Add(diag); return; } if (diag.IsSuppressed) { return; } // Diagnostics that aren't suppressed will be reported to the console output and, if they are errors, // they should fail the run if (diag.Severity == DiagnosticSeverity.Error) { hasErrors = true; } PrintError(diag, consoleOutput); _reportedDiagnostics.Add(diag); } } /// <summary>Returns true if there were any errors, false otherwise.</summary> private bool ReportDiagnostics(DiagnosticBag diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.ToReadOnly(), consoleOutput, errorLoggerOpt, compilation); /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<DiagnosticInfo> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.Select(info => Diagnostic.Create(info)), consoleOutput, errorLoggerOpt, compilation); /// <summary> /// Returns true if there are any error diagnostics in the bag which cannot be suppressed and /// are guaranteed to break the build. /// Only diagnostics which have default severity error and are tagged as NotConfigurable fall in this bucket. /// This includes all compiler error diagnostics and specific analyzer error diagnostics that are marked as not configurable by the analyzer author. /// </summary> internal static bool HasUnsuppressableErrors(DiagnosticBag diagnostics) { foreach (var diag in diagnostics.AsEnumerable()) { if (diag.IsUnsuppressableError()) { return true; } } return false; } /// <summary> /// Returns true if the bag has any diagnostics with effective Severity=Error. Also returns true for warnings or informationals /// or warnings promoted to error via /warnaserror which are not suppressed. /// </summary> internal static bool HasUnsuppressedErrors(DiagnosticBag diagnostics) { foreach (Diagnostic diagnostic in diagnostics.AsEnumerable()) { if (diagnostic.IsUnsuppressedError) { return true; } } return false; } protected virtual void PrintError(Diagnostic diagnostic, TextWriter consoleOutput) { consoleOutput.WriteLine(DiagnosticFormatter.Format(diagnostic, Culture)); } public SarifErrorLogger? GetErrorLogger(TextWriter consoleOutput, CancellationToken cancellationToken) { Debug.Assert(Arguments.ErrorLogOptions?.Path != null); var diagnostics = DiagnosticBag.GetInstance(); var errorLog = OpenFile(Arguments.ErrorLogOptions.Path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); SarifErrorLogger? logger; if (errorLog == null) { Debug.Assert(diagnostics.HasAnyErrors()); logger = null; } else { string toolName = GetToolName(); string compilerVersion = GetCompilerVersion(); Version assemblyVersion = GetAssemblyVersion() ?? new Version(); if (Arguments.ErrorLogOptions.SarifVersion == SarifVersion.Sarif1) { logger = new SarifV1ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } else { logger = new SarifV2ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } } ReportDiagnostics(diagnostics.ToReadOnlyAndFree(), consoleOutput, errorLoggerOpt: logger, compilation: null); return logger; } /// <summary> /// csc.exe and vbc.exe entry point. /// </summary> public virtual int Run(TextWriter consoleOutput, CancellationToken cancellationToken = default) { var saveUICulture = CultureInfo.CurrentUICulture; SarifErrorLogger? errorLogger = null; try { // Messages from exceptions can be used as arguments for errors and they are often localized. // Ensure they are localized to the right language. var culture = this.Culture; if (culture != null) { CultureInfo.CurrentUICulture = culture; } if (Arguments.ErrorLogOptions?.Path != null) { errorLogger = GetErrorLogger(consoleOutput, cancellationToken); if (errorLogger == null) { return Failed; } } return RunCore(consoleOutput, errorLogger, cancellationToken); } catch (OperationCanceledException) { var errorCode = MessageProvider.ERR_CompileCancelled; if (errorCode > 0) { var diag = new DiagnosticInfo(MessageProvider, errorCode); ReportDiagnostics(new[] { diag }, consoleOutput, errorLogger, compilation: null); } return Failed; } finally { CultureInfo.CurrentUICulture = saveUICulture; errorLogger?.Dispose(); } } /// <summary> /// Perform source generation, if the compiler supports it. /// </summary> /// <param name="input">The compilation before any source generation has occurred.</param> /// <param name="parseOptions">The <see cref="ParseOptions"/> to use when parsing any generated sources.</param> /// <param name="generators">The generators to run</param> /// <param name="analyzerConfigOptionsProvider">A provider that returns analyzer config options</param> /// <param name="additionalTexts">Any additional texts that should be passed to the generators when run.</param> /// <param name="generatorDiagnostics">Any diagnostics that were produced during generation</param> /// <returns>A compilation that represents the original compilation with any additional, generated texts added to it.</returns> private protected Compilation RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts, DiagnosticBag generatorDiagnostics) { GeneratorDriver? driver = null; string cacheKey = string.Empty; bool disableCache = Arguments.ParseOptions.Features.ContainsKey("disable-generator-cache") || string.IsNullOrWhiteSpace(Arguments.OutputFileName); if (this.GeneratorDriverCache is object && !disableCache) { cacheKey = deriveCacheKey(); driver = this.GeneratorDriverCache.TryGetDriver(cacheKey); } driver ??= CreateGeneratorDriver(parseOptions, generators, analyzerConfigOptionsProvider, additionalTexts); driver = driver.RunGeneratorsAndUpdateCompilation(input, out var compilationOut, out var diagnostics); generatorDiagnostics.AddRange(diagnostics); if (!disableCache) { this.GeneratorDriverCache?.CacheGenerator(cacheKey, driver); } return compilationOut; string deriveCacheKey() { Debug.Assert(!string.IsNullOrWhiteSpace(Arguments.OutputFileName)); // CONSIDER: The only piece of the cache key that is required for correctness is the generators that were used. // We set up the graph statically based on the generators, so as long as the generator inputs haven't // changed we can technically run any project against another's cache and still get the correct results. // Obviously that would remove the point of the cache, so we also key off of the output file name // and output path so that collisions are unlikely and we'll usually get the correct cache for any // given compilation. PooledStringBuilder sb = PooledStringBuilder.GetInstance(); sb.Builder.Append(Arguments.GetOutputFilePath(Arguments.OutputFileName)); foreach (var generator in generators) { // append the generator FQN and the MVID of the assembly it came from, so any changes will invalidate the cache var type = generator.GetGeneratorType(); sb.Builder.Append(type.AssemblyQualifiedName); sb.Builder.Append(type.Assembly.ManifestModule.ModuleVersionId.ToString()); } return sb.ToStringAndFree(); } } private protected abstract GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts); private int RunCore(TextWriter consoleOutput, ErrorLogger? errorLogger, CancellationToken cancellationToken) { Debug.Assert(!Arguments.IsScriptRunner); cancellationToken.ThrowIfCancellationRequested(); if (Arguments.DisplayVersion) { PrintVersion(consoleOutput); return Succeeded; } if (Arguments.DisplayLangVersions) { PrintLangVersions(consoleOutput); return Succeeded; } if (Arguments.DisplayLogo) { PrintLogo(consoleOutput); } if (Arguments.DisplayHelp) { PrintHelp(consoleOutput); return Succeeded; } if (ReportDiagnostics(Arguments.Errors, consoleOutput, errorLogger, compilation: null)) { return Failed; } var touchedFilesLogger = (Arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null; var diagnostics = DiagnosticBag.GetInstance(); AnalyzerConfigSet? analyzerConfigSet = null; ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions = default; AnalyzerConfigOptionsResult globalConfigOptions = default; if (Arguments.AnalyzerConfigPaths.Length > 0) { if (!TryGetAnalyzerConfigSet(Arguments.AnalyzerConfigPaths, diagnostics, out analyzerConfigSet)) { var hadErrors = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null); Debug.Assert(hadErrors); return Failed; } globalConfigOptions = analyzerConfigSet.GlobalConfigOptions; sourceFileAnalyzerConfigOptions = Arguments.SourceFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var sourceFileAnalyzerConfigOption in sourceFileAnalyzerConfigOptions) { diagnostics.AddRange(sourceFileAnalyzerConfigOption.Diagnostics); } } Compilation? compilation = CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, sourceFileAnalyzerConfigOptions, globalConfigOptions); if (compilation == null) { return Failed; } var diagnosticInfos = new List<DiagnosticInfo>(); ResolveAnalyzersFromArguments(diagnosticInfos, MessageProvider, Arguments.SkipAnalyzers, out var analyzers, out var generators); var additionalTextFiles = ResolveAdditionalFilesFromArguments(diagnosticInfos, MessageProvider, touchedFilesLogger); if (ReportDiagnostics(diagnosticInfos, consoleOutput, errorLogger, compilation)) { return Failed; } ImmutableArray<EmbeddedText?> embeddedTexts = AcquireEmbeddedTexts(compilation, diagnostics); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation)) { return Failed; } var additionalTexts = ImmutableArray<AdditionalText>.CastUp(additionalTextFiles); CompileAndEmit( touchedFilesLogger, ref compilation, analyzers, generators, additionalTexts, analyzerConfigSet, sourceFileAnalyzerConfigOptions, embeddedTexts, diagnostics, cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out var analyzerDriver); // At this point analyzers are already complete in which case this is a no-op. Or they are // still running because the compilation failed before all of the compilation events were // raised. In the latter case the driver, and all its associated state, will be waiting around // for events that are never coming. Cancel now and let the clean up process begin. if (analyzerCts != null) { analyzerCts.Cancel(); } var exitCode = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation) ? Failed : Succeeded; // The act of reporting errors can cause more errors to appear in // additional files due to forcing all additional files to fetch text foreach (var additionalFile in additionalTextFiles) { if (ReportDiagnostics(additionalFile.Diagnostics, consoleOutput, errorLogger, compilation)) { exitCode = Failed; } } diagnostics.Free(); if (reportAnalyzer) { Debug.Assert(analyzerDriver is object); ReportAnalyzerExecutionTime(consoleOutput, analyzerDriver, Culture, compilation.Options.ConcurrentBuild); } return exitCode; } private static CompilerAnalyzerConfigOptionsProvider UpdateAnalyzerConfigOptionsProvider( CompilerAnalyzerConfigOptionsProvider existing, IEnumerable<SyntaxTree> syntaxTrees, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<AdditionalText> additionalFiles = default, ImmutableArray<AnalyzerConfigOptionsResult> additionalFileOptions = default) { var builder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); int i = 0; foreach (var syntaxTree in syntaxTrees) { var options = sourceFileAnalyzerConfigOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(syntaxTree) == CompilerAnalyzerConfigOptions.Empty); builder.Add(syntaxTree, new CompilerAnalyzerConfigOptions(options)); } i++; } if (!additionalFiles.IsDefault) { for (i = 0; i < additionalFiles.Length; i++) { var options = additionalFileOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(additionalFiles[i]) == CompilerAnalyzerConfigOptions.Empty); builder.Add(additionalFiles[i], new CompilerAnalyzerConfigOptions(options)); } } } return existing.WithAdditionalTreeOptions(builder.ToImmutable()); } /// <summary> /// Perform all the work associated with actual compilation /// (parsing, binding, compile, emit), resulting in diagnostics /// and analyzer output. /// </summary> private void CompileAndEmit( TouchedFileLogger? touchedFilesLogger, ref Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<ISourceGenerator> generators, ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigSet? analyzerConfigSet, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<EmbeddedText?> embeddedTexts, DiagnosticBag diagnostics, CancellationToken cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out AnalyzerDriver? analyzerDriver) { analyzerCts = null; reportAnalyzer = false; analyzerDriver = null; // Print the diagnostics produced during the parsing stage and exit if there were any errors. compilation.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } DiagnosticBag? analyzerExceptionDiagnostics = null; if (!analyzers.IsEmpty || !generators.IsEmpty) { var analyzerConfigProvider = CompilerAnalyzerConfigOptionsProvider.Empty; if (Arguments.AnalyzerConfigPaths.Length > 0) { Debug.Assert(analyzerConfigSet is object); analyzerConfigProvider = analyzerConfigProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(analyzerConfigSet.GetOptionsForSourcePath(string.Empty).AnalyzerOptions)); // TODO(https://github.com/dotnet/roslyn/issues/31916): The compiler currently doesn't support // configuring diagnostic reporting on additional text files individually. ImmutableArray<AnalyzerConfigOptionsResult> additionalFileAnalyzerOptions = additionalTextFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var result in additionalFileAnalyzerOptions) { diagnostics.AddRange(result.Diagnostics); } analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, compilation.SyntaxTrees, sourceFileAnalyzerConfigOptions, additionalTextFiles, additionalFileAnalyzerOptions); } if (!generators.IsEmpty) { // At this point we have a compilation with nothing yet computed. // We pass it to the generators, which will realize any symbols they require. compilation = RunGenerators(compilation, Arguments.ParseOptions, generators, analyzerConfigProvider, additionalTextFiles, diagnostics); bool hasAnalyzerConfigs = !Arguments.AnalyzerConfigPaths.IsEmpty; bool hasGeneratedOutputPath = !string.IsNullOrWhiteSpace(Arguments.GeneratedFilesOutputDirectory); var generatedSyntaxTrees = compilation.SyntaxTrees.Skip(Arguments.SourceFiles.Length).ToList(); var analyzerOptionsBuilder = hasAnalyzerConfigs ? ArrayBuilder<AnalyzerConfigOptionsResult>.GetInstance(generatedSyntaxTrees.Count) : null; var embeddedTextBuilder = ArrayBuilder<EmbeddedText>.GetInstance(generatedSyntaxTrees.Count); try { foreach (var tree in generatedSyntaxTrees) { Debug.Assert(!string.IsNullOrWhiteSpace(tree.FilePath)); cancellationToken.ThrowIfCancellationRequested(); var sourceText = tree.GetText(cancellationToken); // embed the generated text and get analyzer options for it if needed embeddedTextBuilder.Add(EmbeddedText.FromSource(tree.FilePath, sourceText)); if (analyzerOptionsBuilder is object) { analyzerOptionsBuilder.Add(analyzerConfigSet!.GetOptionsForSourcePath(tree.FilePath)); } // write out the file if we have an output path if (hasGeneratedOutputPath) { var path = Path.Combine(Arguments.GeneratedFilesOutputDirectory!, tree.FilePath); if (Directory.Exists(Arguments.GeneratedFilesOutputDirectory)) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); } var fileStream = OpenFile(path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (fileStream is object) { Debug.Assert(tree.Encoding is object); using var disposer = new NoThrowStreamDisposer(fileStream, path, diagnostics, MessageProvider); using var writer = new StreamWriter(fileStream, tree.Encoding); sourceText.Write(writer, cancellationToken); touchedFilesLogger?.AddWritten(path); } } } embeddedTexts = embeddedTexts.AddRange(embeddedTextBuilder); if (analyzerOptionsBuilder is object) { analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, generatedSyntaxTrees, analyzerOptionsBuilder.ToImmutable()); } } finally { analyzerOptionsBuilder?.Free(); embeddedTextBuilder.Free(); } } AnalyzerOptions analyzerOptions = CreateAnalyzerOptions( additionalTextFiles, analyzerConfigProvider); if (!analyzers.IsEmpty) { analyzerCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); analyzerExceptionDiagnostics = new DiagnosticBag(); // PERF: Avoid executing analyzers that report only Hidden and/or Info diagnostics, which don't appear in the build output. // 1. Always filter out 'Hidden' analyzer diagnostics in build. // 2. Filter out 'Info' analyzer diagnostics if they are not required to be logged in errorlog. var severityFilter = SeverityFilter.Hidden; if (Arguments.ErrorLogPath == null) severityFilter |= SeverityFilter.Info; analyzerDriver = AnalyzerDriver.CreateAndAttachToCompilation( compilation, analyzers, analyzerOptions, new AnalyzerManager(analyzers), analyzerExceptionDiagnostics.Add, Arguments.ReportAnalyzer, severityFilter, out compilation, analyzerCts.Token); reportAnalyzer = Arguments.ReportAnalyzer && !analyzers.IsEmpty; } } compilation.GetDiagnostics(CompilationStage.Declare, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } cancellationToken.ThrowIfCancellationRequested(); // Given a compilation and a destination directory, determine three names: // 1) The name with which the assembly should be output. // 2) The path of the assembly/module file (default = destination directory + compilation output name). // 3) The path of the pdb file (default = assembly/module path with ".pdb" extension). string outputName = GetOutputFileName(compilation, cancellationToken)!; var finalPeFilePath = Arguments.GetOutputFilePath(outputName); var finalPdbFilePath = Arguments.GetPdbFilePath(outputName); var finalXmlFilePath = Arguments.DocumentationPath; NoThrowStreamDisposer? sourceLinkStreamDisposerOpt = null; try { // NOTE: Unlike the PDB path, the XML doc path is not embedded in the assembly, so we don't need to pass it to emit. var emitOptions = Arguments.EmitOptions. WithOutputNameOverride(outputName). WithPdbFilePath(PathUtilities.NormalizePathPrefix(finalPdbFilePath, Arguments.PathMap)); // TODO(https://github.com/dotnet/roslyn/issues/19592): // This feature flag is being maintained until our next major release to avoid unnecessary // compat breaks with customers. if (Arguments.ParseOptions.Features.ContainsKey("pdb-path-determinism") && !string.IsNullOrEmpty(emitOptions.PdbFilePath)) { emitOptions = emitOptions.WithPdbFilePath(Path.GetFileName(emitOptions.PdbFilePath)); } if (Arguments.SourceLink != null) { var sourceLinkStreamOpt = OpenFile( Arguments.SourceLink, diagnostics, FileMode.Open, FileAccess.Read, FileShare.Read); if (sourceLinkStreamOpt != null) { sourceLinkStreamDisposerOpt = new NoThrowStreamDisposer( sourceLinkStreamOpt, Arguments.SourceLink, diagnostics, MessageProvider); } } // Need to ensure the PDB file path validation is done on the original path as that is the // file we will write out to disk, there is no guarantee that the file paths emitted into // the PE / PDB are valid file paths because pathmap can be used to create deliberately // illegal names if (!PathUtilities.IsValidFilePath(finalPdbFilePath)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.FTL_InvalidInputFileName, Location.None, finalPdbFilePath)); } var moduleBeingBuilt = compilation.CheckOptionsAndCreateModuleBuilder( diagnostics, Arguments.ManifestResources, emitOptions, debugEntryPoint: null, sourceLinkStream: sourceLinkStreamDisposerOpt?.Stream, embeddedTexts: embeddedTexts, testData: null, cancellationToken: cancellationToken); if (moduleBeingBuilt != null) { bool success; try { success = compilation.CompileMethods( moduleBeingBuilt, Arguments.EmitPdb, emitOptions.EmitMetadataOnly, emitOptions.EmitTestCoverageData, diagnostics, filterOpt: null, cancellationToken: cancellationToken); // Prior to generating the xml documentation file, // we apply programmatic suppressions for compiler warnings from diagnostic suppressors. // If there are still any unsuppressed errors or warnings escalated to errors // then we bail out from generating the documentation file. // This maintains the compiler invariant that xml documentation file should not be // generated in presence of diagnostics that break the build. if (analyzerDriver != null && !diagnostics.IsEmptyWithoutResolution) { analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { // NOTE: as native compiler does, we generate the documentation file // NOTE: 'in place', replacing the contents of the file if it exists NoThrowStreamDisposer? xmlStreamDisposerOpt = null; if (finalXmlFilePath != null) { var xmlStreamOpt = OpenFile(finalXmlFilePath, diagnostics, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (xmlStreamOpt == null) { return; } try { xmlStreamOpt.SetLength(0); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, finalXmlFilePath, diagnostics); return; } xmlStreamDisposerOpt = new NoThrowStreamDisposer( xmlStreamOpt, finalXmlFilePath, diagnostics, MessageProvider); } using (xmlStreamDisposerOpt) { using (var win32ResourceStreamOpt = GetWin32Resources(FileSystem, MessageProvider, Arguments, compilation, diagnostics)) { if (HasUnsuppressableErrors(diagnostics)) { return; } success = compilation.GenerateResourcesAndDocumentationComments( moduleBeingBuilt, xmlStreamDisposerOpt?.Stream, win32ResourceStreamOpt, useRawWin32Resources: false, emitOptions.OutputNameOverride, diagnostics, cancellationToken); } } if (xmlStreamDisposerOpt?.HasFailedToDispose == true) { return; } // only report unused usings if we have success. if (success) { compilation.ReportUnusedImports(diagnostics, cancellationToken); } } compilation.CompleteTrees(null); if (analyzerDriver != null) { // GetDiagnosticsAsync is called after ReportUnusedImports // since that method calls EventQueue.TryComplete. Without // TryComplete, we may miss diagnostics. var hostDiagnostics = analyzerDriver.GetDiagnosticsAsync(compilation).Result; diagnostics.AddRange(hostDiagnostics); if (!diagnostics.IsEmptyWithoutResolution) { // Apply diagnostic suppressions for analyzer and/or compiler diagnostics from diagnostic suppressors. analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } } } finally { moduleBeingBuilt.CompilationFinished(); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { var peStreamProvider = new CompilerEmitStreamProvider(this, finalPeFilePath); var pdbStreamProviderOpt = Arguments.EmitPdbFile ? new CompilerEmitStreamProvider(this, finalPdbFilePath) : null; string? finalRefPeFilePath = Arguments.OutputRefFilePath; var refPeStreamProviderOpt = finalRefPeFilePath != null ? new CompilerEmitStreamProvider(this, finalRefPeFilePath) : null; RSAParameters? privateKeyOpt = null; if (compilation.Options.StrongNameProvider != null && compilation.SignUsingBuilder && !compilation.Options.PublicSign) { privateKeyOpt = compilation.StrongNameKeys.PrivateKey; } // If we serialize to a PE stream we need to record the fallback encoding if it was used // so the compilation can be recreated. emitOptions = emitOptions.WithFallbackSourceFileEncoding(GetFallbackEncoding()); success = compilation.SerializeToPeStream( moduleBeingBuilt, peStreamProvider, refPeStreamProviderOpt, pdbStreamProviderOpt, rebuildData: null, testSymWriterFactory: null, diagnostics: diagnostics, emitOptions: emitOptions, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken); peStreamProvider.Close(diagnostics); refPeStreamProviderOpt?.Close(diagnostics); pdbStreamProviderOpt?.Close(diagnostics); if (success && touchedFilesLogger != null) { if (pdbStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalPdbFilePath); } if (refPeStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalRefPeFilePath!); } touchedFilesLogger.AddWritten(finalPeFilePath); } } } if (HasUnsuppressableErrors(diagnostics)) { return; } } finally { sourceLinkStreamDisposerOpt?.Dispose(); } if (sourceLinkStreamDisposerOpt?.HasFailedToDispose == true) { return; } cancellationToken.ThrowIfCancellationRequested(); if (analyzerExceptionDiagnostics != null) { diagnostics.AddRange(analyzerExceptionDiagnostics); if (HasUnsuppressableErrors(analyzerExceptionDiagnostics)) { return; } } cancellationToken.ThrowIfCancellationRequested(); if (!WriteTouchedFiles(diagnostics, touchedFilesLogger, finalXmlFilePath)) { return; } } // virtual for testing protected virtual Diagnostics.AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) => new Diagnostics.AnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); private bool WriteTouchedFiles(DiagnosticBag diagnostics, TouchedFileLogger? touchedFilesLogger, string? finalXmlFilePath) { if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger != null); if (finalXmlFilePath != null) { touchedFilesLogger.AddWritten(finalXmlFilePath); } string readFilesPath = Arguments.TouchedFilesPath + ".read"; string writtenFilesPath = Arguments.TouchedFilesPath + ".write"; var readStream = OpenFile(readFilesPath, diagnostics, mode: FileMode.OpenOrCreate); var writtenStream = OpenFile(writtenFilesPath, diagnostics, mode: FileMode.OpenOrCreate); if (readStream == null || writtenStream == null) { return false; } string? filePath = null; try { filePath = readFilesPath; using (var writer = new StreamWriter(readStream)) { touchedFilesLogger.WriteReadPaths(writer); } filePath = writtenFilesPath; using (var writer = new StreamWriter(writtenStream)) { touchedFilesLogger.WriteWrittenPaths(writer); } } catch (Exception e) { Debug.Assert(filePath != null); MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return false; } } return true; } protected virtual ImmutableArray<AdditionalTextFile> ResolveAdditionalFilesFromArguments(List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, TouchedFileLogger? touchedFilesLogger) { var builder = ImmutableArray.CreateBuilder<AdditionalTextFile>(); foreach (var file in Arguments.AdditionalFiles) { builder.Add(new AdditionalTextFile(file, this)); } return builder.ToImmutableArray(); } private static void ReportAnalyzerExecutionTime(TextWriter consoleOutput, AnalyzerDriver analyzerDriver, CultureInfo culture, bool isConcurrentBuild) { Debug.Assert(analyzerDriver.AnalyzerExecutionTimes != null); if (analyzerDriver.AnalyzerExecutionTimes.IsEmpty) { return; } var totalAnalyzerExecutionTime = analyzerDriver.AnalyzerExecutionTimes.Sum(kvp => kvp.Value.TotalSeconds); Func<double, string> getFormattedTime = d => d.ToString("##0.000", culture); consoleOutput.WriteLine(); consoleOutput.WriteLine(string.Format(CodeAnalysisResources.AnalyzerTotalExecutionTime, getFormattedTime(totalAnalyzerExecutionTime))); if (isConcurrentBuild) { consoleOutput.WriteLine(CodeAnalysisResources.MultithreadedAnalyzerExecutionNote); } var analyzersByAssembly = analyzerDriver.AnalyzerExecutionTimes .GroupBy(kvp => kvp.Key.GetType().GetTypeInfo().Assembly) .OrderByDescending(kvp => kvp.Sum(entry => entry.Value.Ticks)); consoleOutput.WriteLine(); getFormattedTime = d => d < 0.001 ? string.Format(culture, "{0,8:<0.000}", 0.001) : string.Format(culture, "{0,8:##0.000}", d); Func<int, string> getFormattedPercentage = i => string.Format("{0,5}", i < 1 ? "<1" : i.ToString()); Func<string?, string> getFormattedAnalyzerName = s => " " + s; // Table header var analyzerTimeColumn = string.Format("{0,8}", CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader); var analyzerPercentageColumn = string.Format("{0,5}", "%"); var analyzerNameColumn = getFormattedAnalyzerName(CodeAnalysisResources.AnalyzerNameColumnHeader); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Table rows grouped by assembly. foreach (var analyzerGroup in analyzersByAssembly) { var executionTime = analyzerGroup.Sum(kvp => kvp.Value.TotalSeconds); var percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); analyzerNameColumn = getFormattedAnalyzerName(analyzerGroup.Key.FullName); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Rows for each diagnostic analyzer in the assembly. foreach (var kvp in analyzerGroup.OrderByDescending(kvp => kvp.Value)) { executionTime = kvp.Value.TotalSeconds; percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); var analyzerIds = string.Join(", ", kvp.Key.SupportedDiagnostics.Select(d => d.Id).Distinct().OrderBy(id => id)); analyzerNameColumn = getFormattedAnalyzerName($" {kvp.Key} ({analyzerIds})"); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); } consoleOutput.WriteLine(); } } /// <summary> /// Returns the name with which the assembly should be output /// </summary> protected abstract string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken); private Stream? OpenFile( string filePath, DiagnosticBag diagnostics, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.None) { try { return FileSystem.OpenFile(filePath, mode, access, share); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return null; } } // internal for testing internal static Stream? GetWin32ResourcesInternal( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, out IEnumerable<DiagnosticInfo> errors) { var diagnostics = DiagnosticBag.GetInstance(); var stream = GetWin32Resources(fileSystem, messageProvider, arguments, compilation, diagnostics); errors = diagnostics.ToReadOnlyAndFree().SelectAsArray(diag => new DiagnosticInfo(messageProvider, diag.IsWarningAsError, diag.Code, (object[])diag.Arguments)); return stream; } private static Stream? GetWin32Resources( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, DiagnosticBag diagnostics) { if (arguments.Win32ResourceFile != null) { return OpenStream(fileSystem, messageProvider, arguments.Win32ResourceFile, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Resource, diagnostics); } using (Stream? manifestStream = OpenManifestStream(fileSystem, messageProvider, compilation.Options.OutputKind, arguments, diagnostics)) { using (Stream? iconStream = OpenStream(fileSystem, messageProvider, arguments.Win32Icon, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Icon, diagnostics)) { try { return compilation.CreateDefaultWin32Resources(true, arguments.NoWin32Manifest, manifestStream, iconStream); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_ErrorBuildingWin32Resource, Location.None, ex.Message)); } } } return null; } private static Stream? OpenManifestStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, OutputKind outputKind, CommandLineArguments arguments, DiagnosticBag diagnostics) { return outputKind.IsNetModule() ? null : OpenStream(fileSystem, messageProvider, arguments.Win32Manifest, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Manifest, diagnostics); } private static Stream? OpenStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, string? path, string? baseDirectory, int errorCode, DiagnosticBag diagnostics) { if (path == null) { return null; } string? fullPath = ResolveRelativePath(messageProvider, path, baseDirectory, diagnostics); if (fullPath == null) { return null; } try { return fileSystem.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(errorCode, Location.None, fullPath, ex.Message)); } return null; } private static string? ResolveRelativePath(CommonMessageProvider messageProvider, string path, string? baseDirectory, DiagnosticBag diagnostics) { string? fullPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (fullPath == null) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.FTL_InvalidInputFileName, Location.None, path ?? "")); } return fullPath; } internal static bool TryGetCompilerDiagnosticCode(string diagnosticId, string expectedPrefix, out uint code) { code = 0; return diagnosticId.StartsWith(expectedPrefix, StringComparison.Ordinal) && uint.TryParse(diagnosticId.Substring(expectedPrefix.Length), out code); } /// <summary> /// When overridden by a derived class, this property can override the current thread's /// CurrentUICulture property for diagnostic message resource lookups. /// </summary> protected virtual CultureInfo Culture { get { return Arguments.PreferredUILang ?? CultureInfo.CurrentUICulture; } } private static void EmitDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { var key = CreateDeterminismKey(args, rawArgs, baseDirectory, parser); var filePath = Path.Combine(args.OutputDirectory, args.OutputFileName + ".key"); using (var stream = File.Create(filePath)) { var bytes = Encoding.UTF8.GetBytes(key); stream.Write(bytes, 0, bytes.Length); } } /// <summary> /// The string returned from this function represents the inputs to the compiler which impact determinism. It is /// meant to be inline with the specification here: /// /// - https://github.com/dotnet/roslyn/blob/main/docs/compilers/Deterministic%20Inputs.md /// /// Issue #8193 tracks filling this out to the full specification. /// /// https://github.com/dotnet/roslyn/issues/8193 /// </summary> private static string CreateDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { List<Diagnostic> diagnostics = new List<Diagnostic>(); var flattenedArgs = ArrayBuilder<string>.GetInstance(); parser.FlattenArgs(rawArgs, diagnostics, flattenedArgs, null, baseDirectory); var builder = new StringBuilder(); var name = !string.IsNullOrEmpty(args.OutputFileName) ? Path.GetFileNameWithoutExtension(Path.GetFileName(args.OutputFileName)) : $"no-output-name-{Guid.NewGuid().ToString()}"; builder.AppendLine($"{name}"); builder.AppendLine($"Command Line:"); foreach (var current in flattenedArgs) { builder.AppendLine($"\t{current}"); } builder.AppendLine("Source Files:"); var hash = MD5.Create(); foreach (var sourceFile in args.SourceFiles) { var sourceFileName = Path.GetFileName(sourceFile.Path); string hashValue; try { var bytes = File.ReadAllBytes(sourceFile.Path); var hashBytes = hash.ComputeHash(bytes); var data = BitConverter.ToString(hashBytes); hashValue = data.Replace("-", ""); } catch (Exception ex) { hashValue = $"Could not compute {ex.Message}"; } builder.AppendLine($"\t{sourceFileName} - {hashValue}"); } flattenedArgs.Free(); return builder.ToString(); } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Server/VBCSCompiler/CSharpCompilerServer.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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class CSharpCompilerServer : CSharpCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader) { } internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class CSharpCompilerServer : CSharpCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader, driverCache) { } internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader, driverCache) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Server/VBCSCompiler/CompilerRequestHandler.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.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; namespace Microsoft.CodeAnalysis.CompilerServer { internal readonly struct RunRequest { public Guid RequestId { get; } public string Language { get; } public string? WorkingDirectory { get; } public string? TempDirectory { get; } public string? LibDirectory { get; } public string[] Arguments { get; } public RunRequest(Guid requestId, string language, string? workingDirectory, string? tempDirectory, string? libDirectory, string[] arguments) { RequestId = requestId; Language = language; WorkingDirectory = workingDirectory; TempDirectory = tempDirectory; LibDirectory = libDirectory; Arguments = arguments; } } internal sealed class CompilerServerHost : ICompilerServerHost { public IAnalyzerAssemblyLoader AnalyzerAssemblyLoader { get; } = new ShadowCopyAnalyzerAssemblyLoader(Path.Combine(Path.GetTempPath(), "VBCSCompiler", "AnalyzerAssemblyLoader")); public static Func<string, MetadataReferenceProperties, PortableExecutableReference> SharedAssemblyReferenceProvider { get; } = (path, properties) => new CachingMetadataReference(path, properties); /// <summary> /// The caching metadata provider used by the C# and VB compilers /// </summary> private Func<string, MetadataReferenceProperties, PortableExecutableReference> AssemblyReferenceProvider { get; } = SharedAssemblyReferenceProvider; /// <summary> /// Directory that contains the compiler executables and the response files. /// </summary> private string ClientDirectory { get; } /// <summary> /// Directory that contains mscorlib. Can be null when the host is executing in a CoreCLR context. /// </summary> private string SdkDirectory { get; } public ICompilerServerLogger Logger { get; } internal CompilerServerHost(string clientDirectory, string sdkDirectory, ICompilerServerLogger logger) { ClientDirectory = clientDirectory; SdkDirectory = sdkDirectory; Logger = logger; } private bool CheckAnalyzers(string baseDirectory, ImmutableArray<CommandLineAnalyzerReference> analyzers, [NotNullWhen(false)] out List<string>? errorMessages) { return AnalyzerConsistencyChecker.Check(baseDirectory, analyzers, AnalyzerAssemblyLoader, Logger, out errorMessages); } public bool TryCreateCompiler(in RunRequest request, BuildPaths buildPaths, [NotNullWhen(true)] out CommonCompiler? compiler) { switch (request.Language) { case LanguageNames.CSharp: compiler = new CSharpCompilerServer( AssemblyReferenceProvider, args: request.Arguments, buildPaths: buildPaths, libDirectory: request.LibDirectory, analyzerLoader: AnalyzerAssemblyLoader); return true; case LanguageNames.VisualBasic: compiler = new VisualBasicCompilerServer( AssemblyReferenceProvider, args: request.Arguments, buildPaths: buildPaths, libDirectory: request.LibDirectory, analyzerLoader: AnalyzerAssemblyLoader); return true; default: compiler = null; return false; } } public BuildResponse RunCompilation(in RunRequest request, CancellationToken cancellationToken) { Logger.Log($@" Run Compilation for {request.RequestId} Language = {request.Language} CurrentDirectory = '{request.WorkingDirectory} LIB = '{request.LibDirectory}'"); // Compiler server must be provided with a valid current directory in order to correctly // resolve files in the compilation if (string.IsNullOrEmpty(request.WorkingDirectory)) { var message = "Missing working directory"; Logger.Log($"Rejected: {request.RequestId}: {message}"); return new RejectedBuildResponse(message); } // Compiler server must be provided with a valid temporary directory in order to correctly // isolate signing between compilations. if (string.IsNullOrEmpty(request.TempDirectory)) { var message = "Missing temp directory"; Logger.Log($"Rejected: {request.RequestId}: {message}"); return new RejectedBuildResponse(message); } var buildPaths = new BuildPaths(ClientDirectory, request.WorkingDirectory, SdkDirectory, request.TempDirectory); if (!TryCreateCompiler(request, buildPaths, out CommonCompiler? compiler)) { var message = $"Cannot create compiler for language id {request.Language}"; Logger.Log($"Rejected: {request.RequestId}: {message}"); return new RejectedBuildResponse(message); } bool utf8output = compiler.Arguments.Utf8Output; if (!CheckAnalyzers(request.WorkingDirectory, compiler.Arguments.AnalyzerReferences, out List<string>? errorMessages)) { Logger.Log($"Rejected: {request.RequestId}: for analyzer load issues {string.Join(";", errorMessages)}"); return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(errorMessages)); } Logger.Log($"Begin {request.RequestId} {request.Language} compiler run"); try { TextWriter output = new StringWriter(CultureInfo.InvariantCulture); int returnCode = compiler.Run(output, cancellationToken); var outputString = output.ToString(); Logger.Log(@$"End {request.RequestId} {request.Language} compiler run Return code: {returnCode} Output: {outputString}"); return new CompletedBuildResponse(returnCode, utf8output, outputString); } catch (Exception ex) { Logger.LogException(ex, $"Running compilation for {request.RequestId}"); throw; } } } }
// Licensed to the .NET Foundation under one or more 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.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; namespace Microsoft.CodeAnalysis.CompilerServer { internal readonly struct RunRequest { public Guid RequestId { get; } public string Language { get; } public string? WorkingDirectory { get; } public string? TempDirectory { get; } public string? LibDirectory { get; } public string[] Arguments { get; } public RunRequest(Guid requestId, string language, string? workingDirectory, string? tempDirectory, string? libDirectory, string[] arguments) { RequestId = requestId; Language = language; WorkingDirectory = workingDirectory; TempDirectory = tempDirectory; LibDirectory = libDirectory; Arguments = arguments; } } internal sealed class CompilerServerHost : ICompilerServerHost { public IAnalyzerAssemblyLoader AnalyzerAssemblyLoader { get; } = new ShadowCopyAnalyzerAssemblyLoader(Path.Combine(Path.GetTempPath(), "VBCSCompiler", "AnalyzerAssemblyLoader")); public static Func<string, MetadataReferenceProperties, PortableExecutableReference> SharedAssemblyReferenceProvider { get; } = (path, properties) => new CachingMetadataReference(path, properties); /// <summary> /// The caching metadata provider used by the C# and VB compilers /// </summary> private Func<string, MetadataReferenceProperties, PortableExecutableReference> AssemblyReferenceProvider { get; } = SharedAssemblyReferenceProvider; /// <summary> /// Directory that contains the compiler executables and the response files. /// </summary> private string ClientDirectory { get; } /// <summary> /// Directory that contains mscorlib. Can be null when the host is executing in a CoreCLR context. /// </summary> private string SdkDirectory { get; } public ICompilerServerLogger Logger { get; } /// <summary> /// A cache that can store generator drivers in order to enable incrementalism across builds for the lifetime of the server. /// </summary> private readonly GeneratorDriverCache _driverCache = new GeneratorDriverCache(); internal CompilerServerHost(string clientDirectory, string sdkDirectory, ICompilerServerLogger logger) { ClientDirectory = clientDirectory; SdkDirectory = sdkDirectory; Logger = logger; } private bool CheckAnalyzers(string baseDirectory, ImmutableArray<CommandLineAnalyzerReference> analyzers, [NotNullWhen(false)] out List<string>? errorMessages) { return AnalyzerConsistencyChecker.Check(baseDirectory, analyzers, AnalyzerAssemblyLoader, Logger, out errorMessages); } public bool TryCreateCompiler(in RunRequest request, BuildPaths buildPaths, [NotNullWhen(true)] out CommonCompiler? compiler) { switch (request.Language) { case LanguageNames.CSharp: compiler = new CSharpCompilerServer( AssemblyReferenceProvider, args: request.Arguments, buildPaths: buildPaths, libDirectory: request.LibDirectory, analyzerLoader: AnalyzerAssemblyLoader, _driverCache); return true; case LanguageNames.VisualBasic: compiler = new VisualBasicCompilerServer( AssemblyReferenceProvider, args: request.Arguments, buildPaths: buildPaths, libDirectory: request.LibDirectory, analyzerLoader: AnalyzerAssemblyLoader, _driverCache); return true; default: compiler = null; return false; } } public BuildResponse RunCompilation(in RunRequest request, CancellationToken cancellationToken) { Logger.Log($@" Run Compilation for {request.RequestId} Language = {request.Language} CurrentDirectory = '{request.WorkingDirectory} LIB = '{request.LibDirectory}'"); // Compiler server must be provided with a valid current directory in order to correctly // resolve files in the compilation if (string.IsNullOrEmpty(request.WorkingDirectory)) { var message = "Missing working directory"; Logger.Log($"Rejected: {request.RequestId}: {message}"); return new RejectedBuildResponse(message); } // Compiler server must be provided with a valid temporary directory in order to correctly // isolate signing between compilations. if (string.IsNullOrEmpty(request.TempDirectory)) { var message = "Missing temp directory"; Logger.Log($"Rejected: {request.RequestId}: {message}"); return new RejectedBuildResponse(message); } var buildPaths = new BuildPaths(ClientDirectory, request.WorkingDirectory, SdkDirectory, request.TempDirectory); if (!TryCreateCompiler(request, buildPaths, out CommonCompiler? compiler)) { var message = $"Cannot create compiler for language id {request.Language}"; Logger.Log($"Rejected: {request.RequestId}: {message}"); return new RejectedBuildResponse(message); } bool utf8output = compiler.Arguments.Utf8Output; if (!CheckAnalyzers(request.WorkingDirectory, compiler.Arguments.AnalyzerReferences, out List<string>? errorMessages)) { Logger.Log($"Rejected: {request.RequestId}: for analyzer load issues {string.Join(";", errorMessages)}"); return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(errorMessages)); } Logger.Log($"Begin {request.RequestId} {request.Language} compiler run"); try { TextWriter output = new StringWriter(CultureInfo.InvariantCulture); int returnCode = compiler.Run(output, cancellationToken); var outputString = output.ToString(); Logger.Log(@$"End {request.RequestId} {request.Language} compiler run Return code: {returnCode} Output: {outputString}"); return new CompletedBuildResponse(returnCode, utf8output, outputString); } catch (Exception ex) { Logger.LogException(ex, $"Running compilation for {request.RequestId}"); throw; } } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Server/VBCSCompiler/VisualBasicCompilerServer.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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class VisualBasicCompilerServer : VisualBasicCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader) { } internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class VisualBasicCompilerServer : VisualBasicCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader, driverCache) { } internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader, GeneratorDriverCache driverCache) : base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader, driverCache) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Server/VBCSCompilerTests/TouchedFileLoggingTests.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.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.SharedResourceHelpers; using System.Reflection; using Microsoft.CodeAnalysis.CompilerServer; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class TouchedFileLoggingTests : TestBase { private static readonly string s_libDirectory = Environment.GetEnvironmentVariable("LIB"); private readonly string _baseDirectory = TempRoot.Root; private const string HelloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; private const string HelloWorldVB = @"Imports System Class C Shared Sub Main(args As String()) Console.WriteLine(""Hello, world"") End Sub End Class "; [ConditionalFact(typeof(DesktopOnly))] public void CSharpTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldCS).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new CSharpCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader()); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (String f in filelist) { CleanupAllGeneratedFiles(f); } } [ConditionalFact(typeof(DesktopOnly))] public void VisualBasicTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldVB).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new VisualBasicCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader()); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (string f in filelist) { CleanupAllGeneratedFiles(f); } } /// <summary> /// Builds the expected base of touched files. /// Adds a hook for temporary file creation as well, /// so this method must be called before the execution of /// Csc.Run. /// </summary> private static void BuildTouchedFiles(CommonCompiler cmd, string outputPath, out List<string> expectedReads, out List<string> expectedWrites) { expectedReads = new List<string>(); expectedReads.AddRange(cmd.Arguments.MetadataReferences.Select(r => r.Reference)); if (cmd.Arguments is VisualBasicCommandLineArguments { DefaultCoreLibraryReference: { } reference }) { expectedReads.Add(reference.Reference); } foreach (var file in cmd.Arguments.SourceFiles) { expectedReads.Add(file.Path); } var writes = new List<string>(); writes.Add(outputPath); expectedWrites = writes; } private static void AssertTouchedFilesEqual( List<string> expectedReads, List<string> expectedWrites, string touchedFilesBase) { var touchedReadPath = touchedFilesBase + ".read"; var touchedWritesPath = touchedFilesBase + ".write"; var expected = expectedReads.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedReadPath).Trim()); expected = expectedWrites.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedWritesPath).Trim()); } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.SharedResourceHelpers; using System.Reflection; using Microsoft.CodeAnalysis.CompilerServer; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class TouchedFileLoggingTests : TestBase { private static readonly string s_libDirectory = Environment.GetEnvironmentVariable("LIB"); private readonly string _baseDirectory = TempRoot.Root; private const string HelloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; private const string HelloWorldVB = @"Imports System Class C Shared Sub Main(args As String()) Console.WriteLine(""Hello, world"") End Sub End Class "; [ConditionalFact(typeof(DesktopOnly))] public void CSharpTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldCS).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new CSharpCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader(), driverCache: null); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (String f in filelist) { CleanupAllGeneratedFiles(f); } } [ConditionalFact(typeof(DesktopOnly))] public void VisualBasicTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldVB).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new VisualBasicCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader(), driverCache: null); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (string f in filelist) { CleanupAllGeneratedFiles(f); } } /// <summary> /// Builds the expected base of touched files. /// Adds a hook for temporary file creation as well, /// so this method must be called before the execution of /// Csc.Run. /// </summary> private static void BuildTouchedFiles(CommonCompiler cmd, string outputPath, out List<string> expectedReads, out List<string> expectedWrites) { expectedReads = new List<string>(); expectedReads.AddRange(cmd.Arguments.MetadataReferences.Select(r => r.Reference)); if (cmd.Arguments is VisualBasicCommandLineArguments { DefaultCoreLibraryReference: { } reference }) { expectedReads.Add(reference.Reference); } foreach (var file in cmd.Arguments.SourceFiles) { expectedReads.Add(file.Path); } var writes = new List<string>(); writes.Add(outputPath); expectedWrites = writes; } private static void AssertTouchedFilesEqual( List<string> expectedReads, List<string> expectedWrites, string touchedFilesBase) { var touchedReadPath = touchedFilesBase + ".read"; var touchedWritesPath = touchedFilesBase + ".write"; var expected = expectedReads.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedReadPath).Trim()); expected = expectedWrites.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedWritesPath).Trim()); } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Test/Utilities/CSharp/MockCSharpCompiler.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.IO; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { internal class MockCSharpCompiler : CSharpCompiler { private readonly ImmutableArray<DiagnosticAnalyzer> _analyzers; private readonly ImmutableArray<ISourceGenerator> _generators; internal Compilation Compilation; internal AnalyzerOptions AnalyzerOptions; public MockCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) : this(responseFile, CreateBuildPaths(workingDirectory), args, analyzers, generators, loader) { } public MockCSharpCompiler(string responseFile, BuildPaths buildPaths, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, Environment.GetEnvironmentVariable("LIB"), loader ?? new DefaultAnalyzerAssemblyLoader()) { _analyzers = analyzers.NullToEmpty(); _generators = generators.NullToEmpty(); } private static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null) => RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory); protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { base.ResolveAnalyzersFromArguments(diagnostics, messageProvider, skipAnalyzers, out analyzers, out generators); if (!_analyzers.IsDefaultOrEmpty) { analyzers = analyzers.InsertRange(0, _analyzers); } if (!_generators.IsDefaultOrEmpty) { generators = generators.InsertRange(0, _generators); } } public Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger) => CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt: default, globalDiagnosticOptionsOpt: default); public override Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> syntaxDiagOptionsOpt, AnalyzerConfigOptionsResult globalDiagnosticOptionsOpt) { Compilation = base.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt, globalDiagnosticOptionsOpt); return Compilation; } protected override AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) { AnalyzerOptions = base.CreateAnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); return AnalyzerOptions; } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { internal class MockCSharpCompiler : CSharpCompiler { private readonly ImmutableArray<DiagnosticAnalyzer> _analyzers; private readonly ImmutableArray<ISourceGenerator> _generators; internal Compilation Compilation; internal AnalyzerOptions AnalyzerOptions; public MockCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) : this(responseFile, CreateBuildPaths(workingDirectory), args, analyzers, generators, loader) { } public MockCSharpCompiler(string responseFile, BuildPaths buildPaths, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null, GeneratorDriverCache driverCache = null) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, Environment.GetEnvironmentVariable("LIB"), loader ?? new DefaultAnalyzerAssemblyLoader(), driverCache) { _analyzers = analyzers.NullToEmpty(); _generators = generators.NullToEmpty(); } private static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null) => RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory); protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { base.ResolveAnalyzersFromArguments(diagnostics, messageProvider, skipAnalyzers, out analyzers, out generators); if (!_analyzers.IsDefaultOrEmpty) { analyzers = analyzers.InsertRange(0, _analyzers); } if (!_generators.IsDefaultOrEmpty) { generators = generators.InsertRange(0, _generators); } } public Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger) => CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt: default, globalDiagnosticOptionsOpt: default); public override Compilation CreateCompilation( TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> syntaxDiagOptionsOpt, AnalyzerConfigOptionsResult globalDiagnosticOptionsOpt) { Compilation = base.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, syntaxDiagOptionsOpt, globalDiagnosticOptionsOpt); return Compilation; } protected override AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) { AnalyzerOptions = base.CreateAnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); return AnalyzerOptions; } } }
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCompiler.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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicCompiler Inherits CommonCompiler Friend Const ResponseFileName As String = "vbc.rsp" Friend Const VbcCommandLinePrefix = "vbc : " 'Common prefix String For VB diagnostic output with no location. Private Shared ReadOnly s_responseFileName As String Private ReadOnly _responseFile As String Private ReadOnly _diagnosticFormatter As CommandLineDiagnosticFormatter Private ReadOnly _tempDirectory As String Private _additionalTextFiles As ImmutableArray(Of AdditionalTextFile) Protected Sub New(parser As VisualBasicCommandLineParser, responseFile As String, args As String(), buildPaths As BuildPaths, additionalReferenceDirectories As String, analyzerLoader As IAnalyzerAssemblyLoader) MyBase.New(parser, responseFile, args, buildPaths, additionalReferenceDirectories, analyzerLoader) _diagnosticFormatter = New CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, AddressOf GetAdditionalTextFiles) _additionalTextFiles = Nothing _tempDirectory = buildPaths.TempDirectory Debug.Assert(Arguments.OutputFileName IsNot Nothing OrElse Arguments.Errors.Length > 0 OrElse parser.IsScriptCommandLineParser) End Sub Private Function GetAdditionalTextFiles() As ImmutableArray(Of AdditionalTextFile) Debug.Assert(Not _additionalTextFiles.IsDefault, "GetAdditionalTextFiles called before ResolveAdditionalFilesFromArguments") Return _additionalTextFiles End Function Protected Overrides Function ResolveAdditionalFilesFromArguments(diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, touchedFilesLogger As TouchedFileLogger) As ImmutableArray(Of AdditionalTextFile) _additionalTextFiles = MyBase.ResolveAdditionalFilesFromArguments(diagnostics, messageProvider, touchedFilesLogger) Return _additionalTextFiles End Function Friend Overloads ReadOnly Property Arguments As VisualBasicCommandLineArguments Get Return DirectCast(MyBase.Arguments, VisualBasicCommandLineArguments) End Get End Property Public Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter Get Return _diagnosticFormatter End Get End Property Private Function ParseFile(consoleOutput As TextWriter, parseOptions As VisualBasicParseOptions, scriptParseOptions As VisualBasicParseOptions, ByRef hadErrors As Boolean, file As CommandLineSourceFile, errorLogger As ErrorLogger) As SyntaxTree Dim fileReadDiagnostics As New List(Of DiagnosticInfo)() Dim content = TryReadFileContent(file, fileReadDiagnostics) If content Is Nothing Then ReportDiagnostics(fileReadDiagnostics, consoleOutput, errorLogger, compilation:=Nothing) fileReadDiagnostics.Clear() hadErrors = True Return Nothing End If Dim tree = VisualBasicSyntaxTree.ParseText( content, If(file.IsScript, scriptParseOptions, parseOptions), file.Path) ' prepopulate line tables. ' we will need line tables anyways and it is better to Not wait until we are in emit ' where things run sequentially. Dim isHiddenDummy As Boolean tree.GetMappedLineSpanAndVisibility(Nothing, isHiddenDummy) Return tree End Function Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, analyzerConfigOptions As ImmutableArray(Of AnalyzerConfigOptionsResult), globalAnalyzerConfigOptions As AnalyzerConfigOptionsResult) As Compilation Dim parseOptions = Arguments.ParseOptions ' We compute script parse options once so we don't have to do it repeatedly in ' case there are many script files. Dim scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script) Dim hadErrors As Boolean = False Dim sourceFiles As ImmutableArray(Of CommandLineSourceFile) = Arguments.SourceFiles Dim trees(sourceFiles.Length - 1) As SyntaxTree If Arguments.CompilationOptions.ConcurrentBuild Then RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture(Of Integer)( Sub(i As Integer) ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) End Sub), CancellationToken.None) Else For i = 0 To sourceFiles.Length - 1 ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) Next End If If hadErrors Then Return Nothing End If If Arguments.TouchedFilesPath IsNot Nothing Then For Each file In sourceFiles touchedFilesLogger.AddRead(file.Path) Next End If Dim diagnostics = New List(Of DiagnosticInfo)() Dim assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default Dim referenceDirectiveResolver As MetadataReferenceResolver = Nothing Dim resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, referenceDirectiveResolver) If ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation:=Nothing) Then Return Nothing End If If Arguments.OutputLevel = OutputLevel.Verbose Then PrintReferences(resolvedReferences, consoleOutput) End If Dim xmlFileResolver = New LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger) ' TODO: support for #load search paths Dim sourceFileResolver = New LoggingSourceFileResolver(ImmutableArray(Of String).Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger) Dim loggingFileSystem = New LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory) Dim syntaxTreeOptions = New CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalAnalyzerConfigOptions) Return VisualBasicCompilation.Create( Arguments.CompilationName, trees, resolvedReferences, Arguments.CompilationOptions. WithMetadataReferenceResolver(referenceDirectiveResolver). WithAssemblyIdentityComparer(assemblyIdentityComparer). WithXmlReferenceResolver(xmlFileResolver). WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)). WithSourceReferenceResolver(sourceFileResolver). WithSyntaxTreeOptionsProvider(syntaxTreeOptions)) End Function Protected Overrides Function GetOutputFileName(compilation As Compilation, cancellationToken As CancellationToken) As String ' The only case this is Nothing is when there are errors during parsing in which case this should never get called Debug.Assert(Arguments.OutputFileName IsNot Nothing) Return Arguments.OutputFileName End Function Private Sub PrintReferences(resolvedReferences As List(Of MetadataReference), consoleOutput As TextWriter) For Each reference In resolvedReferences If reference.Properties.Kind = MetadataImageKind.Module Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDMODULE, Culture), reference.Display) ElseIf reference.Properties.EmbedInteropTypes Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDLINKREFERENCE, Culture), reference.Display) Else consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDREFERENCE, Culture), reference.Display) End If Next consoleOutput.WriteLine() End Sub Friend Overrides Function SuppressDefaultResponseFile(args As IEnumerable(Of String)) As Boolean For Each arg In args Select Case arg.ToLowerInvariant Case "/noconfig", "-noconfig", "/nostdlib", "-nostdlib" Return True End Select Next Return False End Function ''' <summary> ''' Print compiler logo ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintLogo(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine2, Culture)) consoleOutput.WriteLine() End Sub Friend Overrides Function GetToolName() As String Return ErrorFactory.IdToString(ERRID.IDS_ToolName, Culture) End Function Friend Overrides ReadOnly Property Type As Type Get ' We do not use Me.GetType() so that we don't break mock subtypes Return GetType(VisualBasicCompiler) End Get End Property ''' <summary> ''' Print Commandline help message (up to 80 English characters per line) ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintHelp(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_VBCHelp, Culture)) End Sub Public Overrides Sub PrintLangVersions(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LangVersions, Culture)) Dim defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion() Dim latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion() For Each v As LanguageVersion In System.Enum.GetValues(GetType(LanguageVersion)) If v = defaultVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (default)") ElseIf v = latestVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)") Else consoleOutput.WriteLine(v.ToDisplayString()) End If Next consoleOutput.WriteLine() End Sub Protected Overrides Function TryGetCompilerDiagnosticCode(diagnosticId As String, ByRef code As UInteger) As Boolean Return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "BC", code) End Function Protected Overrides Sub ResolveAnalyzersFromArguments( diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, skipAnalyzers As Boolean, ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer), ByRef generators As ImmutableArray(Of ISourceGenerator)) Arguments.ResolveAnalyzersFromArguments(LanguageNames.VisualBasic, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, analyzers, generators) End Sub Protected Overrides Sub ResolveEmbeddedFilesFromExternalSourceDirectives( tree As SyntaxTree, resolver As SourceReferenceResolver, embeddedFiles As OrderedSet(Of String), diagnostics As DiagnosticBag) For Each directive As ExternalSourceDirectiveTriviaSyntax In tree.GetRoot().GetDirectives( Function(d) d.Kind() = SyntaxKind.ExternalSourceDirectiveTrivia) If directive.ExternalSource.IsMissing Then Continue For End If Dim path = CStr(directive.ExternalSource.Value) If path Is Nothing Then Continue For End If Dim resolvedPath = resolver.ResolveReference(path, tree.FilePath) If resolvedPath Is Nothing Then diagnostics.Add( MessageProvider.CreateDiagnostic( MessageProvider.ERR_FileNotFound, directive.ExternalSource.GetLocation(), path)) Continue For End If embeddedFiles.Add(resolvedPath) Next End Sub Private Protected Overrides Function RunGenerators(input As Compilation, parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), diagnostics As DiagnosticBag) As Compilation Dim driver = VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), analyzerConfigOptionsProvider) Dim compilationOut As Compilation = Nothing, generatorDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(input, compilationOut, generatorDiagnostics) diagnostics.AddRange(generatorDiagnostics) Return compilationOut 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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicCompiler Inherits CommonCompiler Friend Const ResponseFileName As String = "vbc.rsp" Friend Const VbcCommandLinePrefix = "vbc : " 'Common prefix String For VB diagnostic output with no location. Private Shared ReadOnly s_responseFileName As String Private ReadOnly _responseFile As String Private ReadOnly _diagnosticFormatter As CommandLineDiagnosticFormatter Private ReadOnly _tempDirectory As String Private _additionalTextFiles As ImmutableArray(Of AdditionalTextFile) Protected Sub New(parser As VisualBasicCommandLineParser, responseFile As String, args As String(), buildPaths As BuildPaths, additionalReferenceDirectories As String, analyzerLoader As IAnalyzerAssemblyLoader, Optional driverCache As GeneratorDriverCache = Nothing) MyBase.New(parser, responseFile, args, buildPaths, additionalReferenceDirectories, analyzerLoader, driverCache) _diagnosticFormatter = New CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, AddressOf GetAdditionalTextFiles) _additionalTextFiles = Nothing _tempDirectory = buildPaths.TempDirectory Debug.Assert(Arguments.OutputFileName IsNot Nothing OrElse Arguments.Errors.Length > 0 OrElse parser.IsScriptCommandLineParser) End Sub Private Function GetAdditionalTextFiles() As ImmutableArray(Of AdditionalTextFile) Debug.Assert(Not _additionalTextFiles.IsDefault, "GetAdditionalTextFiles called before ResolveAdditionalFilesFromArguments") Return _additionalTextFiles End Function Protected Overrides Function ResolveAdditionalFilesFromArguments(diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, touchedFilesLogger As TouchedFileLogger) As ImmutableArray(Of AdditionalTextFile) _additionalTextFiles = MyBase.ResolveAdditionalFilesFromArguments(diagnostics, messageProvider, touchedFilesLogger) Return _additionalTextFiles End Function Friend Overloads ReadOnly Property Arguments As VisualBasicCommandLineArguments Get Return DirectCast(MyBase.Arguments, VisualBasicCommandLineArguments) End Get End Property Public Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter Get Return _diagnosticFormatter End Get End Property Private Function ParseFile(consoleOutput As TextWriter, parseOptions As VisualBasicParseOptions, scriptParseOptions As VisualBasicParseOptions, ByRef hadErrors As Boolean, file As CommandLineSourceFile, errorLogger As ErrorLogger) As SyntaxTree Dim fileReadDiagnostics As New List(Of DiagnosticInfo)() Dim content = TryReadFileContent(file, fileReadDiagnostics) If content Is Nothing Then ReportDiagnostics(fileReadDiagnostics, consoleOutput, errorLogger, compilation:=Nothing) fileReadDiagnostics.Clear() hadErrors = True Return Nothing End If Dim tree = VisualBasicSyntaxTree.ParseText( content, If(file.IsScript, scriptParseOptions, parseOptions), file.Path) ' prepopulate line tables. ' we will need line tables anyways and it is better to Not wait until we are in emit ' where things run sequentially. Dim isHiddenDummy As Boolean tree.GetMappedLineSpanAndVisibility(Nothing, isHiddenDummy) Return tree End Function Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, analyzerConfigOptions As ImmutableArray(Of AnalyzerConfigOptionsResult), globalAnalyzerConfigOptions As AnalyzerConfigOptionsResult) As Compilation Dim parseOptions = Arguments.ParseOptions ' We compute script parse options once so we don't have to do it repeatedly in ' case there are many script files. Dim scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script) Dim hadErrors As Boolean = False Dim sourceFiles As ImmutableArray(Of CommandLineSourceFile) = Arguments.SourceFiles Dim trees(sourceFiles.Length - 1) As SyntaxTree If Arguments.CompilationOptions.ConcurrentBuild Then RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture(Of Integer)( Sub(i As Integer) ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) End Sub), CancellationToken.None) Else For i = 0 To sourceFiles.Length - 1 ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) Next End If If hadErrors Then Return Nothing End If If Arguments.TouchedFilesPath IsNot Nothing Then For Each file In sourceFiles touchedFilesLogger.AddRead(file.Path) Next End If Dim diagnostics = New List(Of DiagnosticInfo)() Dim assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default Dim referenceDirectiveResolver As MetadataReferenceResolver = Nothing Dim resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, referenceDirectiveResolver) If ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation:=Nothing) Then Return Nothing End If If Arguments.OutputLevel = OutputLevel.Verbose Then PrintReferences(resolvedReferences, consoleOutput) End If Dim xmlFileResolver = New LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger) ' TODO: support for #load search paths Dim sourceFileResolver = New LoggingSourceFileResolver(ImmutableArray(Of String).Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger) Dim loggingFileSystem = New LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory) Dim syntaxTreeOptions = New CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalAnalyzerConfigOptions) Return VisualBasicCompilation.Create( Arguments.CompilationName, trees, resolvedReferences, Arguments.CompilationOptions. WithMetadataReferenceResolver(referenceDirectiveResolver). WithAssemblyIdentityComparer(assemblyIdentityComparer). WithXmlReferenceResolver(xmlFileResolver). WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)). WithSourceReferenceResolver(sourceFileResolver). WithSyntaxTreeOptionsProvider(syntaxTreeOptions)) End Function Protected Overrides Function GetOutputFileName(compilation As Compilation, cancellationToken As CancellationToken) As String ' The only case this is Nothing is when there are errors during parsing in which case this should never get called Debug.Assert(Arguments.OutputFileName IsNot Nothing) Return Arguments.OutputFileName End Function Private Sub PrintReferences(resolvedReferences As List(Of MetadataReference), consoleOutput As TextWriter) For Each reference In resolvedReferences If reference.Properties.Kind = MetadataImageKind.Module Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDMODULE, Culture), reference.Display) ElseIf reference.Properties.EmbedInteropTypes Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDLINKREFERENCE, Culture), reference.Display) Else consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDREFERENCE, Culture), reference.Display) End If Next consoleOutput.WriteLine() End Sub Friend Overrides Function SuppressDefaultResponseFile(args As IEnumerable(Of String)) As Boolean For Each arg In args Select Case arg.ToLowerInvariant Case "/noconfig", "-noconfig", "/nostdlib", "-nostdlib" Return True End Select Next Return False End Function ''' <summary> ''' Print compiler logo ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintLogo(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine2, Culture)) consoleOutput.WriteLine() End Sub Friend Overrides Function GetToolName() As String Return ErrorFactory.IdToString(ERRID.IDS_ToolName, Culture) End Function Friend Overrides ReadOnly Property Type As Type Get ' We do not use Me.GetType() so that we don't break mock subtypes Return GetType(VisualBasicCompiler) End Get End Property ''' <summary> ''' Print Commandline help message (up to 80 English characters per line) ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintHelp(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_VBCHelp, Culture)) End Sub Public Overrides Sub PrintLangVersions(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LangVersions, Culture)) Dim defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion() Dim latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion() For Each v As LanguageVersion In System.Enum.GetValues(GetType(LanguageVersion)) If v = defaultVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (default)") ElseIf v = latestVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)") Else consoleOutput.WriteLine(v.ToDisplayString()) End If Next consoleOutput.WriteLine() End Sub Protected Overrides Function TryGetCompilerDiagnosticCode(diagnosticId As String, ByRef code As UInteger) As Boolean Return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "BC", code) End Function Protected Overrides Sub ResolveAnalyzersFromArguments( diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, skipAnalyzers As Boolean, ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer), ByRef generators As ImmutableArray(Of ISourceGenerator)) Arguments.ResolveAnalyzersFromArguments(LanguageNames.VisualBasic, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, analyzers, generators) End Sub Protected Overrides Sub ResolveEmbeddedFilesFromExternalSourceDirectives( tree As SyntaxTree, resolver As SourceReferenceResolver, embeddedFiles As OrderedSet(Of String), diagnostics As DiagnosticBag) For Each directive As ExternalSourceDirectiveTriviaSyntax In tree.GetRoot().GetDirectives( Function(d) d.Kind() = SyntaxKind.ExternalSourceDirectiveTrivia) If directive.ExternalSource.IsMissing Then Continue For End If Dim path = CStr(directive.ExternalSource.Value) If path Is Nothing Then Continue For End If Dim resolvedPath = resolver.ResolveReference(path, tree.FilePath) If resolvedPath Is Nothing Then diagnostics.Add( MessageProvider.CreateDiagnostic( MessageProvider.ERR_FileNotFound, directive.ExternalSource.GetLocation(), path)) Continue For End If embeddedFiles.Add(resolvedPath) Next End Sub Private Protected Overrides Function CreateGeneratorDriver(parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText)) As GeneratorDriver Return VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), analyzerConfigOptionsProvider) End Function End Class End Namespace
1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Portable/Symbols/MergedNamespaceSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A MergedNamespaceSymbol represents a namespace that merges the contents of two or more other /// namespaces. Any sub-namespaces with the same names are also merged if they have two or more /// instances. /// /// Merged namespaces are used to merge the symbols from multiple metadata modules and the /// source "module" into a single symbol tree that represents all the available symbols. The /// compiler resolves names against this merged set of symbols. /// /// Typically there will not be very many merged namespaces in a Compilation: only the root /// namespaces and namespaces that are used in multiple referenced modules. (Microsoft, System, /// System.Xml, System.Diagnostics, System.Threading, ...) /// </summary> internal sealed class MergedNamespaceSymbol : NamespaceSymbol { private readonly NamespaceExtent _extent; private readonly ImmutableArray<NamespaceSymbol> _namespacesToMerge; private readonly NamespaceSymbol _containingNamespace; // used when this namespace is constructed as the result of an extern alias directive private readonly string _nameOpt; // The cachedLookup caches results of lookups on the constituent namespaces so that // subsequent lookups for the same name are much faster than having to ask each of the // constituent namespaces. private readonly CachingDictionary<string, Symbol> _cachedLookup; // GetMembers() is repeatedly called on merged namespaces in some IDE scenarios. // This caches the result that is built by asking the 'cachedLookup' for a concatenated // view of all of its values. private ImmutableArray<Symbol> _allMembers; /// <summary> /// Create a possibly merged namespace symbol. If only a single namespace is passed it, it /// is just returned directly. If two or more namespaces are passed in, then a new merged /// namespace is created with the given extent and container. /// </summary> /// <param name="extent">The namespace extent to use, IF a merged namespace is created.</param> /// <param name="containingNamespace">The containing namespace to used, IF a merged /// namespace is created.</param> /// <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it /// is returned. The merged namespace symbol may hold onto the array.</param> /// <param name="nameOpt">An optional name to give the resulting namespace.</param> /// <returns>A namespace symbol representing the merged namespace.</returns> internal static NamespaceSymbol Create( NamespaceExtent extent, NamespaceSymbol containingNamespace, ImmutableArray<NamespaceSymbol> namespacesToMerge, string nameOpt = null) { // Currently, if we are just merging 1 namespace, we just return the namespace itself. // This is by far the most efficient, because it means that we don't create merged // namespaces (which have a fair amount of memory overhead) unless there is actual // merging going on. However, it means that the child namespace of a Compilation extent // namespace may be a Module extent namespace, and the containing of that module extent // namespace will be another module extent namespace. This is basically no different // than type members of namespaces, so it shouldn't be TOO unexpected. // EDMAURER if the caller is supplying a name, then produce the merged namespace with // the new name even if only a single namespace was provided. This behavior was introduced // to support nice extern alias error reporting. Debug.Assert(namespacesToMerge.Length != 0); return (namespacesToMerge.Length == 1 && nameOpt == null) ? namespacesToMerge[0] : new MergedNamespaceSymbol(extent, containingNamespace, namespacesToMerge, nameOpt); } // Constructor. Use static Create method to create instances. private MergedNamespaceSymbol(NamespaceExtent extent, NamespaceSymbol containingNamespace, ImmutableArray<NamespaceSymbol> namespacesToMerge, string nameOpt) { _extent = extent; _namespacesToMerge = namespacesToMerge; _containingNamespace = containingNamespace; _cachedLookup = new CachingDictionary<string, Symbol>(SlowGetChildrenOfName, SlowGetChildNames, EqualityComparer<string>.Default); _nameOpt = nameOpt; #if DEBUG // We shouldn't merged namespaces that are already merged. foreach (NamespaceSymbol ns in namespacesToMerge) { Debug.Assert(ns.ConstituentNamespaces.Length == 1); } #endif } internal NamespaceSymbol GetConstituentForCompilation(CSharpCompilation compilation) { //return namespacesToMerge.FirstOrDefault(n => n.IsFromSource); //Replace above code with that below to eliminate allocation of array enumerator. foreach (var n in _namespacesToMerge) { if (n.IsFromCompilation(compilation)) return n; } return null; } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { foreach (var part in _namespacesToMerge) { cancellationToken.ThrowIfCancellationRequested(); part.ForceComplete(locationOpt, cancellationToken); } } /// <summary> /// Method that is called from the CachingLookup to lookup the children of a given name. /// Looks in all the constituent namespaces. /// </summary> private ImmutableArray<Symbol> SlowGetChildrenOfName(string name) { ArrayBuilder<NamespaceSymbol> namespaceSymbols = null; var otherSymbols = ArrayBuilder<Symbol>.GetInstance(); // Accumulate all the child namespaces and types. foreach (NamespaceSymbol namespaceSymbol in _namespacesToMerge) { foreach (Symbol childSymbol in namespaceSymbol.GetMembers(name)) { if (childSymbol.Kind == SymbolKind.Namespace) { namespaceSymbols = namespaceSymbols ?? ArrayBuilder<NamespaceSymbol>.GetInstance(); namespaceSymbols.Add((NamespaceSymbol)childSymbol); } else { otherSymbols.Add(childSymbol); } } } if (namespaceSymbols != null) { otherSymbols.Add(MergedNamespaceSymbol.Create(_extent, this, namespaceSymbols.ToImmutableAndFree())); } return otherSymbols.ToImmutableAndFree(); } /// <summary> /// Method that is called from the CachingLookup to get all child names. Looks in all /// constituent namespaces. /// </summary> private HashSet<string> SlowGetChildNames(IEqualityComparer<string> comparer) { var childNames = new HashSet<string>(comparer); foreach (var ns in _namespacesToMerge) { foreach (var child in ns.GetMembersUnordered()) { childNames.Add(child.Name); } } return childNames; } public override string Name { get { return _nameOpt ?? _namespacesToMerge[0].Name; } } internal override NamespaceExtent Extent { get { return _extent; } } public override ImmutableArray<NamespaceSymbol> ConstituentNamespaces { get { return _namespacesToMerge; } } public override ImmutableArray<Symbol> GetMembers() { // Return all the elements from every IGrouping in the ILookup. if (_allMembers.IsDefault) { var builder = ArrayBuilder<Symbol>.GetInstance(); _cachedLookup.AddValues(builder); _allMembers = builder.ToImmutableAndFree(); } return _allMembers; } public override ImmutableArray<Symbol> GetMembers(string name) { return _cachedLookup[name]; } internal sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return ImmutableArray.CreateRange<NamedTypeSymbol>(GetMembersUnordered().OfType<NamedTypeSymbol>()); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray.CreateRange<NamedTypeSymbol>(GetMembers().OfType<NamedTypeSymbol>()); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { // TODO - This is really inefficient. Creating a new array on each lookup needs to fixed! return ImmutableArray.CreateRange<NamedTypeSymbol>(_cachedLookup[name].OfType<NamedTypeSymbol>()); } public override Symbol ContainingSymbol { get { return _containingNamespace; } } public override AssemblySymbol ContainingAssembly { get { if (_extent.Kind == NamespaceKind.Module) { return _extent.Module.ContainingAssembly; } else if (_extent.Kind == NamespaceKind.Assembly) { return _extent.Assembly; } else { return null; } } } public override ImmutableArray<Location> Locations { // Merge the locations of all constituent namespaces. get { //TODO: cache return _namespacesToMerge.SelectMany(namespaceSymbol => namespaceSymbol.Locations).AsImmutable(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _namespacesToMerge.SelectMany(namespaceSymbol => namespaceSymbol.DeclaringSyntaxReferences).AsImmutable(); } } internal override void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string name, int arity, LookupOptions options) { foreach (NamespaceSymbol namespaceSymbol in _namespacesToMerge) { namespaceSymbol.GetExtensionMethods(methods, name, arity, 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A MergedNamespaceSymbol represents a namespace that merges the contents of two or more other /// namespaces. Any sub-namespaces with the same names are also merged if they have two or more /// instances. /// /// Merged namespaces are used to merge the symbols from multiple metadata modules and the /// source "module" into a single symbol tree that represents all the available symbols. The /// compiler resolves names against this merged set of symbols. /// /// Typically there will not be very many merged namespaces in a Compilation: only the root /// namespaces and namespaces that are used in multiple referenced modules. (Microsoft, System, /// System.Xml, System.Diagnostics, System.Threading, ...) /// </summary> internal sealed class MergedNamespaceSymbol : NamespaceSymbol { private readonly NamespaceExtent _extent; private readonly ImmutableArray<NamespaceSymbol> _namespacesToMerge; private readonly NamespaceSymbol _containingNamespace; // used when this namespace is constructed as the result of an extern alias directive private readonly string _nameOpt; // The cachedLookup caches results of lookups on the constituent namespaces so that // subsequent lookups for the same name are much faster than having to ask each of the // constituent namespaces. private readonly CachingDictionary<string, Symbol> _cachedLookup; // GetMembers() is repeatedly called on merged namespaces in some IDE scenarios. // This caches the result that is built by asking the 'cachedLookup' for a concatenated // view of all of its values. private ImmutableArray<Symbol> _allMembers; /// <summary> /// Create a possibly merged namespace symbol. If only a single namespace is passed it, it /// is just returned directly. If two or more namespaces are passed in, then a new merged /// namespace is created with the given extent and container. /// </summary> /// <param name="extent">The namespace extent to use, IF a merged namespace is created.</param> /// <param name="containingNamespace">The containing namespace to used, IF a merged /// namespace is created.</param> /// <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it /// is returned. The merged namespace symbol may hold onto the array.</param> /// <param name="nameOpt">An optional name to give the resulting namespace.</param> /// <returns>A namespace symbol representing the merged namespace.</returns> internal static NamespaceSymbol Create( NamespaceExtent extent, NamespaceSymbol containingNamespace, ImmutableArray<NamespaceSymbol> namespacesToMerge, string nameOpt = null) { // Currently, if we are just merging 1 namespace, we just return the namespace itself. // This is by far the most efficient, because it means that we don't create merged // namespaces (which have a fair amount of memory overhead) unless there is actual // merging going on. However, it means that the child namespace of a Compilation extent // namespace may be a Module extent namespace, and the containing of that module extent // namespace will be another module extent namespace. This is basically no different // than type members of namespaces, so it shouldn't be TOO unexpected. // EDMAURER if the caller is supplying a name, then produce the merged namespace with // the new name even if only a single namespace was provided. This behavior was introduced // to support nice extern alias error reporting. Debug.Assert(namespacesToMerge.Length != 0); return (namespacesToMerge.Length == 1 && nameOpt == null) ? namespacesToMerge[0] : new MergedNamespaceSymbol(extent, containingNamespace, namespacesToMerge, nameOpt); } // Constructor. Use static Create method to create instances. private MergedNamespaceSymbol(NamespaceExtent extent, NamespaceSymbol containingNamespace, ImmutableArray<NamespaceSymbol> namespacesToMerge, string nameOpt) { _extent = extent; _namespacesToMerge = namespacesToMerge; _containingNamespace = containingNamespace; _cachedLookup = new CachingDictionary<string, Symbol>(SlowGetChildrenOfName, SlowGetChildNames, EqualityComparer<string>.Default); _nameOpt = nameOpt; #if DEBUG // We shouldn't merged namespaces that are already merged. foreach (NamespaceSymbol ns in namespacesToMerge) { Debug.Assert(ns.ConstituentNamespaces.Length == 1); } #endif } internal NamespaceSymbol GetConstituentForCompilation(CSharpCompilation compilation) { //return namespacesToMerge.FirstOrDefault(n => n.IsFromSource); //Replace above code with that below to eliminate allocation of array enumerator. foreach (var n in _namespacesToMerge) { if (n.IsFromCompilation(compilation)) return n; } return null; } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { foreach (var part in _namespacesToMerge) { cancellationToken.ThrowIfCancellationRequested(); part.ForceComplete(locationOpt, cancellationToken); } } /// <summary> /// Method that is called from the CachingLookup to lookup the children of a given name. /// Looks in all the constituent namespaces. /// </summary> private ImmutableArray<Symbol> SlowGetChildrenOfName(string name) { ArrayBuilder<NamespaceSymbol> namespaceSymbols = null; var otherSymbols = ArrayBuilder<Symbol>.GetInstance(); // Accumulate all the child namespaces and types. foreach (NamespaceSymbol namespaceSymbol in _namespacesToMerge) { foreach (Symbol childSymbol in namespaceSymbol.GetMembers(name)) { if (childSymbol.Kind == SymbolKind.Namespace) { namespaceSymbols = namespaceSymbols ?? ArrayBuilder<NamespaceSymbol>.GetInstance(); namespaceSymbols.Add((NamespaceSymbol)childSymbol); } else { otherSymbols.Add(childSymbol); } } } if (namespaceSymbols != null) { otherSymbols.Add(MergedNamespaceSymbol.Create(_extent, this, namespaceSymbols.ToImmutableAndFree())); } return otherSymbols.ToImmutableAndFree(); } /// <summary> /// Method that is called from the CachingLookup to get all child names. Looks in all /// constituent namespaces. /// </summary> private HashSet<string> SlowGetChildNames(IEqualityComparer<string> comparer) { var childNames = new HashSet<string>(comparer); foreach (var ns in _namespacesToMerge) { foreach (var child in ns.GetMembersUnordered()) { childNames.Add(child.Name); } } return childNames; } public override string Name { get { return _nameOpt ?? _namespacesToMerge[0].Name; } } internal override NamespaceExtent Extent { get { return _extent; } } public override ImmutableArray<NamespaceSymbol> ConstituentNamespaces { get { return _namespacesToMerge; } } public override ImmutableArray<Symbol> GetMembers() { // Return all the elements from every IGrouping in the ILookup. if (_allMembers.IsDefault) { var builder = ArrayBuilder<Symbol>.GetInstance(); _cachedLookup.AddValues(builder); _allMembers = builder.ToImmutableAndFree(); } return _allMembers; } public override ImmutableArray<Symbol> GetMembers(string name) { return _cachedLookup[name]; } internal sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return ImmutableArray.CreateRange<NamedTypeSymbol>(GetMembersUnordered().OfType<NamedTypeSymbol>()); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray.CreateRange<NamedTypeSymbol>(GetMembers().OfType<NamedTypeSymbol>()); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { // TODO - This is really inefficient. Creating a new array on each lookup needs to fixed! return ImmutableArray.CreateRange<NamedTypeSymbol>(_cachedLookup[name].OfType<NamedTypeSymbol>()); } public override Symbol ContainingSymbol { get { return _containingNamespace; } } public override AssemblySymbol ContainingAssembly { get { if (_extent.Kind == NamespaceKind.Module) { return _extent.Module.ContainingAssembly; } else if (_extent.Kind == NamespaceKind.Assembly) { return _extent.Assembly; } else { return null; } } } public override ImmutableArray<Location> Locations { // Merge the locations of all constituent namespaces. get { //TODO: cache return _namespacesToMerge.SelectMany(namespaceSymbol => namespaceSymbol.Locations).AsImmutable(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _namespacesToMerge.SelectMany(namespaceSymbol => namespaceSymbol.DeclaringSyntaxReferences).AsImmutable(); } } internal override void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string name, int arity, LookupOptions options) { foreach (NamespaceSymbol namespaceSymbol in _namespacesToMerge) { namespaceSymbol.GetExtensionMethods(methods, name, arity, options); } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/JoinKeywordRecommender.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.Queries ''' <summary> ''' Recommends the "Join" keyword. ''' </summary> Friend Class JoinKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Join", VBFeaturesResources.Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) ' First there is the normal and boring "Join" If context.IsQueryOperatorContext OrElse context.IsAdditionalJoinOperatorContext(cancellationToken) Then Return s_keywords End If ' Now this might be Group Join... Dim targetToken = context.TargetToken ' If it's just "Group" it may have parsed as a Group By Return If(targetToken.IsChildToken(Of GroupByClauseSyntax)(Function(groupBy) groupBy.GroupKeyword) OrElse targetToken.IsChildToken(Of GroupJoinClauseSyntax)(Function(groupBy) groupBy.GroupKeyword), s_keywords, 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.Queries ''' <summary> ''' Recommends the "Join" keyword. ''' </summary> Friend Class JoinKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Join", VBFeaturesResources.Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) ' First there is the normal and boring "Join" If context.IsQueryOperatorContext OrElse context.IsAdditionalJoinOperatorContext(cancellationToken) Then Return s_keywords End If ' Now this might be Group Join... Dim targetToken = context.TargetToken ' If it's just "Group" it may have parsed as a Group By Return If(targetToken.IsChildToken(Of GroupByClauseSyntax)(Function(groupBy) groupBy.GroupKeyword) OrElse targetToken.IsChildToken(Of GroupJoinClauseSyntax)(Function(groupBy) groupBy.GroupKeyword), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/CodeAnalysisTest/StringTableTests.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.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public sealed class StringTableTests { [Fact] public void TestAddSameWithStringBuilderProducesSameStringInstance() { var st = new StringTable(); var sb1 = new StringBuilder("goo"); var sb2 = new StringBuilder("goo"); var s1 = st.Add(sb1); var s2 = st.Add(sb2); Assert.Same(s1, s2); } [Fact] public void TestAddDifferentWithStringBuilderProducesDifferentStringInstance() { var st = new StringTable(); var sb1 = new StringBuilder("goo"); var sb2 = new StringBuilder("bar"); var s1 = st.Add(sb1); var s2 = st.Add(sb2); Assert.NotEqual((object)s1, (object)s2); } [Fact] public void TestAddSameWithVariousInputsProducesSameStringInstance() { var st = new StringTable(); var s1 = st.Add(new StringBuilder(" ")); var s2 = st.Add(' '); Assert.Same(s1, s2); var s3 = st.Add(" "); Assert.Same(s2, s3); var s4 = st.Add(new char[1] { ' ' }, 0, 1); Assert.Same(s3, s4); var s5 = st.Add("ABC DEF", 3, 1); Assert.Same(s4, s5); } [Fact] public void TestAddSameWithCharProducesSameStringInstance() { var st = new StringTable(); var s1 = st.Add(' '); var s2 = st.Add(' '); Assert.Same(s1, s2); } [Fact] public void TestSharedAddSameWithStringBuilderProducesSameStringInstance() { var sb1 = new StringBuilder("goo"); var sb2 = new StringBuilder("goo"); var s1 = new StringTable().Add(sb1); var s2 = new StringTable().Add(sb2); Assert.Same(s1, s2); } [Fact] public void TestSharedAddSameWithCharProducesSameStringInstance() { // Regression test for a bug where single-char strings were not being // found in the shared table. var s1 = new StringTable().Add(' '); var s2 = new StringTable().Add(' '); Assert.Same(s1, s2); } private static unsafe bool TestTextEqualsASCII(string str, string ascii) { fixed (byte* ptr = Encoding.ASCII.GetBytes(ascii)) { var ptrResult = StringTable.TextEqualsASCII(str, new ReadOnlySpan<byte>(ptr, ascii.Length)); var sbResult = StringTable.TextEquals(str, new StringBuilder(ascii)); var substrResult = StringTable.TextEquals(str, "xxx" + ascii + "yyy", 3, ascii.Length); Assert.Equal(substrResult, sbResult); Assert.Equal(ptrResult, sbResult); return ptrResult; } } [Fact] public void TextEquals1() { Assert.True(TestTextEqualsASCII("", "")); Assert.False(TestTextEqualsASCII("a", "")); Assert.False(TestTextEqualsASCII("", "a")); Assert.True(TestTextEqualsASCII("a", "a")); Assert.False(TestTextEqualsASCII("a", "ab")); Assert.False(TestTextEqualsASCII("ab", "a")); Assert.False(TestTextEqualsASCII("abc", "a")); Assert.False(TestTextEqualsASCII("abcd", "a")); Assert.False(TestTextEqualsASCII("abcde", "a")); Assert.False(TestTextEqualsASCII("abcdef", "a")); Assert.False(TestTextEqualsASCII("abcdefg", "a")); Assert.False(TestTextEqualsASCII("abcdefgh", "a")); Assert.False(TestTextEqualsASCII("a", "ab")); Assert.False(TestTextEqualsASCII("a", "abc")); Assert.False(TestTextEqualsASCII("a", "abcd")); Assert.False(TestTextEqualsASCII("a", "abcde")); Assert.False(TestTextEqualsASCII("a", "abcdef")); Assert.False(TestTextEqualsASCII("a", "abcdefg")); Assert.False(TestTextEqualsASCII("a", "abcdefgh")); Assert.False(TestTextEqualsASCII("\u1234", "a")); Assert.False(TestTextEqualsASCII("\ud800", "xx")); Assert.False(TestTextEqualsASCII("\uffff", "")); } [Fact] public void TestAddEqualSubstringsFromDifferentStringsWorks() { // Make neither of the strings equal to the result of the substring call // to test an issue that was surfaced by pooling the wrong string. var str1 = "abcd1"; var str2 = "abcd2"; var st = new StringTable(); var s1 = st.Add(str1, 0, 4); var s2 = st.Add(str2, 0, 4); Assert.Same(s1, s2); Assert.Equal("abcd", s1); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public sealed class StringTableTests { [Fact] public void TestAddSameWithStringBuilderProducesSameStringInstance() { var st = new StringTable(); var sb1 = new StringBuilder("goo"); var sb2 = new StringBuilder("goo"); var s1 = st.Add(sb1); var s2 = st.Add(sb2); Assert.Same(s1, s2); } [Fact] public void TestAddDifferentWithStringBuilderProducesDifferentStringInstance() { var st = new StringTable(); var sb1 = new StringBuilder("goo"); var sb2 = new StringBuilder("bar"); var s1 = st.Add(sb1); var s2 = st.Add(sb2); Assert.NotEqual((object)s1, (object)s2); } [Fact] public void TestAddSameWithVariousInputsProducesSameStringInstance() { var st = new StringTable(); var s1 = st.Add(new StringBuilder(" ")); var s2 = st.Add(' '); Assert.Same(s1, s2); var s3 = st.Add(" "); Assert.Same(s2, s3); var s4 = st.Add(new char[1] { ' ' }, 0, 1); Assert.Same(s3, s4); var s5 = st.Add("ABC DEF", 3, 1); Assert.Same(s4, s5); } [Fact] public void TestAddSameWithCharProducesSameStringInstance() { var st = new StringTable(); var s1 = st.Add(' '); var s2 = st.Add(' '); Assert.Same(s1, s2); } [Fact] public void TestSharedAddSameWithStringBuilderProducesSameStringInstance() { var sb1 = new StringBuilder("goo"); var sb2 = new StringBuilder("goo"); var s1 = new StringTable().Add(sb1); var s2 = new StringTable().Add(sb2); Assert.Same(s1, s2); } [Fact] public void TestSharedAddSameWithCharProducesSameStringInstance() { // Regression test for a bug where single-char strings were not being // found in the shared table. var s1 = new StringTable().Add(' '); var s2 = new StringTable().Add(' '); Assert.Same(s1, s2); } private static unsafe bool TestTextEqualsASCII(string str, string ascii) { fixed (byte* ptr = Encoding.ASCII.GetBytes(ascii)) { var ptrResult = StringTable.TextEqualsASCII(str, new ReadOnlySpan<byte>(ptr, ascii.Length)); var sbResult = StringTable.TextEquals(str, new StringBuilder(ascii)); var substrResult = StringTable.TextEquals(str, "xxx" + ascii + "yyy", 3, ascii.Length); Assert.Equal(substrResult, sbResult); Assert.Equal(ptrResult, sbResult); return ptrResult; } } [Fact] public void TextEquals1() { Assert.True(TestTextEqualsASCII("", "")); Assert.False(TestTextEqualsASCII("a", "")); Assert.False(TestTextEqualsASCII("", "a")); Assert.True(TestTextEqualsASCII("a", "a")); Assert.False(TestTextEqualsASCII("a", "ab")); Assert.False(TestTextEqualsASCII("ab", "a")); Assert.False(TestTextEqualsASCII("abc", "a")); Assert.False(TestTextEqualsASCII("abcd", "a")); Assert.False(TestTextEqualsASCII("abcde", "a")); Assert.False(TestTextEqualsASCII("abcdef", "a")); Assert.False(TestTextEqualsASCII("abcdefg", "a")); Assert.False(TestTextEqualsASCII("abcdefgh", "a")); Assert.False(TestTextEqualsASCII("a", "ab")); Assert.False(TestTextEqualsASCII("a", "abc")); Assert.False(TestTextEqualsASCII("a", "abcd")); Assert.False(TestTextEqualsASCII("a", "abcde")); Assert.False(TestTextEqualsASCII("a", "abcdef")); Assert.False(TestTextEqualsASCII("a", "abcdefg")); Assert.False(TestTextEqualsASCII("a", "abcdefgh")); Assert.False(TestTextEqualsASCII("\u1234", "a")); Assert.False(TestTextEqualsASCII("\ud800", "xx")); Assert.False(TestTextEqualsASCII("\uffff", "")); } [Fact] public void TestAddEqualSubstringsFromDifferentStringsWorks() { // Make neither of the strings equal to the result of the substring call // to test an issue that was surfaced by pooling the wrong string. var str1 = "abcd1"; var str2 = "abcd2"; var st = new StringTable(); var s1 = st.Add(str1, 0, 4); var s2 = st.Add(str2, 0, 4); Assert.Same(s1, s2); Assert.Equal("abcd", s1); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/Portable/InternalUtilities/CompilerOptionParseUtilities.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; namespace Roslyn.Utilities { internal static class CompilerOptionParseUtilities { /// <summary> /// Parse the value provided to an MSBuild Feature option into a list of entries. This will /// leave name=value in their raw form. /// </summary> public static IList<string> ParseFeatureFromMSBuild(string? features) { if (RoslynString.IsNullOrEmpty(features)) { return new List<string>(capacity: 0); } return features.Split(new[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); } public static void ParseFeatures(IDictionary<string, string> builder, List<string> values) { foreach (var commaFeatures in values) { foreach (var feature in commaFeatures.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { ParseFeatureCore(builder, feature); } } } private static void ParseFeatureCore(IDictionary<string, string> builder, string feature) { int equals = feature.IndexOf('='); if (equals > 0) { string name = feature.Substring(0, equals); string value = feature.Substring(equals + 1); builder[name] = value; } else { builder[feature] = "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.Collections.Generic; namespace Roslyn.Utilities { internal static class CompilerOptionParseUtilities { /// <summary> /// Parse the value provided to an MSBuild Feature option into a list of entries. This will /// leave name=value in their raw form. /// </summary> public static IList<string> ParseFeatureFromMSBuild(string? features) { if (RoslynString.IsNullOrEmpty(features)) { return new List<string>(capacity: 0); } return features.Split(new[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); } public static void ParseFeatures(IDictionary<string, string> builder, List<string> values) { foreach (var commaFeatures in values) { foreach (var feature in commaFeatures.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { ParseFeatureCore(builder, feature); } } } private static void ParseFeatureCore(IDictionary<string, string> builder, string feature) { int equals = feature.IndexOf('='); if (equals > 0) { string name = feature.Substring(0, equals); string value = feature.Substring(equals + 1); builder[name] = value; } else { builder[feature] = "true"; } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.TopLevelBulkConfigureSeverityCodeAction.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.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private sealed class TopLevelBulkConfigureSeverityCodeAction : AbstractConfigurationActionWithNestedActions { public TopLevelBulkConfigureSeverityCodeAction(ImmutableArray<CodeAction> nestedActions, string? category) : base(nestedActions, category != null ? string.Format(FeaturesResources.Configure_severity_for_all_0_analyzers, category) : FeaturesResources.Configure_severity_for_all_analyzers) { // Ensure that 'Category' based bulk configuration actions are shown above // the 'All analyzer diagnostics' bulk configuration actions. AdditionalPriority = category != null ? CodeActionPriority.Low : CodeActionPriority.Lowest; } internal override CodeActionPriority AdditionalPriority { get; } internal override bool IsBulkConfigurationAction => 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.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private sealed class TopLevelBulkConfigureSeverityCodeAction : AbstractConfigurationActionWithNestedActions { public TopLevelBulkConfigureSeverityCodeAction(ImmutableArray<CodeAction> nestedActions, string? category) : base(nestedActions, category != null ? string.Format(FeaturesResources.Configure_severity_for_all_0_analyzers, category) : FeaturesResources.Configure_severity_for_all_analyzers) { // Ensure that 'Category' based bulk configuration actions are shown above // the 'All analyzer diagnostics' bulk configuration actions. AdditionalPriority = category != null ? CodeActionPriority.Low : CodeActionPriority.Lowest; } internal override CodeActionPriority AdditionalPriority { get; } internal override bool IsBulkConfigurationAction => true; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IFieldReferenceExpression.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.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")> Public Sub FieldReference_Attribute() Dim source = <![CDATA[ Imports System.Diagnostics Class C Private Const field As String = NameOf(field) <Conditional(field)>'BIND:"Conditional(field)" Private Sub M() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IOperation: (OperationKind.None, Type: null) (Syntax: 'Conditional(field)') Children(1): IFieldReferenceOperation: C.field As System.String (Static) (OperationKind.FieldReference, Type: System.String, Constant: "field") (Syntax: 'field') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AttributeSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_ImplicitMe() Dim source = <![CDATA[ Class C Private i As Integer Private Sub M() i = 1 'BIND:"i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_ExplicitMe() Dim source = <![CDATA[ Class C Private i As Integer Private Sub M() Me.i = 1 'BIND:"Me.i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Me.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_MyBase() Dim source = <![CDATA[ Class C Protected i As Integer End Class Class B Inherits C Private Sub M() MyBase.i = 1 'BIND:"MyBase.i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'MyBase.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'MyBase') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_MyClass() Dim source = <![CDATA[ Class C Private i As Integer Private Sub M() MyClass.i = 1 'BIND:"MyClass.i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'MyClass.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'MyClass') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_SharedField() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared i1 As Integer Shared Sub S2() Dim i2 = i1'BIND:"i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_SharedFieldWithInstanceReceiver() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared i1 As Integer = 1 Shared Sub S2() Dim c1Instance As New C1 Dim i1 = c1Instance.i1'BIND:"c1Instance.i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c1Instance.i1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim i1 = c1Instance.i1'BIND:"c1Instance.i1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_SharedFieldAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared i1 As Integer = 1 Shared Sub S2() Dim i1 = C1.i1'BIND:"C1.i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'C1.i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_InstanceFieldAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Dim i1 As Integer = 1 Shared Sub S2() Dim i1 = C1.i1'BIND:"C1.i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'C1.i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. Dim i1 = C1.i1'BIND:"C1.i1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_StaticFieldReferenceInInitializer_RightHandSide() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Public Shared i1 As Integer Public i2 As Integer End Class Sub S1() Dim a = New C1 With {.i2 = .i1}'BIND:".i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: '.i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub FieldReference_NoControlFlow() ' Verify mix of field references with implicit/explicit/null instance in lvalue/rvalue contexts. Dim source = <![CDATA[ Imports System Friend Class C Private i As Integer Private Shared j As Integer Public Sub M(c As C)'BIND:"Public Sub M(c As C)" i = C.j j = Me.i + c.i End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = C.j') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = C.j') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFieldReferenceOperation: C.j As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'C.j') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = Me.i + c.i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = Me.i + c.i') Left: IFieldReferenceOperation: C.j As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'j') Instance Receiver: null Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'Me.i + c.i') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Me.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Right: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.i') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub FieldReference_ControlFlowInReceiver() Dim source = <![CDATA[ Imports System Friend Class C Public i As Integer = 0 Public Sub M(c1 As C, c2 As C, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, p As Integer)" p = If (c1, c2).i End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If (c1, c2).i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If (c1, c2).i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If (c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If (c1, c2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub FieldReference_ControlFlowInReceiver_StaticField() Dim source = <![CDATA[ Imports System Friend Class C Public Shared i As Integer = 0 Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)" p1 = c1.i p2 = If (c1, c2).i End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p1 = c1.i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p1 = c1.i') Left: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') Right: IFieldReferenceOperation: C.i As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c1.i') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p2 = If (c1, c2).i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p2 = If (c1, c2).i') Left: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p2') Right: IFieldReferenceOperation: C.i As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If (c1, c2).i') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p1 = c1.i ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p2 = If (c1, c2).i ~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) 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.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")> Public Sub FieldReference_Attribute() Dim source = <![CDATA[ Imports System.Diagnostics Class C Private Const field As String = NameOf(field) <Conditional(field)>'BIND:"Conditional(field)" Private Sub M() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IOperation: (OperationKind.None, Type: null) (Syntax: 'Conditional(field)') Children(1): IFieldReferenceOperation: C.field As System.String (Static) (OperationKind.FieldReference, Type: System.String, Constant: "field") (Syntax: 'field') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AttributeSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_ImplicitMe() Dim source = <![CDATA[ Class C Private i As Integer Private Sub M() i = 1 'BIND:"i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_ExplicitMe() Dim source = <![CDATA[ Class C Private i As Integer Private Sub M() Me.i = 1 'BIND:"Me.i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Me.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_MyBase() Dim source = <![CDATA[ Class C Protected i As Integer End Class Class B Inherits C Private Sub M() MyBase.i = 1 'BIND:"MyBase.i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'MyBase.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'MyBase') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")> Public Sub FieldReference_MyClass() Dim source = <![CDATA[ Class C Private i As Integer Private Sub M() MyClass.i = 1 'BIND:"MyClass.i" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'MyClass.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'MyClass') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_SharedField() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared i1 As Integer Shared Sub S2() Dim i2 = i1'BIND:"i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_SharedFieldWithInstanceReceiver() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared i1 As Integer = 1 Shared Sub S2() Dim c1Instance As New C1 Dim i1 = c1Instance.i1'BIND:"c1Instance.i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c1Instance.i1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim i1 = c1Instance.i1'BIND:"c1Instance.i1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_SharedFieldAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared i1 As Integer = 1 Shared Sub S2() Dim i1 = C1.i1'BIND:"C1.i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'C1.i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_InstanceFieldAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Dim i1 As Integer = 1 Shared Sub S2() Dim i1 = C1.i1'BIND:"C1.i1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'C1.i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. Dim i1 = C1.i1'BIND:"C1.i1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IFieldReference_StaticFieldReferenceInInitializer_RightHandSide() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Public Shared i1 As Integer Public i2 As Integer End Class Sub S1() Dim a = New C1 With {.i2 = .i1}'BIND:".i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: M1.C1.i1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: '.i1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub FieldReference_NoControlFlow() ' Verify mix of field references with implicit/explicit/null instance in lvalue/rvalue contexts. Dim source = <![CDATA[ Imports System Friend Class C Private i As Integer Private Shared j As Integer Public Sub M(c As C)'BIND:"Public Sub M(c As C)" i = C.j j = Me.i + c.i End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = C.j') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = C.j') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFieldReferenceOperation: C.j As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'C.j') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = Me.i + c.i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = Me.i + c.i') Left: IFieldReferenceOperation: C.j As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'j') Instance Receiver: null Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'Me.i + c.i') Left: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Me.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Right: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.i') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub FieldReference_ControlFlowInReceiver() Dim source = <![CDATA[ Imports System Friend Class C Public i As Integer = 0 Public Sub M(c1 As C, c2 As C, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, p As Integer)" p = If (c1, c2).i End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If (c1, c2).i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If (c1, c2).i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If (c1, c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If (c1, c2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub FieldReference_ControlFlowInReceiver_StaticField() Dim source = <![CDATA[ Imports System Friend Class C Public Shared i As Integer = 0 Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)" p1 = c1.i p2 = If (c1, c2).i End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p1 = c1.i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p1 = c1.i') Left: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') Right: IFieldReferenceOperation: C.i As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c1.i') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p2 = If (c1, c2).i') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p2 = If (c1, c2).i') Left: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p2') Right: IFieldReferenceOperation: C.i As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If (c1, c2).i') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p1 = c1.i ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p2 = If (c1, c2).i ~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ArrayCreationAndInitializer.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.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ArrayCreationAndInitializer : SemanticModelTestBase { [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/new string[1]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_UserDefinedType() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new M[1]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_ConstantDimension() { string source = @" class M { } class C { public void F() { const int dimension = 1; var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): ILocalReferenceOperation: dimension (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_NonConstantDimension() { string source = @" class M { } class C { public void F(int dimension) { var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_DimensionWithImplicitConversion() { string source = @" class M { } class C { public void F(char dimension) { var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_DimensionWithExplicitConversion() { string source = @" class M { } class C { public void F(object dimension) { var a = /*<bind>*/new M[(int)dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[(int)dimension]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/new string[] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new string[ ... ing.Empty }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_PrimitiveTypeWithExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[1] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_PrimitiveTypeWithIncorrectExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[2] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0847: An array initializer of length '2' is expected // var a = /*<bind>*/new string[2] { string.Empty }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ string.Empty }").WithArguments("2").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_PrimitiveTypeWithNonConstantExplicitDimension() { string source = @" class C { public void F(int dimension) { var a = /*<bind>*/new string[dimension] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // var a = /*<bind>*/new string[dimension] { string.Empty }/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstantExpected, "dimension").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_NoExplicitArrayCreationExpression() { string source = @" class C { public void F(int dimension) { /*<bind>*/int[] x = { 1, 2 };/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int[] x = { 1, 2 };') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int[] x = { 1, 2 }') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = { 1, 2 }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= { 1, 2 }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: '{ 1, 2 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{ 1, 2 }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_UserDefinedType() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new M[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[] { new M() }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new M[] { new M() }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new M() }') Element Values(1): IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_ImplicitlyTyped() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new[] { new M() }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { new M() }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new M() }') Element Values(1): IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializerAndDimension() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/new[]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: ?[], IsInvalid) (Syntax: 'new[]/*</bind>*/') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'new[]/*</bind>*/') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '') Element Values(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1514: { expected // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 43), // CS1513: } expected // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 43), // CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializer() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/new[2]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: ?[], IsInvalid) (Syntax: 'new[2]/*</bind>*/') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'new[2]/*</bind>*/') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '') Element Values(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,31): error CS0178: Invalid rank specifier: expected ',' or ']' // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidArray, "2").WithLocation(6, 31), // file.cs(6,44): error CS1514: { expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 44), // file.cs(6,44): error CS1513: } expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 44), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[2]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_MultipleInitializersWithConversions() { string source = @" class C { public void F() { var a = """"; var b = /*<bind>*/new[] { ""hello"", a, null }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new[] { ""he ... , a, null }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new[] { ""he ... , a, null }') Initializer: IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ ""hello"", a, null }') Element Values(3): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"") (Syntax: '""hello""') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.String) (Syntax: 'a') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void MultiDimensionalArrayCreation() { string source = @" class C { public void F() { byte[,,] b = /*<bind>*/new byte[1,2,3]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Byte[,,]) (Syntax: 'new byte[1,2,3]') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void MultiDimensionalArrayCreation_WithInitializer() { string source = @" class C { public void F() { byte[,,] b = /*<bind>*/new byte[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Byte[,,]) (Syntax: 'new byte[,, ... 5, 6 } } }') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { { 1, 2, ... 5, 6 } } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 1, 2, 3 } }') Element Values(1): IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2, 3 }') Element Values(3): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 3, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 4, 5, 6 } }') Element Values(1): IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 4, 5, 6 }') Element Values(3): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 4, IsImplicit) (Syntax: '4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 5, IsImplicit) (Syntax: '5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 6, IsImplicit) (Syntax: '6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfSingleDimensionalArrays() { string source = @" class C { public void F() { int[][] a = /*<bind>*/new int[][] { new[] { 1, 2, 3 }, new int[5] }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][]) (Syntax: 'new int[][] ... ew int[5] }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new int[][] ... ew int[5] }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new[] { 1 ... ew int[5] }') Element Values(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { 1, 2, 3 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new[] { 1, 2, 3 }') Initializer: IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2, 3 }') Element Values(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[5]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfMultiDimensionalArrays() { string source = @" class C { public void F() { int[][,] a = /*<bind>*/new int[1][,]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][,]) (Syntax: 'new int[1][,]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfImplicitlyTypedMultiDimensionalArrays_WithInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/new[] { new[, ,] { { { 1, 2 } } }, new[, ,] { { { 3, 4 } } } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][,,]) (Syntax: 'new[] { new ... , 4 } } } }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[] { new ... , 4 } } } }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new[, ,] ... , 4 } } } }') Element Values(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,,]) (Syntax: 'new[, ,] { ... 1, 2 } } }') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { { 1, 2 } } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 1, 2 } }') Element Values(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,,]) (Syntax: 'new[, ,] { ... 3, 4 } } }') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { { 3, 4 } } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 3, 4 } }') Element Values(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 3, 4 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_MissingDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[]') Dimension Sizes(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1586: Array creation must have array size or array initializer // var a = /*<bind>*/new string[]/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 37) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvalidInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/new string[] { 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[] { 1 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'new string[] { 1 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // var a = /*<bind>*/new string[] { 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_MissingExplicitCast() { string source = @" class C { public void F(object b) { var a = /*<bind>*/new string[b]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[b]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'b') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/new string[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("object", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreation_InvocationExpressionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[M()]/*</bind>*/; } public int M() => 1; } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[M()]') Dimension Sizes(1): IInvocationOperation ( System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreation_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[(int)M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[(int)M()]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Object C.M()) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvocationExpressionAsDimension() { string source = @" class C { public static void F() { var a = /*<bind>*/new string[M()]/*</bind>*/; } public static object M() => null; } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[M()]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (System.Object C.M()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/new string[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M()").WithArguments("object", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[(int)M()]/*</bind>*/; } public C M() => new C(); } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[(int)M()]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( C C.M()) (OperationKind.Invocation, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'C' to 'int' // var a = /*<bind>*/new string[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)M()").WithArguments("C", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")] public void SimpleArrayCreation_ConstantConversion() { string source = @" class C { public void F() { var a = /*<bind>*/new string[0.0]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[0.0]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/new string[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0.0").WithArguments("double", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_NoControlFlow() { string source = @" class C { const int c1 = 2, c2 = 1, c3 = 1; void M(int[] a1, int[] a2, int[,] a3, int[,] a4, int[][] a5, int[][] a6, int d1, int d2, int d3, int d4, int v1, int v2, int v3, int v4) /*<bind>*/ { a1 = new int[d1]; // Single dimension, no initializer a2 = new int[] { v1 }; // Single dimension, initializer a3 = new int[d2, d3]; // Multi-dimension, no initializer a4 = new int[c1, c2] { { v2 }, { v3 } }; // Multi-dimension, initializer a5 = new int[d4][]; // Jagged, no initializer a6 = new int[c3][] { new[] { v4 } }; // Jagged, initializer int[] f = { 1, 3, 4 }; // Array creation with only initializer. }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32[] f] Block[B1] - Block Predecessors: [B0] Statements (7) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new int[d1];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new int[d1]') Left: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[d1]') Dimension Sizes(1): IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd1') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a2 = new int[] { v1 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a2 = new int[] { v1 }') Left: IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a2') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[] { v1 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new int[] { v1 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a3 = new int[d2, d3];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a3 = new int[d2, d3]') Left: IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a3') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[d2, d3]') Dimension Sizes(2): IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd2') IParameterReferenceOperation: d3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd3') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a4 = new in ... , { v3 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a4 = new in ... }, { v3 } }') Left: IParameterReferenceOperation: a4 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a4') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... }, { v3 } }') Dimension Sizes(2): IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v2 }, { v3 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v2 }') Element Values(1): IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 }') Element Values(1): IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a5 = new int[d4][];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[][]) (Syntax: 'a5 = new int[d4][]') Left: IParameterReferenceOperation: a5 (OperationKind.ParameterReference, Type: System.Int32[][]) (Syntax: 'a5') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][]) (Syntax: 'new int[d4][]') Dimension Sizes(1): IParameterReferenceOperation: d4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd4') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a6 = new in ... ] { v4 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[][]) (Syntax: 'a6 = new in ... [] { v4 } }') Left: IParameterReferenceOperation: a6 (OperationKind.ParameterReference, Type: System.Int32[][]) (Syntax: 'a6') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][]) (Syntax: 'new int[c3] ... [] { v4 } }') Dimension Sizes(1): IFieldReferenceOperation: System.Int32 C.c3 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c3') Instance Receiver: null Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new[] { v4 } }') Element Values(1): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { v4 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { v4 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v4 }') Element Values(1): IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[], IsImplicit) (Syntax: 'f = { 1, 3, 4 }') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32[], IsImplicit) (Syntax: 'f = { 1, 3, 4 }') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: '{ 1, 3, 4 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '{ 1, 3, 4 }') Initializer: IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 3, 4 }') Element Values(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstDimension_NoInitializer() { string source = @" class C { void M(int[,] a1, int? d1, int d2, int c) /*<bind>*/ { a1 = new int[d1 ?? d2, c]; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ?? d2, c];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... 1 ?? d2, c]') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[d1 ?? d2, c]') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'd1 ?? d2') IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Initializer: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstDimension_WithInitializer() { string source = @" class C { const int c = 1; void M(int[,] a1, int? d1, int d2, int v1) /*<bind>*/ { a1 = new int[d1 ?? d2, c] { { v1 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... { { v1 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... { { v1 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[d1 ... { { v1 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') IFieldReferenceOperation: System.Int32 C.c (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c') Instance Receiver: null Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, c] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(8, 22) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondDimension_NoInitializer() { string source = @" class C { void M(int[,] a1, int? d1, int d2, int c) /*<bind>*/ { a1 = new int[c, d1 ?? d2]; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... d1 ?? d2];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... , d1 ?? d2]') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c, d1 ?? d2]') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'd1 ?? d2') Initializer: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondDimension_WithInitializer() { string source = @" class C { const int c = 1; void M(int[,] a1, int? d1, int d2, int v1) /*<bind>*/ { a1 = new int[c, d1 ?? d2] { { v1 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IFieldReferenceOperation: System.Int32 C.c (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... { { v1 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... { { v1 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[c, ... { { v1 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,25): error CS0150: A constant value is expected // a1 = new int[c, d1 ?? d2] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(8, 25) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleDimensions() { string source = @" class C { void M(int[,] a1, int? d1, int d2, int? d3, int d4, int v1) /*<bind>*/ { a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IParameterReferenceOperation: d3 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd3') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd4') Value: IParameterReferenceOperation: d4 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd4') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... { { v1 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... { { v1 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[d1 ... { { v1 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3 ?? d4') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(7, 22), // file.cs(7,32): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d3 ?? d4").WithLocation(7, 32) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstInitializerValue_SingleDimArray() { string source = @" class C { const int c1 = 2; void M(int[] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1] { v1 ?? v2, v3 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ? v2, v3 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new in ... ?? v2, v3 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[c1] ... ?? v2, v3 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2, v3 }') Element Values(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstInitializerValue_MultiDimArray() { string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1, c2] { { v1 ?? v2 }, { v3 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... , { v3 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... }, { v3 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... }, { v3 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 ?? v2 }, { v3 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 }') Element Values(1): IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondInitializerValue_SingleDimArray() { string source = @" class C { const int c1 = 2; void M(int[] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1] { v3, v1 ?? v2 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... v1 ?? v2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new in ... v1 ?? v2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[c1] ... v1 ?? v2 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3, v1 ?? v2 }') Element Values(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondInitializerValue_MultiDimArray() { string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1, c2] { { v3 }, { v1 ?? v2 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [4] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ?? v2 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... 1 ?? v2 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... 1 ?? v2 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v3 }, { v1 ?? v2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 }') Element Values(1): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondInitializerValue_MultiDimArray_02() { // Error case where one array initializer element value is a nested array initializer and another one is not. // Verifies that CFG builder handles the mixed kind element values. string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1, c2] { v3, { v1 ?? v2 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'v3') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'v3') Children(1): IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'v3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [4] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... ?? v2 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... 1 ?? v2 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[c1, ... 1 ?? v2 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ v3, { v1 ?? v2 } }') Element Values(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'v3') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,32): error CS0846: A nested array initializer is expected // a1 = new int[c1, c2] { v3, { v1 ?? v2 } }; Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "v3").WithLocation(8, 32) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleInitializerValues_SingleDimArray() { string source = @" class C { const int c1 = 2; void M(int[] a1, int? v1, int v2, int? v3, int v4) /*<bind>*/ { a1 = new int[c1] { v1 ?? v2, v3 ?? v4 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [4] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... v3 ?? v4 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new in ... v3 ?? v4 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[c1] ... v3 ?? v4 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2, v3 ?? v4 }') Element Values(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleInitializerValues_MultiDimArray() { string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int? v3, int v4) /*<bind>*/ { a1 = new int[c1, c2] { { v1 ?? v2 }, { v3 ?? v4 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] [6] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ?? v4 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... 3 ?? v4 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... 3 ?? v4 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 ?? v ... 3 ?? v4 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 ?? v4 }') Element Values(1): IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInDimensionAndMultipleInitializerValues_SingleDimArray() { string source = @" class C { void M(int[] a1, int? v1, int v2, int? v3, int v4, int? d1, int d2) /*<bind>*/ { a1 = new int[d1 ?? d2] { v1 ?? v2, v3 ?? v4 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] [6] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { CaptureIds: [5] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R4} Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B11] Leaving: {R4} } Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... v3 ?? v4 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[], IsInvalid) (Syntax: 'a1 = new in ... v3 ?? v4 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[d1 ... v3 ?? v4 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2, v3 ?? v4 }') Element Values(2): IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B12] Leaving: {R1} } Block[B12] - Exit Predecessors: [B11] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2] { v1 ?? v2, v3 ?? v4 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(7, 22) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleDimensionsAndInitializerValues_MultiDimArray() { string source = @" class C { void M(int[,] a1, int? v1, int v2, int? v3, int v4, int? d1, int d2, int? d3, int d4) /*<bind>*/ { a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 ?? v2 }, { v3 ?? v4 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] [6] [8] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IParameterReferenceOperation: d3 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd3') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd4') Value: IParameterReferenceOperation: d4 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd4') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { CaptureIds: [5] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R4} Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B11] Leaving: {R4} Entering: {R5} } Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B11] Entering: {R5} .locals {R5} { CaptureIds: [7] Block[B11] - Block Predecessors: [B9] [B10] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B13] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R5} Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B14] Leaving: {R5} } Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... ?? v4 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... 3 ?? v4 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[d1 ... 3 ?? v4 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3 ?? d4') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 ?? v ... 3 ?? v4 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 ?? v4 }') Element Values(1): IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B15] Leaving: {R1} } Block[B15] - Exit Predecessors: [B14] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 ?? v2 }, { v3 ?? v4 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(7, 22), // file.cs(7,32): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 ?? v2 }, { v3 ?? v4 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d3 ?? d4").WithLocation(7, 32) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more 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.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ArrayCreationAndInitializer : SemanticModelTestBase { [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/new string[1]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_UserDefinedType() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new M[1]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[1]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_ConstantDimension() { string source = @" class M { } class C { public void F() { const int dimension = 1; var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): ILocalReferenceOperation: dimension (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_NonConstantDimension() { string source = @" class M { } class C { public void F(int dimension) { var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_DimensionWithImplicitConversion() { string source = @" class M { } class C { public void F(char dimension) { var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_DimensionWithExplicitConversion() { string source = @" class M { } class C { public void F(object dimension) { var a = /*<bind>*/new M[(int)dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[(int)dimension]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/new string[] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new string[ ... ing.Empty }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_PrimitiveTypeWithExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[1] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_PrimitiveTypeWithIncorrectExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[2] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0847: An array initializer of length '2' is expected // var a = /*<bind>*/new string[2] { string.Empty }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ string.Empty }").WithArguments("2").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_PrimitiveTypeWithNonConstantExplicitDimension() { string source = @" class C { public void F(int dimension) { var a = /*<bind>*/new string[dimension] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // var a = /*<bind>*/new string[dimension] { string.Empty }/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstantExpected, "dimension").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_NoExplicitArrayCreationExpression() { string source = @" class C { public void F(int dimension) { /*<bind>*/int[] x = { 1, 2 };/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int[] x = { 1, 2 };') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int[] x = { 1, 2 }') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32[] x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = { 1, 2 }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= { 1, 2 }') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: '{ 1, 2 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{ 1, 2 }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_UserDefinedType() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new M[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new M[] { new M() }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new M[] { new M() }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new M() }') Element Values(1): IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_ImplicitlyTyped() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: M[]) (Syntax: 'new[] { new M() }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { new M() }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new M() }') Element Values(1): IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializerAndDimension() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/new[]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: ?[], IsInvalid) (Syntax: 'new[]/*</bind>*/') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'new[]/*</bind>*/') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '') Element Values(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1514: { expected // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 43), // CS1513: } expected // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 43), // CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializer() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/new[2]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: ?[], IsInvalid) (Syntax: 'new[2]/*</bind>*/') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'new[2]/*</bind>*/') Initializer: IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '') Element Values(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,31): error CS0178: Invalid rank specifier: expected ',' or ']' // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidArray, "2").WithLocation(6, 31), // file.cs(6,44): error CS1514: { expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 44), // file.cs(6,44): error CS1513: } expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 44), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[2]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_MultipleInitializersWithConversions() { string source = @" class C { public void F() { var a = """"; var b = /*<bind>*/new[] { ""hello"", a, null }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new[] { ""he ... , a, null }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new[] { ""he ... , a, null }') Initializer: IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ ""hello"", a, null }') Element Values(3): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"") (Syntax: '""hello""') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.String) (Syntax: 'a') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void MultiDimensionalArrayCreation() { string source = @" class C { public void F() { byte[,,] b = /*<bind>*/new byte[1,2,3]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Byte[,,]) (Syntax: 'new byte[1,2,3]') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void MultiDimensionalArrayCreation_WithInitializer() { string source = @" class C { public void F() { byte[,,] b = /*<bind>*/new byte[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Byte[,,]) (Syntax: 'new byte[,, ... 5, 6 } } }') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { { 1, 2, ... 5, 6 } } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 1, 2, 3 } }') Element Values(1): IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2, 3 }') Element Values(3): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 3, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 4, 5, 6 } }') Element Values(1): IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 4, 5, 6 }') Element Values(3): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 4, IsImplicit) (Syntax: '4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 5, IsImplicit) (Syntax: '5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 6, IsImplicit) (Syntax: '6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfSingleDimensionalArrays() { string source = @" class C { public void F() { int[][] a = /*<bind>*/new int[][] { new[] { 1, 2, 3 }, new int[5] }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][]) (Syntax: 'new int[][] ... ew int[5] }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new int[][] ... ew int[5] }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new[] { 1 ... ew int[5] }') Element Values(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { 1, 2, 3 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new[] { 1, 2, 3 }') Initializer: IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2, 3 }') Element Values(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[5]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfMultiDimensionalArrays() { string source = @" class C { public void F() { int[][,] a = /*<bind>*/new int[1][,]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][,]) (Syntax: 'new int[1][,]') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfImplicitlyTypedMultiDimensionalArrays_WithInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/new[] { new[, ,] { { { 1, 2 } } }, new[, ,] { { { 3, 4 } } } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][,,]) (Syntax: 'new[] { new ... , 4 } } } }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[] { new ... , 4 } } } }') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new[, ,] ... , 4 } } } }') Element Values(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,,]) (Syntax: 'new[, ,] { ... 1, 2 } } }') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { { 1, 2 } } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 1, 2 } }') Element Values(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,,]) (Syntax: 'new[, ,] { ... 3, 4 } } }') Dimension Sizes(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { { 3, 4 } } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { 3, 4 } }') Element Values(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 3, 4 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_MissingDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[]') Dimension Sizes(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1586: Array creation must have array size or array initializer // var a = /*<bind>*/new string[]/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 37) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvalidInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/new string[] { 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[] { 1 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'new string[] { 1 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // var a = /*<bind>*/new string[] { 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_MissingExplicitCast() { string source = @" class C { public void F(object b) { var a = /*<bind>*/new string[b]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[b]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'b') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/new string[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("object", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreation_InvocationExpressionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[M()]/*</bind>*/; } public int M() => 1; } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[M()]') Dimension Sizes(1): IInvocationOperation ( System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreation_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[(int)M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[]) (Syntax: 'new string[(int)M()]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Object C.M()) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvocationExpressionAsDimension() { string source = @" class C { public static void F() { var a = /*<bind>*/new string[M()]/*</bind>*/; } public static object M() => null; } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[M()]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (System.Object C.M()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/new string[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "M()").WithArguments("object", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[(int)M()]/*</bind>*/; } public C M() => new C(); } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[(int)M()]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( C C.M()) (OperationKind.Invocation, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'C' to 'int' // var a = /*<bind>*/new string[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)M()").WithArguments("C", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")] public void SimpleArrayCreation_ConstantConversion() { string source = @" class C { public void F() { var a = /*<bind>*/new string[0.0]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String[], IsInvalid) (Syntax: 'new string[0.0]') Dimension Sizes(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/new string[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0.0").WithArguments("double", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_NoControlFlow() { string source = @" class C { const int c1 = 2, c2 = 1, c3 = 1; void M(int[] a1, int[] a2, int[,] a3, int[,] a4, int[][] a5, int[][] a6, int d1, int d2, int d3, int d4, int v1, int v2, int v3, int v4) /*<bind>*/ { a1 = new int[d1]; // Single dimension, no initializer a2 = new int[] { v1 }; // Single dimension, initializer a3 = new int[d2, d3]; // Multi-dimension, no initializer a4 = new int[c1, c2] { { v2 }, { v3 } }; // Multi-dimension, initializer a5 = new int[d4][]; // Jagged, no initializer a6 = new int[c3][] { new[] { v4 } }; // Jagged, initializer int[] f = { 1, 3, 4 }; // Array creation with only initializer. }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32[] f] Block[B1] - Block Predecessors: [B0] Statements (7) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new int[d1];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new int[d1]') Left: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[d1]') Dimension Sizes(1): IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd1') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a2 = new int[] { v1 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a2 = new int[] { v1 }') Left: IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a2') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[] { v1 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new int[] { v1 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a3 = new int[d2, d3];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a3 = new int[d2, d3]') Left: IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a3') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[d2, d3]') Dimension Sizes(2): IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd2') IParameterReferenceOperation: d3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd3') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a4 = new in ... , { v3 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a4 = new in ... }, { v3 } }') Left: IParameterReferenceOperation: a4 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a4') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... }, { v3 } }') Dimension Sizes(2): IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v2 }, { v3 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v2 }') Element Values(1): IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 }') Element Values(1): IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a5 = new int[d4][];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[][]) (Syntax: 'a5 = new int[d4][]') Left: IParameterReferenceOperation: a5 (OperationKind.ParameterReference, Type: System.Int32[][]) (Syntax: 'a5') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][]) (Syntax: 'new int[d4][]') Dimension Sizes(1): IParameterReferenceOperation: d4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd4') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a6 = new in ... ] { v4 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[][]) (Syntax: 'a6 = new in ... [] { v4 } }') Left: IParameterReferenceOperation: a6 (OperationKind.ParameterReference, Type: System.Int32[][]) (Syntax: 'a6') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[][]) (Syntax: 'new int[c3] ... [] { v4 } }') Dimension Sizes(1): IFieldReferenceOperation: System.Int32 C.c3 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c3') Instance Receiver: null Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ new[] { v4 } }') Element Values(1): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { v4 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { v4 }') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v4 }') Element Values(1): IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[], IsImplicit) (Syntax: 'f = { 1, 3, 4 }') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32[], IsImplicit) (Syntax: 'f = { 1, 3, 4 }') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsImplicit) (Syntax: '{ 1, 3, 4 }') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '{ 1, 3, 4 }') Initializer: IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1, 3, 4 }') Element Values(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstDimension_NoInitializer() { string source = @" class C { void M(int[,] a1, int? d1, int d2, int c) /*<bind>*/ { a1 = new int[d1 ?? d2, c]; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ?? d2, c];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... 1 ?? d2, c]') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[d1 ?? d2, c]') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'd1 ?? d2') IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Initializer: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstDimension_WithInitializer() { string source = @" class C { const int c = 1; void M(int[,] a1, int? d1, int d2, int v1) /*<bind>*/ { a1 = new int[d1 ?? d2, c] { { v1 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... { { v1 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... { { v1 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[d1 ... { { v1 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') IFieldReferenceOperation: System.Int32 C.c (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c') Instance Receiver: null Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, c] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(8, 22) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondDimension_NoInitializer() { string source = @" class C { void M(int[,] a1, int? d1, int d2, int c) /*<bind>*/ { a1 = new int[c, d1 ?? d2]; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... d1 ?? d2];') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... , d1 ?? d2]') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c, d1 ?? d2]') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'd1 ?? d2') Initializer: null Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondDimension_WithInitializer() { string source = @" class C { const int c = 1; void M(int[,] a1, int? d1, int d2, int v1) /*<bind>*/ { a1 = new int[c, d1 ?? d2] { { v1 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IFieldReferenceOperation: System.Int32 C.c (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... { { v1 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... { { v1 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[c, ... { { v1 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,25): error CS0150: A constant value is expected // a1 = new int[c, d1 ?? d2] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(8, 25) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleDimensions() { string source = @" class C { void M(int[,] a1, int? d1, int d2, int? d3, int d4, int v1) /*<bind>*/ { a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IParameterReferenceOperation: d3 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd3') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd4') Value: IParameterReferenceOperation: d4 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd4') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... { { v1 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... { { v1 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[d1 ... { { v1 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3 ?? d4') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 } }') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 }') Element Values(1): IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v1') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(7, 22), // file.cs(7,32): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d3 ?? d4").WithLocation(7, 32) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstInitializerValue_SingleDimArray() { string source = @" class C { const int c1 = 2; void M(int[] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1] { v1 ?? v2, v3 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ? v2, v3 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new in ... ?? v2, v3 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[c1] ... ?? v2, v3 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2, v3 }') Element Values(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInFirstInitializerValue_MultiDimArray() { string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1, c2] { { v1 ?? v2 }, { v3 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... , { v3 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... }, { v3 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... }, { v3 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 ?? v2 }, { v3 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 }') Element Values(1): IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondInitializerValue_SingleDimArray() { string source = @" class C { const int c1 = 2; void M(int[] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1] { v3, v1 ?? v2 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... v1 ?? v2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new in ... v1 ?? v2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[c1] ... v1 ?? v2 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3, v1 ?? v2 }') Element Values(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondInitializerValue_MultiDimArray() { string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1, c2] { { v3 }, { v1 ?? v2 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [4] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ?? v2 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... 1 ?? v2 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... 1 ?? v2 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v3 }, { v1 ?? v2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 }') Element Values(1): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInSecondInitializerValue_MultiDimArray_02() { // Error case where one array initializer element value is a nested array initializer and another one is not. // Verifies that CFG builder handles the mixed kind element values. string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int v3) /*<bind>*/ { a1 = new int[c1, c2] { v3, { v1 ?? v2 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'v3') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'v3') Children(1): IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'v3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [4] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... ?? v2 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... 1 ?? v2 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[c1, ... 1 ?? v2 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ v3, { v1 ?? v2 } }') Element Values(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'v3') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,32): error CS0846: A nested array initializer is expected // a1 = new int[c1, c2] { v3, { v1 ?? v2 } }; Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "v3").WithLocation(8, 32) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleInitializerValues_SingleDimArray() { string source = @" class C { const int c1 = 2; void M(int[] a1, int? v1, int v2, int? v3, int v4) /*<bind>*/ { a1 = new int[c1] { v1 ?? v2, v3 ?? v4 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [4] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... v3 ?? v4 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[]) (Syntax: 'a1 = new in ... v3 ?? v4 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[c1] ... v3 ?? v4 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2, v3 ?? v4 }') Element Values(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleInitializerValues_MultiDimArray() { string source = @" class C { const int c1 = 2, c2 = 1; void M(int[,] a1, int? v1, int v2, int? v3, int v4) /*<bind>*/ { a1 = new int[c1, c2] { { v1 ?? v2 }, { v3 ?? v4 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] [6] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFieldReferenceOperation: System.Int32 C.c1 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 2) (Syntax: 'c1') Instance Receiver: null IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IFieldReferenceOperation: System.Int32 C.c2 (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 1) (Syntax: 'c2') Instance Receiver: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new in ... ?? v4 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,]) (Syntax: 'a1 = new in ... 3 ?? v4 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,]) (Syntax: 'new int[c1, ... 3 ?? v4 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'c1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'c2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 ?? v ... 3 ?? v4 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 ?? v4 }') Element Values(1): IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInDimensionAndMultipleInitializerValues_SingleDimArray() { string source = @" class C { void M(int[] a1, int? v1, int v2, int? v3, int v4, int? d1, int d2) /*<bind>*/ { a1 = new int[d1 ?? d2] { v1 ?? v2, v3 ?? v4 }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] [6] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { CaptureIds: [5] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R4} Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B11] Leaving: {R4} } Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... v3 ?? v4 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[], IsInvalid) (Syntax: 'a1 = new in ... v3 ?? v4 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[], IsInvalid) (Syntax: 'new int[d1 ... v3 ?? v4 }') Dimension Sizes(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2, v3 ?? v4 }') Element Values(2): IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B12] Leaving: {R1} } Block[B12] - Exit Predecessors: [B11] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2] { v1 ?? v2, v3 ?? v4 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(7, 22) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ArrayCreationAndInitializer_ControlFlowInMultipleDimensionsAndInitializerValues_MultiDimArray() { string source = @" class C { void M(int[,] a1, int? v1, int v2, int? v3, int v4, int? d1, int d2, int? d3, int d4) /*<bind>*/ { a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 ?? v2 }, { v3 ?? v4 } }; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] [6] [8] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1') Value: IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32[,]) (Syntax: 'a1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IParameterReferenceOperation: d3 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'd3') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'd3') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'd3') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'd4') Value: IParameterReferenceOperation: d4 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'd4') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { CaptureIds: [5] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IParameterReferenceOperation: v1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v1') Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v1') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Leaving: {R4} Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v1') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v1') Arguments(0) Next (Regular) Block[B11] Leaving: {R4} Entering: {R5} } Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v2') Value: IParameterReferenceOperation: v2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v2') Next (Regular) Block[B11] Entering: {R5} .locals {R5} { CaptureIds: [7] Block[B11] - Block Predecessors: [B9] [B10] Statements (1) IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IParameterReferenceOperation: v3 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'v3') Jump if True (Regular) to Block[B13] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'v3') Operand: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Leaving: {R5} Next (Regular) Block[B12] Block[B12] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v3') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'v3') Instance Receiver: IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'v3') Arguments(0) Next (Regular) Block[B14] Leaving: {R5} } Block[B13] - Block Predecessors: [B11] Statements (1) IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v4') Value: IParameterReferenceOperation: v4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'v4') Next (Regular) Block[B14] Block[B14] - Block Predecessors: [B12] [B13] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = new in ... ?? v4 } };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32[,], IsInvalid) (Syntax: 'a1 = new in ... 3 ?? v4 } }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32[,], IsImplicit) (Syntax: 'a1') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[,], IsInvalid) (Syntax: 'new int[d1 ... 3 ?? v4 } }') Dimension Sizes(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd3 ?? d4') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ { v1 ?? v ... 3 ?? v4 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v1 ?? v2 }') Element Values(1): IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v1 ?? v2') IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ v3 ?? v4 }') Element Values(1): IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'v3 ?? v4') Next (Regular) Block[B15] Leaving: {R1} } Block[B15] - Exit Predecessors: [B14] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,22): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 ?? v2 }, { v3 ?? v4 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d1 ?? d2").WithLocation(7, 22), // file.cs(7,32): error CS0150: A constant value is expected // a1 = new int[d1 ?? d2, d3 ?? d4] { { v1 ?? v2 }, { v3 ?? v4 } }; Diagnostic(ErrorCode.ERR_ConstantExpected, "d3 ?? d4").WithLocation(7, 32) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DynamicTests.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.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : CSharpResultProviderTestBase { [Fact] public void Simple() { var value = CreateDkmClrValue(new object()); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object)), declaredTypeInfo: MakeCustomTypeInfo(true)); Verify(evalResult, EvalResult(rootExpr, "{object}", "dynamic {object}", rootExpr)); } [Fact] public void Member() { var source = @" class C { dynamic F; dynamic P { get; set; } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "null", "dynamic {object}", "(new C()).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "null", "dynamic {object}", "(new C()).P", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_ConstructedType() { var source = @" class C<T, U> { T Simple; U[] Array; C<U, T> Constructed; C<C<C<object, T>, dynamic[]>, U[]>[] Complex; }"; var assembly = GetAssembly(source); var typeC = assembly.GetType("C`2"); var typeC_Constructed1 = typeC.MakeGenericType(typeof(object), typeof(object)); // C<object, dynamic> var typeC_Constructed2 = typeC.MakeGenericType(typeof(object), typeC_Constructed1); // C<dynamic, C<object, dynamic>> (i.e. T = dynamic, U = C<object, dynamic>) var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed2)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed2), MakeCustomTypeInfo(false, true, false, false, true)); Verify(evalResult, EvalResult(rootExpr, "{C<object, C<object, object>>}", "C<dynamic, C<object, dynamic>> {C<object, C<object, object>>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "null", "C<object, dynamic>[] {C<object, object>[]}", "c.Array", DkmEvaluationResultFlags.CanFavorite), EvalResult("Complex", "null", "C<C<C<object, dynamic>, dynamic[]>, C<object, dynamic>[]>[] {C<C<C<object, object>, object[]>, C<object, object>[]>[]}", "c.Complex", DkmEvaluationResultFlags.CanFavorite), EvalResult("Constructed", "null", "C<C<object, dynamic>, dynamic> {C<C<object, object>, object>}", "c.Constructed", DkmEvaluationResultFlags.CanFavorite), EvalResult("Simple", "null", "dynamic {object}", "c.Simple", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_NestedType() { var source = @" class Outer<T> { class Inner<U> { T Simple; U[] Array; Outer<U>.Inner<T> Constructed; } }"; var assembly = GetAssembly(source); var typeInner = assembly.GetType("Outer`1+Inner`1"); var typeInner_Constructed = typeInner.MakeGenericType(typeof(object), typeof(object)); // Outer<dynamic>.Inner<object> var value = CreateDkmClrValue(Activator.CreateInstance(typeInner_Constructed)); var rootExpr = "i"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeInner_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{Outer<object>.Inner<object>}", "Outer<dynamic>.Inner<object> {Outer<object>.Inner<object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "null", "object[]", "i.Array", DkmEvaluationResultFlags.CanFavorite), EvalResult("Constructed", "null", "Outer<object>.Inner<dynamic> {Outer<object>.Inner<object>}", "i.Constructed", DkmEvaluationResultFlags.CanFavorite), EvalResult("Simple", "null", "dynamic {object}", "i.Simple", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_ConstructedTypeMember() { var source = @" class C<T> where T : new() { T Simple = new T(); T[] Array = new[] { new T() }; D<T, object, dynamic> Constructed = new D<T, object, dynamic>(); } class D<T, U, V> { T TT; U UU; V VV; }"; var assembly = GetAssembly(source); var typeD = assembly.GetType("D`3"); var typeD_Constructed = typeD.MakeGenericType(typeof(object), typeof(object), typeof(int)); // D<object, dynamic, int> var typeC = assembly.GetType("C`1"); var typeC_Constructed = typeC.MakeGenericType(typeD_Constructed); // C<D<object, dynamic, int>> var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), MakeCustomTypeInfo(false, false, false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{C<D<object, object, int>>}", "C<D<object, dynamic, int>> {C<D<object, object, int>>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "{D<object, object, int>[1]}", "D<object, dynamic, int>[] {D<object, object, int>[]}", "c.Array", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Constructed", "{D<D<object, object, int>, object, object>}", "D<D<object, dynamic, int>, object, dynamic> {D<D<object, object, int>, object, object>}", "c.Constructed", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Simple", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Simple", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children[0]), EvalResult("[0]", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Array[0]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[1]), EvalResult("TT", "null", "D<object, dynamic, int> {D<object, object, int>}", "c.Constructed.TT", DkmEvaluationResultFlags.CanFavorite), EvalResult("UU", "null", "object", "c.Constructed.UU", DkmEvaluationResultFlags.CanFavorite), EvalResult("VV", "null", "dynamic {object}", "c.Constructed.VV", DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children[2]), EvalResult("TT", "null", "object", "c.Simple.TT", DkmEvaluationResultFlags.CanFavorite), EvalResult("UU", "null", "dynamic {object}", "c.Simple.UU", DkmEvaluationResultFlags.CanFavorite), EvalResult("VV", "0", "int", "c.Simple.VV", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_ExplicitInterfaceImplementation() { var source = @" interface I<V, W> { V P { get; set; } W Q { get; set; } } class C<T, U> : I<long, T>, I<bool, U> { long I<long, T>.P { get; set; } T I<long, T>.Q { get; set; } bool I<bool, U>.P { get; set; } U I<bool, U>.Q { get; set; } }"; var assembly = GetAssembly(source); var typeC = assembly.GetType("C`2"); var typeC_Constructed = typeC.MakeGenericType(typeof(object), typeof(object)); // C<dynamic, object> var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{C<object, object>}", "C<dynamic, object> {C<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("I<bool, object>.P", "false", "bool", "((I<bool, object>)c).P", DkmEvaluationResultFlags.Boolean), EvalResult("I<bool, object>.Q", "null", "object", "((I<bool, object>)c).Q"), EvalResult("I<long, dynamic>.P", "0", "long", "((I<long, dynamic>)c).P"), EvalResult("I<long, dynamic>.Q", "null", "dynamic {object}", "((I<long, dynamic>)c).Q")); } [Fact] public void Member_BaseType() { var source = @" class Base<T, U, V, W> { public T P; public U Q; public V R; public W S; } class Derived<T, U> : Base<T, U, object, dynamic> { new public T[] P; new public U[] Q; new public dynamic[] R; new public object[] S; }"; var assembly = GetAssembly(source); var typeDerived = assembly.GetType("Derived`2"); var typeDerived_Constructed = typeDerived.MakeGenericType(typeof(object), typeof(object)); // Derived<dynamic, object> var value = CreateDkmClrValue(Activator.CreateInstance(typeDerived_Constructed)); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeDerived_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{Derived<object, object>}", "Derived<dynamic, object> {Derived<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); // CONSIDER: It would be nice to substitute "dynamic" where appropriate. var children = GetChildren(evalResult); Verify(children, EvalResult("P (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).P"), EvalResult("P", "null", "dynamic[] {object[]}", "d.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("Q (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).Q"), EvalResult("Q", "null", "object[]", "d.Q", DkmEvaluationResultFlags.CanFavorite), EvalResult("R (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).R"), EvalResult("R", "null", "dynamic[] {object[]}", "d.R", DkmEvaluationResultFlags.CanFavorite), EvalResult("S (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).S"), EvalResult("S", "null", "object[]", "d.S", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void ArrayElement() { var value = CreateDkmClrValue(new object[1]); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object[])), declaredTypeInfo: MakeCustomTypeInfo(false, true)); Verify(evalResult, EvalResult(rootExpr, "{object[1]}", "dynamic[] {object[]}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "null", "dynamic {object}", "d[0]")); } [Fact] public void TypeVariables() { var intrinsicSource = @".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U,V> { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CommonTestBase.EmitILToArray(intrinsicSource, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var reflectionType = assembly.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType(new[] { typeof(object), typeof(object), typeof(object[]) }); var value = CreateDkmClrValue(value: null, type: reflectionType, valueFlags: DkmClrValueFlags.Synthetic); var evalResult = FormatResult("typevars", "typevars", value, new DkmClrType((TypeImpl)reflectionType), MakeCustomTypeInfo(false, true, false, false, true)); Verify(evalResult, EvalResult("Type variables", "", "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var children = GetChildren(evalResult); Verify(children, EvalResult("T", "dynamic", "dynamic", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("U", "object", "object", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("V", "dynamic[]", "dynamic[]", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } [WorkItem(13554, "https://github.com/dotnet/roslyn/issues/13554")] [Fact(Skip = "13554")] public void DynamicBaseTypeArgument() { var source = @"class A<T> { #pragma warning disable 0169 internal T F; #pragma warning restore 0169 } class B : A<dynamic> { B() { F = 1; } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("B"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "1", "dynamic {int}", "o.F")); } } } }
// Licensed to the .NET Foundation under one or more 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.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : CSharpResultProviderTestBase { [Fact] public void Simple() { var value = CreateDkmClrValue(new object()); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object)), declaredTypeInfo: MakeCustomTypeInfo(true)); Verify(evalResult, EvalResult(rootExpr, "{object}", "dynamic {object}", rootExpr)); } [Fact] public void Member() { var source = @" class C { dynamic F; dynamic P { get; set; } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var rootExpr = "new C()"; var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "null", "dynamic {object}", "(new C()).F", DkmEvaluationResultFlags.CanFavorite), EvalResult("P", "null", "dynamic {object}", "(new C()).P", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_ConstructedType() { var source = @" class C<T, U> { T Simple; U[] Array; C<U, T> Constructed; C<C<C<object, T>, dynamic[]>, U[]>[] Complex; }"; var assembly = GetAssembly(source); var typeC = assembly.GetType("C`2"); var typeC_Constructed1 = typeC.MakeGenericType(typeof(object), typeof(object)); // C<object, dynamic> var typeC_Constructed2 = typeC.MakeGenericType(typeof(object), typeC_Constructed1); // C<dynamic, C<object, dynamic>> (i.e. T = dynamic, U = C<object, dynamic>) var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed2)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed2), MakeCustomTypeInfo(false, true, false, false, true)); Verify(evalResult, EvalResult(rootExpr, "{C<object, C<object, object>>}", "C<dynamic, C<object, dynamic>> {C<object, C<object, object>>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "null", "C<object, dynamic>[] {C<object, object>[]}", "c.Array", DkmEvaluationResultFlags.CanFavorite), EvalResult("Complex", "null", "C<C<C<object, dynamic>, dynamic[]>, C<object, dynamic>[]>[] {C<C<C<object, object>, object[]>, C<object, object>[]>[]}", "c.Complex", DkmEvaluationResultFlags.CanFavorite), EvalResult("Constructed", "null", "C<C<object, dynamic>, dynamic> {C<C<object, object>, object>}", "c.Constructed", DkmEvaluationResultFlags.CanFavorite), EvalResult("Simple", "null", "dynamic {object}", "c.Simple", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_NestedType() { var source = @" class Outer<T> { class Inner<U> { T Simple; U[] Array; Outer<U>.Inner<T> Constructed; } }"; var assembly = GetAssembly(source); var typeInner = assembly.GetType("Outer`1+Inner`1"); var typeInner_Constructed = typeInner.MakeGenericType(typeof(object), typeof(object)); // Outer<dynamic>.Inner<object> var value = CreateDkmClrValue(Activator.CreateInstance(typeInner_Constructed)); var rootExpr = "i"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeInner_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{Outer<object>.Inner<object>}", "Outer<dynamic>.Inner<object> {Outer<object>.Inner<object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "null", "object[]", "i.Array", DkmEvaluationResultFlags.CanFavorite), EvalResult("Constructed", "null", "Outer<object>.Inner<dynamic> {Outer<object>.Inner<object>}", "i.Constructed", DkmEvaluationResultFlags.CanFavorite), EvalResult("Simple", "null", "dynamic {object}", "i.Simple", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_ConstructedTypeMember() { var source = @" class C<T> where T : new() { T Simple = new T(); T[] Array = new[] { new T() }; D<T, object, dynamic> Constructed = new D<T, object, dynamic>(); } class D<T, U, V> { T TT; U UU; V VV; }"; var assembly = GetAssembly(source); var typeD = assembly.GetType("D`3"); var typeD_Constructed = typeD.MakeGenericType(typeof(object), typeof(object), typeof(int)); // D<object, dynamic, int> var typeC = assembly.GetType("C`1"); var typeC_Constructed = typeC.MakeGenericType(typeD_Constructed); // C<D<object, dynamic, int>> var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), MakeCustomTypeInfo(false, false, false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{C<D<object, object, int>>}", "C<D<object, dynamic, int>> {C<D<object, object, int>>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Array", "{D<object, object, int>[1]}", "D<object, dynamic, int>[] {D<object, object, int>[]}", "c.Array", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Constructed", "{D<D<object, object, int>, object, object>}", "D<D<object, dynamic, int>, object, dynamic> {D<D<object, object, int>, object, object>}", "c.Constructed", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Simple", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Simple", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children[0]), EvalResult("[0]", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Array[0]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[1]), EvalResult("TT", "null", "D<object, dynamic, int> {D<object, object, int>}", "c.Constructed.TT", DkmEvaluationResultFlags.CanFavorite), EvalResult("UU", "null", "object", "c.Constructed.UU", DkmEvaluationResultFlags.CanFavorite), EvalResult("VV", "null", "dynamic {object}", "c.Constructed.VV", DkmEvaluationResultFlags.CanFavorite)); Verify(GetChildren(children[2]), EvalResult("TT", "null", "object", "c.Simple.TT", DkmEvaluationResultFlags.CanFavorite), EvalResult("UU", "null", "dynamic {object}", "c.Simple.UU", DkmEvaluationResultFlags.CanFavorite), EvalResult("VV", "0", "int", "c.Simple.VV", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void Member_ExplicitInterfaceImplementation() { var source = @" interface I<V, W> { V P { get; set; } W Q { get; set; } } class C<T, U> : I<long, T>, I<bool, U> { long I<long, T>.P { get; set; } T I<long, T>.Q { get; set; } bool I<bool, U>.P { get; set; } U I<bool, U>.Q { get; set; } }"; var assembly = GetAssembly(source); var typeC = assembly.GetType("C`2"); var typeC_Constructed = typeC.MakeGenericType(typeof(object), typeof(object)); // C<dynamic, object> var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed)); var rootExpr = "c"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{C<object, object>}", "C<dynamic, object> {C<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("I<bool, object>.P", "false", "bool", "((I<bool, object>)c).P", DkmEvaluationResultFlags.Boolean), EvalResult("I<bool, object>.Q", "null", "object", "((I<bool, object>)c).Q"), EvalResult("I<long, dynamic>.P", "0", "long", "((I<long, dynamic>)c).P"), EvalResult("I<long, dynamic>.Q", "null", "dynamic {object}", "((I<long, dynamic>)c).Q")); } [Fact] public void Member_BaseType() { var source = @" class Base<T, U, V, W> { public T P; public U Q; public V R; public W S; } class Derived<T, U> : Base<T, U, object, dynamic> { new public T[] P; new public U[] Q; new public dynamic[] R; new public object[] S; }"; var assembly = GetAssembly(source); var typeDerived = assembly.GetType("Derived`2"); var typeDerived_Constructed = typeDerived.MakeGenericType(typeof(object), typeof(object)); // Derived<dynamic, object> var value = CreateDkmClrValue(Activator.CreateInstance(typeDerived_Constructed)); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeDerived_Constructed), MakeCustomTypeInfo(false, true, false)); Verify(evalResult, EvalResult(rootExpr, "{Derived<object, object>}", "Derived<dynamic, object> {Derived<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable)); // CONSIDER: It would be nice to substitute "dynamic" where appropriate. var children = GetChildren(evalResult); Verify(children, EvalResult("P (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).P"), EvalResult("P", "null", "dynamic[] {object[]}", "d.P", DkmEvaluationResultFlags.CanFavorite), EvalResult("Q (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).Q"), EvalResult("Q", "null", "object[]", "d.Q", DkmEvaluationResultFlags.CanFavorite), EvalResult("R (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).R"), EvalResult("R", "null", "dynamic[] {object[]}", "d.R", DkmEvaluationResultFlags.CanFavorite), EvalResult("S (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).S"), EvalResult("S", "null", "object[]", "d.S", DkmEvaluationResultFlags.CanFavorite)); } [Fact] public void ArrayElement() { var value = CreateDkmClrValue(new object[1]); var rootExpr = "d"; var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object[])), declaredTypeInfo: MakeCustomTypeInfo(false, true)); Verify(evalResult, EvalResult(rootExpr, "{object[1]}", "dynamic[] {object[]}", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "null", "dynamic {object}", "d[0]")); } [Fact] public void TypeVariables() { var intrinsicSource = @".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U,V> { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CommonTestBase.EmitILToArray(intrinsicSource, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var reflectionType = assembly.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType(new[] { typeof(object), typeof(object), typeof(object[]) }); var value = CreateDkmClrValue(value: null, type: reflectionType, valueFlags: DkmClrValueFlags.Synthetic); var evalResult = FormatResult("typevars", "typevars", value, new DkmClrType((TypeImpl)reflectionType), MakeCustomTypeInfo(false, true, false, false, true)); Verify(evalResult, EvalResult("Type variables", "", "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var children = GetChildren(evalResult); Verify(children, EvalResult("T", "dynamic", "dynamic", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("U", "object", "object", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("V", "dynamic[]", "dynamic[]", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } [WorkItem(13554, "https://github.com/dotnet/roslyn/issues/13554")] [Fact(Skip = "13554")] public void DynamicBaseTypeArgument() { var source = @"class A<T> { #pragma warning disable 0169 internal T F; #pragma warning restore 0169 } class B : A<dynamic> { B() { F = 1; } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("B"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "1", "dynamic {int}", "o.F")); } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Test/Core/Pe/BrokenStream.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; namespace Roslyn.Test.Utilities { internal class BrokenStream : Stream { public enum BreakHowType { ThrowOnSetPosition, ThrowOnWrite, ThrowOnSetLength, CancelOnWrite } public BreakHowType BreakHow; public Exception ThrownException { get; private set; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { if (BreakHow == BreakHowType.ThrowOnSetPosition) { ThrownException = new NotSupportedException(); throw ThrownException; } } } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { if (BreakHow == BreakHowType.ThrowOnSetLength) { ThrownException = new IOException(); throw ThrownException; } } public override void Write(byte[] buffer, int offset, int count) { if (BreakHow == BreakHowType.ThrowOnWrite) { ThrownException = new IOException(); throw ThrownException; } else if (BreakHow == BreakHowType.CancelOnWrite) { ThrownException = new OperationCanceledException(); throw ThrownException; } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Roslyn.Test.Utilities { internal class BrokenStream : Stream { public enum BreakHowType { ThrowOnSetPosition, ThrowOnWrite, ThrowOnSetLength, CancelOnWrite } public BreakHowType BreakHow; public Exception ThrownException { get; private set; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { if (BreakHow == BreakHowType.ThrowOnSetPosition) { ThrownException = new NotSupportedException(); throw ThrownException; } } } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { if (BreakHow == BreakHowType.ThrowOnSetLength) { ThrownException = new IOException(); throw ThrownException; } } public override void Write(byte[] buffer, int offset, int count) { if (BreakHow == BreakHowType.ThrowOnWrite) { ThrownException = new IOException(); throw ThrownException; } else if (BreakHow == BreakHowType.CancelOnWrite) { ThrownException = new OperationCanceledException(); throw ThrownException; } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProviderBase_MethodGroup.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal partial class InvocationExpressionSignatureHelpProviderBase { internal virtual Task<(ImmutableArray<SignatureHelpItem> items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync( ImmutableArray<IMethodSymbol> accessibleMethods, Document document, InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, SymbolInfo currentSymbol, CancellationToken cancellationToken) { return Task.FromResult( (accessibleMethods.SelectAsArray(m => ConvertMethodGroupMethod(document, m, invocationExpression.SpanStart, semanticModel)), TryGetSelectedIndex(accessibleMethods, currentSymbol.Symbol))); } private static ImmutableArray<IMethodSymbol> GetAccessibleMethods( InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, ISymbol within, IEnumerable<IMethodSymbol> methodGroup, CancellationToken cancellationToken) { ITypeSymbol? throughType = null; if (invocationExpression.Expression is MemberAccessExpressionSyntax memberAccess) { var throughExpression = memberAccess.Expression; var throughSymbol = semanticModel.GetSymbolInfo(throughExpression, cancellationToken).GetAnySymbol(); // if it is via a base expression "base.", we know the "throughType" is the base class but // we need to be able to tell between "base.M()" and "new Base().M()". // currently, Access check methods do not differentiate between them. // so handle "base." primary-expression here by nulling out "throughType" if (!(throughExpression is BaseExpressionSyntax)) { throughType = semanticModel.GetTypeInfo(throughExpression, cancellationToken).Type; } var includeInstance = !throughExpression.IsKind(SyntaxKind.IdentifierName) || semanticModel.LookupSymbols(throughExpression.SpanStart, name: throughSymbol?.Name).Any(s => !(s is INamedTypeSymbol)) || (!(throughSymbol is INamespaceOrTypeSymbol) && semanticModel.LookupSymbols(throughExpression.SpanStart, container: throughSymbol?.ContainingType).Any(s => !(s is INamedTypeSymbol))); var includeStatic = throughSymbol is INamedTypeSymbol || (throughExpression.IsKind(SyntaxKind.IdentifierName) && semanticModel.LookupNamespacesAndTypes(throughExpression.SpanStart, name: throughSymbol?.Name).Any(t => Equals(t.GetSymbolType(), throughType))); Contract.ThrowIfFalse(includeInstance || includeStatic); methodGroup = methodGroup.Where(m => (m.IsStatic && includeStatic) || (!m.IsStatic && includeInstance)); } else if (invocationExpression.Expression is SimpleNameSyntax && invocationExpression.IsInStaticContext()) { // We always need to include local functions regardless of whether they are static. methodGroup = methodGroup.Where(m => m.IsStatic || m is IMethodSymbol { MethodKind: MethodKind.LocalFunction }); } var accessibleMethods = methodGroup.Where(m => m.IsAccessibleWithin(within, throughType: throughType)).ToImmutableArrayOrEmpty(); if (accessibleMethods.Length == 0) { return accessibleMethods; } var methodSet = accessibleMethods.ToSet(); return accessibleMethods.Where(m => !IsHiddenByOtherMethod(m, methodSet)).ToImmutableArrayOrEmpty(); } private static bool IsHiddenByOtherMethod(IMethodSymbol method, ISet<IMethodSymbol> methodSet) { foreach (var m in methodSet) { if (!Equals(m, method)) { if (IsHiddenBy(method, m)) { return true; } } } return false; } private static bool IsHiddenBy(IMethodSymbol method1, IMethodSymbol method2) { // If they have the same parameter types and the same parameter names, then the // constructed method is hidden by the unconstructed one. return method2.IsMoreSpecificThan(method1) == 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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal partial class InvocationExpressionSignatureHelpProviderBase { internal virtual Task<(ImmutableArray<SignatureHelpItem> items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync( ImmutableArray<IMethodSymbol> accessibleMethods, Document document, InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, SymbolInfo currentSymbol, CancellationToken cancellationToken) { return Task.FromResult( (accessibleMethods.SelectAsArray(m => ConvertMethodGroupMethod(document, m, invocationExpression.SpanStart, semanticModel)), TryGetSelectedIndex(accessibleMethods, currentSymbol.Symbol))); } private static ImmutableArray<IMethodSymbol> GetAccessibleMethods( InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, ISymbol within, IEnumerable<IMethodSymbol> methodGroup, CancellationToken cancellationToken) { ITypeSymbol? throughType = null; if (invocationExpression.Expression is MemberAccessExpressionSyntax memberAccess) { var throughExpression = memberAccess.Expression; var throughSymbol = semanticModel.GetSymbolInfo(throughExpression, cancellationToken).GetAnySymbol(); // if it is via a base expression "base.", we know the "throughType" is the base class but // we need to be able to tell between "base.M()" and "new Base().M()". // currently, Access check methods do not differentiate between them. // so handle "base." primary-expression here by nulling out "throughType" if (!(throughExpression is BaseExpressionSyntax)) { throughType = semanticModel.GetTypeInfo(throughExpression, cancellationToken).Type; } var includeInstance = !throughExpression.IsKind(SyntaxKind.IdentifierName) || semanticModel.LookupSymbols(throughExpression.SpanStart, name: throughSymbol?.Name).Any(s => !(s is INamedTypeSymbol)) || (!(throughSymbol is INamespaceOrTypeSymbol) && semanticModel.LookupSymbols(throughExpression.SpanStart, container: throughSymbol?.ContainingType).Any(s => !(s is INamedTypeSymbol))); var includeStatic = throughSymbol is INamedTypeSymbol || (throughExpression.IsKind(SyntaxKind.IdentifierName) && semanticModel.LookupNamespacesAndTypes(throughExpression.SpanStart, name: throughSymbol?.Name).Any(t => Equals(t.GetSymbolType(), throughType))); Contract.ThrowIfFalse(includeInstance || includeStatic); methodGroup = methodGroup.Where(m => (m.IsStatic && includeStatic) || (!m.IsStatic && includeInstance)); } else if (invocationExpression.Expression is SimpleNameSyntax && invocationExpression.IsInStaticContext()) { // We always need to include local functions regardless of whether they are static. methodGroup = methodGroup.Where(m => m.IsStatic || m is IMethodSymbol { MethodKind: MethodKind.LocalFunction }); } var accessibleMethods = methodGroup.Where(m => m.IsAccessibleWithin(within, throughType: throughType)).ToImmutableArrayOrEmpty(); if (accessibleMethods.Length == 0) { return accessibleMethods; } var methodSet = accessibleMethods.ToSet(); return accessibleMethods.Where(m => !IsHiddenByOtherMethod(m, methodSet)).ToImmutableArrayOrEmpty(); } private static bool IsHiddenByOtherMethod(IMethodSymbol method, ISet<IMethodSymbol> methodSet) { foreach (var m in methodSet) { if (!Equals(m, method)) { if (IsHiddenBy(method, m)) { return true; } } } return false; } private static bool IsHiddenBy(IMethodSymbol method1, IMethodSymbol method2) { // If they have the same parameter types and the same parameter names, then the // constructed method is hidden by the unconstructed one. return method2.IsMoreSpecificThan(method1) == true; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Def/Implementation/ExtractClass/ExtractClassDialog.xaml.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.Windows; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { /// <summary> /// Interaction logic for ExtractClassDialog.xaml /// </summary> internal partial class ExtractClassDialog : DialogWindow { public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string SelectMembers => ServicesVSResources.Select_members_colon; public string ExtractClassTitle => ServicesVSResources.Extract_Base_Class; public ExtractClassViewModel ViewModel { get; } public MemberSelection MemberSelectionControl { get; } public ExtractClassDialog(ExtractClassViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = 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.Windows; using System.Windows.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass { /// <summary> /// Interaction logic for ExtractClassDialog.xaml /// </summary> internal partial class ExtractClassDialog : DialogWindow { public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string SelectMembers => ServicesVSResources.Select_members_colon; public string ExtractClassTitle => ServicesVSResources.Extract_Base_Class; public ExtractClassViewModel ViewModel { get; } public MemberSelection MemberSelectionControl { get; } public ExtractClassDialog(ExtractClassViewModel viewModel) { ViewModel = viewModel; DataContext = ViewModel; MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel); Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); InitializeComponent(); } private void OK_Click(object sender, RoutedEventArgs e) { if (ViewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/EditAndContinue/CommittedSolution.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.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Encapsulates access to the last committed solution. /// We don't want to expose the solution directly since access to documents must be gated by out-of-sync checks. /// </summary> internal sealed class CommittedSolution { private readonly DebuggingSession _debuggingSession; private Solution _solution; internal enum DocumentState { None = 0, /// <summary> /// The current document content does not match the content the module was compiled with. /// This document state may change to <see cref="MatchesBuildOutput"/> or <see cref="DesignTimeOnly"/>. /// </summary> OutOfSync = 1, /// <summary> /// It hasn't been possible to determine whether the current document content does matches the content /// the module was compiled with due to error while reading the PDB or the source file. /// This document state may change to <see cref="MatchesBuildOutput"/> or <see cref="DesignTimeOnly"/>. /// </summary> Indeterminate = 2, /// <summary> /// The document is not compiled into the module. It's only included in the project /// to support design-time features such as completion, etc. /// This is a final state. Once a document is in this state it won't switch to a different one. /// </summary> DesignTimeOnly = 3, /// <summary> /// The current document content matches the content the built module was compiled with. /// This is a final state. Once a document is in this state it won't switch to a different one. /// </summary> MatchesBuildOutput = 4 } /// <summary> /// Implements workaround for https://github.com/dotnet/project-system/issues/5457. /// /// When debugging is started we capture the current solution snapshot. /// The documents in this snapshot might not match exactly to those that the compiler used to build the module /// that's currently loaded into the debuggee. This is because there is no reliable synchronization between /// the (design-time) build and Roslyn workspace. Although Roslyn uses file-watchers to watch for changes in /// the files on disk, the file-changed events raised by the build might arrive to Roslyn after the debugger /// has attached to the debuggee and EnC service captured the solution. /// /// Ideally, the Project System would notify Roslyn at the end of each build what the content of the source /// files generated by various targets is. Roslyn would then apply these changes to the workspace and /// the EnC service would capture a solution snapshot that includes these changes. /// /// Since this notification is currently not available we check the current content of source files against /// the corresponding checksums stored in the PDB. Documents for which we have not observed source file content /// that maches the PDB checksum are considered <see cref="DocumentState.OutOfSync"/>. /// /// Some documents in the workspace are added for design-time-only purposes and are not part of the compilation /// from which the assembly is built. These documents won't have a record in the PDB and will be tracked as /// <see cref="DocumentState.DesignTimeOnly"/>. /// /// A document state can only change from <see cref="DocumentState.OutOfSync"/> to <see cref="DocumentState.MatchesBuildOutput"/>. /// Once a document state is <see cref="DocumentState.MatchesBuildOutput"/> or <see cref="DocumentState.DesignTimeOnly"/> /// it will never change. /// </summary> private readonly Dictionary<DocumentId, DocumentState> _documentState; private readonly object _guard = new(); public CommittedSolution(DebuggingSession debuggingSession, Solution solution, IEnumerable<KeyValuePair<DocumentId, DocumentState>> initialDocumentStates) { _solution = solution; _debuggingSession = debuggingSession; _documentState = new Dictionary<DocumentId, DocumentState>(); _documentState.AddRange(initialDocumentStates); } // test only internal void Test_SetDocumentState(DocumentId documentId, DocumentState state) { lock (_guard) { _documentState[documentId] = state; } } // test only internal ImmutableArray<(DocumentId id, DocumentState state)> Test_GetDocumentStates() { lock (_guard) { return _documentState.SelectAsArray(e => (e.Key, e.Value)); } } public bool HasNoChanges(Solution solution) => _solution == solution; public Project? GetProject(ProjectId id) => _solution.GetProject(id); public Project GetRequiredProject(ProjectId id) => _solution.GetRequiredProject(id); public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string path) => _solution.GetDocumentIdsWithFilePath(path); public bool ContainsDocument(DocumentId documentId) => _solution.ContainsDocument(documentId); /// <summary> /// Captures the content of a file that is about to be overwritten by saving an open document, /// if the document is currently out-of-sync and the content of the file matches the PDB. /// If we didn't capture the content before the save we might never be able to find a document /// snapshot that matches the PDB. /// </summary> public Task OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken) => GetDocumentAndStateAsync(document.Id, document, cancellationToken, reloadOutOfSyncDocument: true); /// <summary> /// Returns a document snapshot for given <see cref="Document"/> whose content exactly matches /// the source file used to compile the binary currently loaded in the debuggee. Returns null /// if it fails to find a document snapshot whose content hash maches the one recorded in the PDB. /// /// The result is cached and the next lookup uses the cached value, including failures unless <paramref name="reloadOutOfSyncDocument"/> is true. /// </summary> public async Task<(Document? Document, DocumentState State)> GetDocumentAndStateAsync(DocumentId documentId, Document? currentDocument, CancellationToken cancellationToken, bool reloadOutOfSyncDocument = false) { Contract.ThrowIfFalse(currentDocument == null || documentId == currentDocument.Id); Solution solution; var documentState = DocumentState.None; lock (_guard) { solution = _solution; _documentState.TryGetValue(documentId, out documentState); } var committedDocument = solution.GetDocument(documentId); switch (documentState) { case DocumentState.MatchesBuildOutput: // Note: committedDocument is null if we previously validated that a document that is not in // the committed solution is also not in the PDB. This means the document has been added during debugging. return (committedDocument, documentState); case DocumentState.DesignTimeOnly: return (null, documentState); case DocumentState.OutOfSync: if (reloadOutOfSyncDocument) { break; } return (null, documentState); case DocumentState.Indeterminate: // Previous attempt resulted in a read error. Try again. break; case DocumentState.None: // Have not seen the document before, the document is not in the solution, or the document is source generated. if (committedDocument == null) { var sourceGeneratedDocument = await solution.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (sourceGeneratedDocument != null) { // source generated files are never out-of-date: return (sourceGeneratedDocument, DocumentState.MatchesBuildOutput); } // The current document is source-generated therefore the corresponding one is not present in the base solution. if (currentDocument is SourceGeneratedDocument) { return (null, DocumentState.MatchesBuildOutput); } } break; } // Document compiled into the baseline DLL/PDB may have been added to the workspace // after the committed solution snapshot was taken. var document = committedDocument ?? currentDocument; if (document == null) { // Document has been deleted. return (null, DocumentState.None); } if (!document.DocumentState.SupportsEditAndContinue()) { return (null, DocumentState.DesignTimeOnly); } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var sourceTextVersion = (committedDocument == null) ? await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false) : default; // run file IO on a background thread: var (matchingSourceText, pdbHasDocument) = await Task.Run(() => { var compilationOutputs = _debuggingSession.GetCompilationOutputs(document.Project); using var debugInfoReaderProvider = GetMethodDebugInfoReader(compilationOutputs, document.Project.Name); if (debugInfoReaderProvider == null) { return (null, null); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); Contract.ThrowIfNull(document.FilePath); return TryGetPdbMatchingSourceText(debugInfoReader, document.FilePath, sourceText.Encoding); }, cancellationToken).ConfigureAwait(false); lock (_guard) { // only listed document states can be changed: if (_documentState.TryGetValue(documentId, out documentState) && documentState != DocumentState.OutOfSync && documentState != DocumentState.Indeterminate) { return (document, documentState); } DocumentState newState; Document? matchingDocument; if (pdbHasDocument == null) { // Unable to determine due to error reading the PDB or the source file. return (document, DocumentState.Indeterminate); } if (pdbHasDocument == false) { // Source file is not listed in the PDB. // It could either be a newly added document or a design-time-only document (e.g. WPF .g.i.cs files). // We can't distinguish between newly added document and newly added design-time-only document. matchingDocument = null; newState = (committedDocument != null) ? DocumentState.DesignTimeOnly : DocumentState.MatchesBuildOutput; } else { // Document exists in the PDB but not in the committed solution. // Add the document to the committed solution with its current (possibly out-of-sync) text. if (committedDocument == null) { _solution = _solution.AddDocument(DocumentInfo.Create( documentId, name: document.Name, folders: document.Folders, sourceCodeKind: document.SourceCodeKind, loader: TextLoader.From(TextAndVersion.Create(sourceText, sourceTextVersion, document.Name)), filePath: document.FilePath, isGenerated: document.State.Attributes.IsGenerated, designTimeOnly: document.State.Attributes.DesignTimeOnly, documentServiceProvider: document.State.Services)); } if (matchingSourceText != null) { if (committedDocument != null && sourceText.ContentEquals(matchingSourceText)) { matchingDocument = document; } else { _solution = _solution.WithDocumentText(documentId, matchingSourceText, PreservationMode.PreserveValue); matchingDocument = _solution.GetDocument(documentId); } newState = DocumentState.MatchesBuildOutput; } else { matchingDocument = null; newState = DocumentState.OutOfSync; } } _documentState[documentId] = newState; return (matchingDocument, newState); } } internal static async Task<IEnumerable<KeyValuePair<DocumentId, DocumentState>>> GetMatchingDocumentsAsync( IEnumerable<(Project, IEnumerable<CodeAnalysis.DocumentState>)> documentsByProject, Func<Project, CompilationOutputs> compilationOutputsProvider, CancellationToken cancellationToken) { var projectTasks = documentsByProject.Select(async projectDocumentStates => { cancellationToken.ThrowIfCancellationRequested(); var (project, documentStates) = projectDocumentStates; // Skip projects that do not support Roslyn EnC (e.g. F#, etc). // Source files of these do not even need to be captured in the solution snapshot. if (!project.SupportsEditAndContinue()) { return Array.Empty<DocumentId?>(); } using var debugInfoReaderProvider = GetMethodDebugInfoReader(compilationOutputsProvider(project), project.Name); if (debugInfoReaderProvider == null) { return Array.Empty<DocumentId?>(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); var documentTasks = documentStates.Select(async documentState => { cancellationToken.ThrowIfCancellationRequested(); if (documentState.SupportsEditAndContinue()) { var sourceFilePath = documentState.FilePath; Contract.ThrowIfNull(sourceFilePath); // Hydrate the solution snapshot with the content of the file. // It's important to do this before we start watching for changes so that we have a baseline we can compare future snapshots to. var sourceText = await documentState.GetTextAsync(cancellationToken).ConfigureAwait(false); // TODO: https://github.com/dotnet/roslyn/issues/51993 // avoid rereading the file in common case - the workspace should create source texts with the right checksum algorithm and encoding var (source, hasDocument) = TryGetPdbMatchingSourceText(debugInfoReader, sourceFilePath, sourceText.Encoding); if (source != null) { return documentState.Id; } } return null; }); return await Task.WhenAll(documentTasks).ConfigureAwait(false); }); var documentIdArrays = await Task.WhenAll(projectTasks).ConfigureAwait(false); return documentIdArrays.SelectMany(ids => ids.WhereNotNull()).Select(id => KeyValuePairUtil.Create(id, DocumentState.MatchesBuildOutput)); } private static DebugInformationReaderProvider? GetMethodDebugInfoReader(CompilationOutputs compilationOutputs, string projectName) { DebugInformationReaderProvider? debugInfoReaderProvider; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { EditAndContinueWorkspaceService.Log.Write("Source file of project '{0}' doesn't match output PDB: PDB '{1}' not found", projectName, compilationOutputs.PdbDisplayPath); } return debugInfoReaderProvider; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Source file of project '{0}' doesn't match output PDB: error opening PDB '{1}': {2}", projectName, compilationOutputs.PdbDisplayPath, e.Message); return null; } } public void CommitSolution(Solution solution) { lock (_guard) { _solution = solution; } } private static (SourceText? Source, bool? HasDocument) TryGetPdbMatchingSourceText(EditAndContinueMethodDebugInfoReader debugInfoReader, string sourceFilePath, Encoding? encoding) { var hasDocument = TryReadSourceFileChecksumFromPdb(debugInfoReader, sourceFilePath, out var symChecksum, out var algorithm); if (hasDocument != true) { return (Source: null, hasDocument); } try { using var fileStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); // We must use the encoding of the document as determined by the IDE (the editor). // This might differ from the encoding that the compiler chooses, so if we just relied on the compiler we // might end up updating the committed solution with a document that has a different encoding than // the one that's in the workspace, resulting in false document changes when we compare the two. var sourceText = SourceText.From(fileStream, encoding, checksumAlgorithm: algorithm); var fileChecksum = sourceText.GetChecksum(); if (fileChecksum.SequenceEqual(symChecksum)) { return (sourceText, hasDocument); } EditAndContinueWorkspaceService.Log.Write("Checksum differs for source file '{0}'", sourceFilePath); return (Source: null, hasDocument); } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Error calculating checksum for source file '{0}': '{1}'", sourceFilePath, e.Message); return (Source: null, HasDocument: null); } } /// <summary> /// Returns true if the PDB contains a document record for given <paramref name="sourceFilePath"/>, /// in which case <paramref name="checksum"/> and <paramref name="algorithm"/> contain its checksum. /// False if the document is not found in the PDB. /// Null if it can't be determined because the PDB is not available or an error occurred while reading the PDB. /// </summary> private static bool? TryReadSourceFileChecksumFromPdb(EditAndContinueMethodDebugInfoReader debugInfoReader, string sourceFilePath, out ImmutableArray<byte> checksum, out SourceHashAlgorithm algorithm) { checksum = default; algorithm = default; try { if (!debugInfoReader.TryGetDocumentChecksum(sourceFilePath, out checksum, out var algorithmId)) { EditAndContinueWorkspaceService.Log.Write("Source '{0}' doesn't match output PDB: no document", sourceFilePath); return false; } algorithm = SourceHashAlgorithms.GetSourceHashAlgorithm(algorithmId); if (algorithm == SourceHashAlgorithm.None) { // This can only happen if the PDB was post-processed by a misbehaving tool. EditAndContinueWorkspaceService.Log.Write("Source '{0}' doesn't match PDB: unknown checksum alg", sourceFilePath); } return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Source '{0}' doesn't match output PDB: error reading symbols: {1}", sourceFilePath, e.Message); } 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Encapsulates access to the last committed solution. /// We don't want to expose the solution directly since access to documents must be gated by out-of-sync checks. /// </summary> internal sealed class CommittedSolution { private readonly DebuggingSession _debuggingSession; private Solution _solution; internal enum DocumentState { None = 0, /// <summary> /// The current document content does not match the content the module was compiled with. /// This document state may change to <see cref="MatchesBuildOutput"/> or <see cref="DesignTimeOnly"/>. /// </summary> OutOfSync = 1, /// <summary> /// It hasn't been possible to determine whether the current document content does matches the content /// the module was compiled with due to error while reading the PDB or the source file. /// This document state may change to <see cref="MatchesBuildOutput"/> or <see cref="DesignTimeOnly"/>. /// </summary> Indeterminate = 2, /// <summary> /// The document is not compiled into the module. It's only included in the project /// to support design-time features such as completion, etc. /// This is a final state. Once a document is in this state it won't switch to a different one. /// </summary> DesignTimeOnly = 3, /// <summary> /// The current document content matches the content the built module was compiled with. /// This is a final state. Once a document is in this state it won't switch to a different one. /// </summary> MatchesBuildOutput = 4 } /// <summary> /// Implements workaround for https://github.com/dotnet/project-system/issues/5457. /// /// When debugging is started we capture the current solution snapshot. /// The documents in this snapshot might not match exactly to those that the compiler used to build the module /// that's currently loaded into the debuggee. This is because there is no reliable synchronization between /// the (design-time) build and Roslyn workspace. Although Roslyn uses file-watchers to watch for changes in /// the files on disk, the file-changed events raised by the build might arrive to Roslyn after the debugger /// has attached to the debuggee and EnC service captured the solution. /// /// Ideally, the Project System would notify Roslyn at the end of each build what the content of the source /// files generated by various targets is. Roslyn would then apply these changes to the workspace and /// the EnC service would capture a solution snapshot that includes these changes. /// /// Since this notification is currently not available we check the current content of source files against /// the corresponding checksums stored in the PDB. Documents for which we have not observed source file content /// that maches the PDB checksum are considered <see cref="DocumentState.OutOfSync"/>. /// /// Some documents in the workspace are added for design-time-only purposes and are not part of the compilation /// from which the assembly is built. These documents won't have a record in the PDB and will be tracked as /// <see cref="DocumentState.DesignTimeOnly"/>. /// /// A document state can only change from <see cref="DocumentState.OutOfSync"/> to <see cref="DocumentState.MatchesBuildOutput"/>. /// Once a document state is <see cref="DocumentState.MatchesBuildOutput"/> or <see cref="DocumentState.DesignTimeOnly"/> /// it will never change. /// </summary> private readonly Dictionary<DocumentId, DocumentState> _documentState; private readonly object _guard = new(); public CommittedSolution(DebuggingSession debuggingSession, Solution solution, IEnumerable<KeyValuePair<DocumentId, DocumentState>> initialDocumentStates) { _solution = solution; _debuggingSession = debuggingSession; _documentState = new Dictionary<DocumentId, DocumentState>(); _documentState.AddRange(initialDocumentStates); } // test only internal void Test_SetDocumentState(DocumentId documentId, DocumentState state) { lock (_guard) { _documentState[documentId] = state; } } // test only internal ImmutableArray<(DocumentId id, DocumentState state)> Test_GetDocumentStates() { lock (_guard) { return _documentState.SelectAsArray(e => (e.Key, e.Value)); } } public bool HasNoChanges(Solution solution) => _solution == solution; public Project? GetProject(ProjectId id) => _solution.GetProject(id); public Project GetRequiredProject(ProjectId id) => _solution.GetRequiredProject(id); public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string path) => _solution.GetDocumentIdsWithFilePath(path); public bool ContainsDocument(DocumentId documentId) => _solution.ContainsDocument(documentId); /// <summary> /// Captures the content of a file that is about to be overwritten by saving an open document, /// if the document is currently out-of-sync and the content of the file matches the PDB. /// If we didn't capture the content before the save we might never be able to find a document /// snapshot that matches the PDB. /// </summary> public Task OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken) => GetDocumentAndStateAsync(document.Id, document, cancellationToken, reloadOutOfSyncDocument: true); /// <summary> /// Returns a document snapshot for given <see cref="Document"/> whose content exactly matches /// the source file used to compile the binary currently loaded in the debuggee. Returns null /// if it fails to find a document snapshot whose content hash maches the one recorded in the PDB. /// /// The result is cached and the next lookup uses the cached value, including failures unless <paramref name="reloadOutOfSyncDocument"/> is true. /// </summary> public async Task<(Document? Document, DocumentState State)> GetDocumentAndStateAsync(DocumentId documentId, Document? currentDocument, CancellationToken cancellationToken, bool reloadOutOfSyncDocument = false) { Contract.ThrowIfFalse(currentDocument == null || documentId == currentDocument.Id); Solution solution; var documentState = DocumentState.None; lock (_guard) { solution = _solution; _documentState.TryGetValue(documentId, out documentState); } var committedDocument = solution.GetDocument(documentId); switch (documentState) { case DocumentState.MatchesBuildOutput: // Note: committedDocument is null if we previously validated that a document that is not in // the committed solution is also not in the PDB. This means the document has been added during debugging. return (committedDocument, documentState); case DocumentState.DesignTimeOnly: return (null, documentState); case DocumentState.OutOfSync: if (reloadOutOfSyncDocument) { break; } return (null, documentState); case DocumentState.Indeterminate: // Previous attempt resulted in a read error. Try again. break; case DocumentState.None: // Have not seen the document before, the document is not in the solution, or the document is source generated. if (committedDocument == null) { var sourceGeneratedDocument = await solution.GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (sourceGeneratedDocument != null) { // source generated files are never out-of-date: return (sourceGeneratedDocument, DocumentState.MatchesBuildOutput); } // The current document is source-generated therefore the corresponding one is not present in the base solution. if (currentDocument is SourceGeneratedDocument) { return (null, DocumentState.MatchesBuildOutput); } } break; } // Document compiled into the baseline DLL/PDB may have been added to the workspace // after the committed solution snapshot was taken. var document = committedDocument ?? currentDocument; if (document == null) { // Document has been deleted. return (null, DocumentState.None); } if (!document.DocumentState.SupportsEditAndContinue()) { return (null, DocumentState.DesignTimeOnly); } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var sourceTextVersion = (committedDocument == null) ? await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false) : default; // run file IO on a background thread: var (matchingSourceText, pdbHasDocument) = await Task.Run(() => { var compilationOutputs = _debuggingSession.GetCompilationOutputs(document.Project); using var debugInfoReaderProvider = GetMethodDebugInfoReader(compilationOutputs, document.Project.Name); if (debugInfoReaderProvider == null) { return (null, null); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); Contract.ThrowIfNull(document.FilePath); return TryGetPdbMatchingSourceText(debugInfoReader, document.FilePath, sourceText.Encoding); }, cancellationToken).ConfigureAwait(false); lock (_guard) { // only listed document states can be changed: if (_documentState.TryGetValue(documentId, out documentState) && documentState != DocumentState.OutOfSync && documentState != DocumentState.Indeterminate) { return (document, documentState); } DocumentState newState; Document? matchingDocument; if (pdbHasDocument == null) { // Unable to determine due to error reading the PDB or the source file. return (document, DocumentState.Indeterminate); } if (pdbHasDocument == false) { // Source file is not listed in the PDB. // It could either be a newly added document or a design-time-only document (e.g. WPF .g.i.cs files). // We can't distinguish between newly added document and newly added design-time-only document. matchingDocument = null; newState = (committedDocument != null) ? DocumentState.DesignTimeOnly : DocumentState.MatchesBuildOutput; } else { // Document exists in the PDB but not in the committed solution. // Add the document to the committed solution with its current (possibly out-of-sync) text. if (committedDocument == null) { _solution = _solution.AddDocument(DocumentInfo.Create( documentId, name: document.Name, folders: document.Folders, sourceCodeKind: document.SourceCodeKind, loader: TextLoader.From(TextAndVersion.Create(sourceText, sourceTextVersion, document.Name)), filePath: document.FilePath, isGenerated: document.State.Attributes.IsGenerated, designTimeOnly: document.State.Attributes.DesignTimeOnly, documentServiceProvider: document.State.Services)); } if (matchingSourceText != null) { if (committedDocument != null && sourceText.ContentEquals(matchingSourceText)) { matchingDocument = document; } else { _solution = _solution.WithDocumentText(documentId, matchingSourceText, PreservationMode.PreserveValue); matchingDocument = _solution.GetDocument(documentId); } newState = DocumentState.MatchesBuildOutput; } else { matchingDocument = null; newState = DocumentState.OutOfSync; } } _documentState[documentId] = newState; return (matchingDocument, newState); } } internal static async Task<IEnumerable<KeyValuePair<DocumentId, DocumentState>>> GetMatchingDocumentsAsync( IEnumerable<(Project, IEnumerable<CodeAnalysis.DocumentState>)> documentsByProject, Func<Project, CompilationOutputs> compilationOutputsProvider, CancellationToken cancellationToken) { var projectTasks = documentsByProject.Select(async projectDocumentStates => { cancellationToken.ThrowIfCancellationRequested(); var (project, documentStates) = projectDocumentStates; // Skip projects that do not support Roslyn EnC (e.g. F#, etc). // Source files of these do not even need to be captured in the solution snapshot. if (!project.SupportsEditAndContinue()) { return Array.Empty<DocumentId?>(); } using var debugInfoReaderProvider = GetMethodDebugInfoReader(compilationOutputsProvider(project), project.Name); if (debugInfoReaderProvider == null) { return Array.Empty<DocumentId?>(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); var documentTasks = documentStates.Select(async documentState => { cancellationToken.ThrowIfCancellationRequested(); if (documentState.SupportsEditAndContinue()) { var sourceFilePath = documentState.FilePath; Contract.ThrowIfNull(sourceFilePath); // Hydrate the solution snapshot with the content of the file. // It's important to do this before we start watching for changes so that we have a baseline we can compare future snapshots to. var sourceText = await documentState.GetTextAsync(cancellationToken).ConfigureAwait(false); // TODO: https://github.com/dotnet/roslyn/issues/51993 // avoid rereading the file in common case - the workspace should create source texts with the right checksum algorithm and encoding var (source, hasDocument) = TryGetPdbMatchingSourceText(debugInfoReader, sourceFilePath, sourceText.Encoding); if (source != null) { return documentState.Id; } } return null; }); return await Task.WhenAll(documentTasks).ConfigureAwait(false); }); var documentIdArrays = await Task.WhenAll(projectTasks).ConfigureAwait(false); return documentIdArrays.SelectMany(ids => ids.WhereNotNull()).Select(id => KeyValuePairUtil.Create(id, DocumentState.MatchesBuildOutput)); } private static DebugInformationReaderProvider? GetMethodDebugInfoReader(CompilationOutputs compilationOutputs, string projectName) { DebugInformationReaderProvider? debugInfoReaderProvider; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { EditAndContinueWorkspaceService.Log.Write("Source file of project '{0}' doesn't match output PDB: PDB '{1}' not found", projectName, compilationOutputs.PdbDisplayPath); } return debugInfoReaderProvider; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Source file of project '{0}' doesn't match output PDB: error opening PDB '{1}': {2}", projectName, compilationOutputs.PdbDisplayPath, e.Message); return null; } } public void CommitSolution(Solution solution) { lock (_guard) { _solution = solution; } } private static (SourceText? Source, bool? HasDocument) TryGetPdbMatchingSourceText(EditAndContinueMethodDebugInfoReader debugInfoReader, string sourceFilePath, Encoding? encoding) { var hasDocument = TryReadSourceFileChecksumFromPdb(debugInfoReader, sourceFilePath, out var symChecksum, out var algorithm); if (hasDocument != true) { return (Source: null, hasDocument); } try { using var fileStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); // We must use the encoding of the document as determined by the IDE (the editor). // This might differ from the encoding that the compiler chooses, so if we just relied on the compiler we // might end up updating the committed solution with a document that has a different encoding than // the one that's in the workspace, resulting in false document changes when we compare the two. var sourceText = SourceText.From(fileStream, encoding, checksumAlgorithm: algorithm); var fileChecksum = sourceText.GetChecksum(); if (fileChecksum.SequenceEqual(symChecksum)) { return (sourceText, hasDocument); } EditAndContinueWorkspaceService.Log.Write("Checksum differs for source file '{0}'", sourceFilePath); return (Source: null, hasDocument); } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Error calculating checksum for source file '{0}': '{1}'", sourceFilePath, e.Message); return (Source: null, HasDocument: null); } } /// <summary> /// Returns true if the PDB contains a document record for given <paramref name="sourceFilePath"/>, /// in which case <paramref name="checksum"/> and <paramref name="algorithm"/> contain its checksum. /// False if the document is not found in the PDB. /// Null if it can't be determined because the PDB is not available or an error occurred while reading the PDB. /// </summary> private static bool? TryReadSourceFileChecksumFromPdb(EditAndContinueMethodDebugInfoReader debugInfoReader, string sourceFilePath, out ImmutableArray<byte> checksum, out SourceHashAlgorithm algorithm) { checksum = default; algorithm = default; try { if (!debugInfoReader.TryGetDocumentChecksum(sourceFilePath, out checksum, out var algorithmId)) { EditAndContinueWorkspaceService.Log.Write("Source '{0}' doesn't match output PDB: no document", sourceFilePath); return false; } algorithm = SourceHashAlgorithms.GetSourceHashAlgorithm(algorithmId); if (algorithm == SourceHashAlgorithm.None) { // This can only happen if the PDB was post-processed by a misbehaving tool. EditAndContinueWorkspaceService.Log.Write("Source '{0}' doesn't match PDB: unknown checksum alg", sourceFilePath); } return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Source '{0}' doesn't match output PDB: error reading symbols: {1}", sourceFilePath, e.Message); } return null; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/Completion/Providers/AbstractObjectInitializerCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractObjectInitializerCompletionProvider : LSPCompletionProvider { protected abstract Tuple<ITypeSymbol, Location> GetInitializedType(Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken); protected abstract HashSet<string> GetInitializedMembers(SyntaxTree tree, int position, CancellationToken cancellationToken); protected abstract string EscapeIdentifier(ISymbol symbol); public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); if (!(GetInitializedType(document, semanticModel, position, cancellationToken) is var (type, initializerLocation))) { return; } if (type is ITypeParameterSymbol typeParameterSymbol) { type = typeParameterSymbol.GetNamedTypeSymbolConstraint(); } if (type is not INamedTypeSymbol initializedType) { return; } if (await IsExclusiveAsync(document, position, cancellationToken).ConfigureAwait(false)) { context.IsExclusive = true; } var enclosing = semanticModel.GetEnclosingNamedType(position, cancellationToken); // Find the members that can be initialized. If we have a NamedTypeSymbol, also get the overridden members. IEnumerable<ISymbol> members = semanticModel.LookupSymbols(position, initializedType); members = members.Where(m => IsInitializable(m, enclosing) && m.CanBeReferencedByName && IsLegalFieldOrProperty(m) && !m.IsImplicitlyDeclared); // Filter out those members that have already been typed var alreadyTypedMembers = GetInitializedMembers(semanticModel.SyntaxTree, position, cancellationToken); var uninitializedMembers = members.Where(m => !alreadyTypedMembers.Contains(m.Name)); uninitializedMembers = uninitializedMembers.Where(m => m.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)); foreach (var uninitializedMember in uninitializedMembers) { context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: EscapeIdentifier(uninitializedMember), displayTextSuffix: "", insertionText: null, symbols: ImmutableArray.Create(uninitializedMember), contextPosition: initializerLocation.SourceSpan.Start, rules: s_rules)); } } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); protected abstract Task<bool> IsExclusiveAsync(Document document, int position, CancellationToken cancellationToken); private static bool IsLegalFieldOrProperty(ISymbol symbol) { return symbol.IsWriteableFieldOrProperty() || symbol.ContainingType.IsAnonymousType || CanSupportObjectInitializer(symbol); } private static readonly CompletionItemRules s_rules = CompletionItemRules.Create(enterKeyRule: EnterKeyRule.Never); protected virtual bool IsInitializable(ISymbol member, INamedTypeSymbol containingType) { return !member.IsStatic && member.MatchesKind(SymbolKind.Field, SymbolKind.Property) && member.IsAccessibleWithin(containingType); } private static bool CanSupportObjectInitializer(ISymbol symbol) { Debug.Assert(!symbol.IsWriteableFieldOrProperty(), "Assertion failed - expected writable field/property check before calling this method."); if (symbol is IFieldSymbol fieldSymbol) { return !fieldSymbol.Type.IsStructType(); } else if (symbol is IPropertySymbol propertySymbol) { return !propertySymbol.Type.IsStructType(); } 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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractObjectInitializerCompletionProvider : LSPCompletionProvider { protected abstract Tuple<ITypeSymbol, Location> GetInitializedType(Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken); protected abstract HashSet<string> GetInitializedMembers(SyntaxTree tree, int position, CancellationToken cancellationToken); protected abstract string EscapeIdentifier(ISymbol symbol); public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); if (!(GetInitializedType(document, semanticModel, position, cancellationToken) is var (type, initializerLocation))) { return; } if (type is ITypeParameterSymbol typeParameterSymbol) { type = typeParameterSymbol.GetNamedTypeSymbolConstraint(); } if (type is not INamedTypeSymbol initializedType) { return; } if (await IsExclusiveAsync(document, position, cancellationToken).ConfigureAwait(false)) { context.IsExclusive = true; } var enclosing = semanticModel.GetEnclosingNamedType(position, cancellationToken); // Find the members that can be initialized. If we have a NamedTypeSymbol, also get the overridden members. IEnumerable<ISymbol> members = semanticModel.LookupSymbols(position, initializedType); members = members.Where(m => IsInitializable(m, enclosing) && m.CanBeReferencedByName && IsLegalFieldOrProperty(m) && !m.IsImplicitlyDeclared); // Filter out those members that have already been typed var alreadyTypedMembers = GetInitializedMembers(semanticModel.SyntaxTree, position, cancellationToken); var uninitializedMembers = members.Where(m => !alreadyTypedMembers.Contains(m.Name)); uninitializedMembers = uninitializedMembers.Where(m => m.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)); foreach (var uninitializedMember in uninitializedMembers) { context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: EscapeIdentifier(uninitializedMember), displayTextSuffix: "", insertionText: null, symbols: ImmutableArray.Create(uninitializedMember), contextPosition: initializerLocation.SourceSpan.Start, rules: s_rules)); } } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); protected abstract Task<bool> IsExclusiveAsync(Document document, int position, CancellationToken cancellationToken); private static bool IsLegalFieldOrProperty(ISymbol symbol) { return symbol.IsWriteableFieldOrProperty() || symbol.ContainingType.IsAnonymousType || CanSupportObjectInitializer(symbol); } private static readonly CompletionItemRules s_rules = CompletionItemRules.Create(enterKeyRule: EnterKeyRule.Never); protected virtual bool IsInitializable(ISymbol member, INamedTypeSymbol containingType) { return !member.IsStatic && member.MatchesKind(SymbolKind.Field, SymbolKind.Property) && member.IsAccessibleWithin(containingType); } private static bool CanSupportObjectInitializer(ISymbol symbol) { Debug.Assert(!symbol.IsWriteableFieldOrProperty(), "Assertion failed - expected writable field/property check before calling this method."); if (symbol is IFieldSymbol fieldSymbol) { return !fieldSymbol.Type.IsStructType(); } else if (symbol is IPropertySymbol propertySymbol) { return !propertySymbol.Type.IsStructType(); } throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/OperatorKeywordRecommender.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.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Operator" keyword in member declaration contexts ''' </summary> Friend Class OperatorKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim modifiers = context.ModifierCollectionFacts If context.SyntaxTree.IsDeclarationContextWithinTypeBlocks(context.Position, context.TargetToken, True, cancellationToken, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) AndAlso modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Operator) Then If modifiers.NarrowingOrWideningKeyword.Kind <> SyntaxKind.None Then Return ImmutableArray.Create(New RecommendedKeyword("Operator CType", VBFeaturesResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type)) Else Return ImmutableArray.Create(New RecommendedKeyword("Operator", VBFeaturesResources.Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure)) 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.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Operator" keyword in member declaration contexts ''' </summary> Friend Class OperatorKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim modifiers = context.ModifierCollectionFacts If context.SyntaxTree.IsDeclarationContextWithinTypeBlocks(context.Position, context.TargetToken, True, cancellationToken, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) AndAlso modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Operator) Then If modifiers.NarrowingOrWideningKeyword.Kind <> SyntaxKind.None Then Return ImmutableArray.Create(New RecommendedKeyword("Operator CType", VBFeaturesResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type)) Else Return ImmutableArray.Create(New RecommendedKeyword("Operator", VBFeaturesResources.Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure)) End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Indentation; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { public class SmartIndenterEnterOnTokenTests : CSharpFormatterTestsBase { public SmartIndenterEnterOnTokenTests(ITestOutputHelper output) : base(output) { } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBody1() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor1() { var code = @"class A { #region T #endregion } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor2() { var code = @"class A { #line 1 #lien 2 } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor3() { var code = @"#region stuff #endregion "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 2, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Comments() { var code = @"using System; class Class { // Comments // Comments "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task UsingDirective() { var code = @"using System; using System.Linq; "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'u', indentationLine: 1, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterTopOfFileComment() { var code = @"// comment class "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 2, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task DottedName() { var code = @"using System. Collection; "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 1, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Namespace() { var code = @"using System; namespace NS { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceDottedName() { var code = @"using System; namespace NS. NS2 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceBody() { var code = @"using System; namespace NS { class "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'c', indentationLine: 4, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceCloseBrace() { var code = @"using System; namespace NS { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 4, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Class() { var code = @"using System; namespace NS { class Class { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 5, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ClassBody() { var code = @"using System; namespace NS { class Class { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 6, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ClassCloseBrace() { var code = @"using System; namespace NS { class Class { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 6, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Method() { var code = @"using System; namespace NS { class Class { void Method() { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 7, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBody() { var code = @"using System; namespace NS { class Class { void Method() { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 8, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodCloseBrace() { var code = @"using System; namespace NS { class Class { void Method() { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 8, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Statement() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10; int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 9, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodCall() { var code = @"class c { void Method() { M( a: 1, b: 1); } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Switch() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 9, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchBody() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'c', indentationLine: 10, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchCase() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 11, expectedIndentation: 20); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchCaseBlock() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 11, expectedIndentation: 20); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Block() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 12, expectedIndentation: 24); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MultilineStatement1() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 1 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 9, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MultilineStatement2() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 20 + 30 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 10, expectedIndentation: 20); } // Bug number 902477 [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Comments2() { var code = @"class Class { void Method() { if (true) // Test int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 5, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterCompletedBlock() { var code = @"class Program { static void Main(string[] args) { foreach(var a in x) {} int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 5, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterTopLevelAttribute() { var code = @"class Program { [Attr] [ } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '[', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537802")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task EmbededStatement() { var code = @"class Program { static void Main(string[] args) { if (true) Console.WriteLine(1); int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 6, expectedIndentation: 8); } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBraces1() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBraces2() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 4, expectedIndentation: 4); } [WorkItem(537795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537795")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Property1() { var code = @"class C { string Name { get; set; } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 6, expectedIndentation: 4); } [WorkItem(537563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537563")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Class1() { var code = @"class C { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 2, expectedIndentation: 0); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer1() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer2() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 5, expectedIndentation: 4); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer3() { var code = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression2() { var code = @"class C { void Method() { var a = from c in b where } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'w', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression3() { var code = @"class C { void Method() { var a = from c in b where select } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'w', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression4() { var code = @"class C { void Method() { var a = from c in b where c > 10 select } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 's', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [WorkItem(853748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853748")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer() { var code = @"class C { void Method() { var l = new int[] { } } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(939305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939305")] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayExpression() { var code = @"class C { void M(object[] q) { M( q: new object[] { }); } } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 6, expectedIndentation: 14); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task CollectionExpression() { var code = @"class C { void M(List<int> e) { M( new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 6, expectedIndentation: 12); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ObjectInitializer() { var code = @"class C { void M(What dd) { M( new What { d = 3, dd = "" }); } } class What { public int d; public string dd; }"; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 6, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor() { var code = @" #line 1 """"Bar""""class Goo : [|IComparable|]#line default#line hidden"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 1, expectedIndentation: 0); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Implicit() { var code = @"class X { int[] a = { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_ImplicitNew() { var code = @"class X { int[] a = new[] { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Explicit() { var code = @"class X { int[] a = new int[] { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Collection() { var code = @"using System.Collections.Generic; class X { private List<int> a = new List<int>() { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 4, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_ObjectInitializers() { var code = @"class C { private What sdfsd = new What { d = 3, } } class What { public int d; public string dd; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_1() { var code = @"class Program { static void Main(string[] args) { var s = $@"" {Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment {Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number} ""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_4() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here ""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task OutsideInterpolationString() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here"" ; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_1() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program .number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 6, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ }""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_4() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_5() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_6() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })) .Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_7() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine(((Func<int, int>)((int s) => { return number; })).Invoke(3)); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(1339, "https://github.com/dotnet/roslyn/issues/1339")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentAutoPropertyInitializerAsPartOfTheDeclaration() { var code = @"class Program { public int d { get; } = 3; static void Main(string[] args) { } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentPatternPropertyFirst() { var code = @" class C { void Main(object o) { var y = o is Point { } } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentPatternPropertySecond() { var code = @" class C { void Main(object o) { var y = o is Point { X is 13, } } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 8, expectedIndentation: 12); } [Trait(Traits.Feature, Traits.Features.SmartIndent)] [WpfTheory] [InlineData("x", "is < 7 and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is", "< 7 and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is <", "7 and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7", "and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and", "(>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (", ">= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>=", "3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3", "or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or", "> 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or >", "50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50", ") or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50)", "or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or", "not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not", "<= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not <=", "0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not <= 0", ";", 12)] public async Task IndentPatternsInLocalDeclarationCSharp9(string line1, string line2, int expectedIndentation) { var code = @$" class C {{ void M() {{ var x = 7; var y = {line1} {line2} }} }}"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation); } [Trait(Traits.Feature, Traits.Features.SmartIndent)] [WpfTheory] [InlineData("x", "is < 7 and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is", "< 7 and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is <", "7 and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7", "and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and", "(>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (", ">= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>=", "3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3", "or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or", "> 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or >", "50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50", ") or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50)", "or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or", "not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not", "<= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not <=", "0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not <= 0", ";", 8)] public async Task IndentPatternsInFieldDeclarationCSharp9(string line1, string line2, int expectedIndentation) { var code = @$" class C {{ static int x = 7; bool y = {line1} {line2} }}"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation); } [Trait(Traits.Feature, Traits.Features.SmartIndent)] [WpfTheory] [InlineData("<", "7 and (>= 3 or > 50) or not <= 0", 12)] [InlineData("< 7", "and (>= 3 or > 50) or not <= 0", 12)] [InlineData("< 7 and", "(>= 3 or > 50) or not <= 0", 12)] [InlineData("< 7 and (", ">= 3 or > 50) or not <= 0", 12)] [InlineData("< 7 and (>=", "3 or > 50) or not <= 0", 12)] [InlineData("< 7 and (>= 3", "or > 50) or not <= 0", 12)] [InlineData("< 7 and (>= 3 or", "> 50) or not <= 0", 12)] [InlineData("< 7 and (>= 3 or >", "50) or not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50", ") or not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50)", "or not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or", "not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or not", "<= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or not <=", "0", 12)] public async Task IndentPatternsInSwitchCSharp9(string line1, string line2, int expectedIndentation) { var code = @$" class C {{ void M() {{ var x = 7; var y = x switch {{ {line1} {line2} => true, _ => false }}; }} }}"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 9, expectedIndentation); } private static async Task AssertIndentUsingSmartTokenFormatterAsync( string code, char ch, int indentationLine, int? expectedIndentation) { await AssertIndentUsingSmartTokenFormatterAsync(code, ch, indentationLine, expectedIndentation, useTabs: false).ConfigureAwait(false); await AssertIndentUsingSmartTokenFormatterAsync(code.Replace(" ", "\t"), ch, indentationLine, expectedIndentation, useTabs: true).ConfigureAwait(false); } private static async Task AssertIndentUsingSmartTokenFormatterAsync( string code, char ch, int indentationLine, int? expectedIndentation, bool useTabs) { // create tree service using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax; var optionService = workspace.Services.GetRequiredService<IOptionService>(); Assert.True( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line.AsTextLine(), optionService, await document.GetOptionsAsync(), out _)); var actualIndentation = await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch); Assert.Equal(expectedIndentation.Value, actualIndentation); } private static async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( string code, int indentationLine, int? expectedIndentation, IndentStyle indentStyle = IndentStyle.Smart) { await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(code, indentationLine, expectedIndentation, useTabs: false, indentStyle).ConfigureAwait(false); await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(code.Replace(" ", "\t"), indentationLine, expectedIndentation, useTabs: true, indentStyle).ConfigureAwait(false); } private static async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( string code, int indentationLine, int? expectedIndentation, bool useTabs, IndentStyle indentStyle) { // create tree service using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(SmartIndent, LanguageNames.CSharp, indentStyle) .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax; var optionService = workspace.Services.GetRequiredService<IOptionService>(); Assert.False( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line.AsTextLine(), optionService, await document.GetOptionsAsync(), out _)); TestIndentation(workspace, indentationLine, expectedIndentation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Indentation; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { public class SmartIndenterEnterOnTokenTests : CSharpFormatterTestsBase { public SmartIndenterEnterOnTokenTests(ITestOutputHelper output) : base(output) { } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBody1() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor1() { var code = @"class A { #region T #endregion } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor2() { var code = @"class A { #line 1 #lien 2 } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor3() { var code = @"#region stuff #endregion "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 2, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Comments() { var code = @"using System; class Class { // Comments // Comments "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task UsingDirective() { var code = @"using System; using System.Linq; "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'u', indentationLine: 1, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterTopOfFileComment() { var code = @"// comment class "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 2, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task DottedName() { var code = @"using System. Collection; "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 1, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Namespace() { var code = @"using System; namespace NS { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceDottedName() { var code = @"using System; namespace NS. NS2 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceBody() { var code = @"using System; namespace NS { class "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'c', indentationLine: 4, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task NamespaceCloseBrace() { var code = @"using System; namespace NS { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 4, expectedIndentation: 0); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Class() { var code = @"using System; namespace NS { class Class { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 5, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ClassBody() { var code = @"using System; namespace NS { class Class { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 6, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ClassCloseBrace() { var code = @"using System; namespace NS { class Class { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 6, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Method() { var code = @"using System; namespace NS { class Class { void Method() { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 7, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBody() { var code = @"using System; namespace NS { class Class { void Method() { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 8, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodCloseBrace() { var code = @"using System; namespace NS { class Class { void Method() { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 8, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Statement() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10; int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 9, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodCall() { var code = @"class c { void Method() { M( a: 1, b: 1); } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Switch() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 9, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchBody() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'c', indentationLine: 10, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchCase() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 11, expectedIndentation: 20); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task SwitchCaseBlock() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 11, expectedIndentation: 20); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Block() { var code = @"using System; namespace NS { class Class { void Method() { switch (10) { case 10 : { int "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 12, expectedIndentation: 24); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MultilineStatement1() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 1 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 9, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MultilineStatement2() { var code = @"using System; namespace NS { class Class { void Method() { int i = 10 + 20 + 30 "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 10, expectedIndentation: 20); } // Bug number 902477 [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Comments2() { var code = @"class Class { void Method() { if (true) // Test int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 5, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterCompletedBlock() { var code = @"class Program { static void Main(string[] args) { foreach(var a in x) {} int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 5, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task AfterTopLevelAttribute() { var code = @"class Program { [Attr] [ } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '[', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537802")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task EmbededStatement() { var code = @"class Program { static void Main(string[] args) { if (true) Console.WriteLine(1); int } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'i', indentationLine: 6, expectedIndentation: 8); } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBraces1() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 3, expectedIndentation: 4); } [WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task MethodBraces2() { var code = @"class Class1 { void method() { } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 4, expectedIndentation: 4); } [WorkItem(537795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537795")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Property1() { var code = @"class C { string Name { get; set; } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 6, expectedIndentation: 4); } [WorkItem(537563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537563")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Class1() { var code = @"class C { } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 2, expectedIndentation: 0); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer1() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer2() { var code = @"class C { var a = new [] { 1, 2, 3 } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 5, expectedIndentation: 4); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer3() { var code = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression2() { var code = @"class C { void Method() { var a = from c in b where } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'w', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression3() { var code = @"class C { void Method() { var a = from c in b where select } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 'w', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task QueryExpression4() { var code = @"class C { void Method() { var a = from c in b where c > 10 select } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, 's', indentationLine: 5, expectedIndentation: 16); } [WpfFact] [WorkItem(853748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853748")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayInitializer() { var code = @"class C { void Method() { var l = new int[] { } } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '}', indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(939305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939305")] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ArrayExpression() { var code = @"class C { void M(object[] q) { M( q: new object[] { }); } } "; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 6, expectedIndentation: 14); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task CollectionExpression() { var code = @"class C { void M(List<int> e) { M( new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); } } "; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 6, expectedIndentation: 12); } [WpfFact] [WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task ObjectInitializer() { var code = @"class C { void M(What dd) { M( new What { d = 3, dd = "" }); } } class What { public int d; public string dd; }"; await AssertIndentUsingSmartTokenFormatterAsync( code, '{', indentationLine: 6, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task Preprocessor() { var code = @" #line 1 """"Bar""""class Goo : [|IComparable|]#line default#line hidden"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 1, expectedIndentation: 0); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Implicit() { var code = @"class X { int[] a = { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_ImplicitNew() { var code = @"class X { int[] a = new[] { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Explicit() { var code = @"class X { int[] a = new int[] { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_Collection() { var code = @"using System.Collections.Generic; class X { private List<int> a = new List<int>() { 1, }; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 4, expectedIndentation: 8); } [WpfFact] [WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInitializerWithTypeBody_ObjectInitializers() { var code = @"class C { private What sdfsd = new What { d = 3, } } class What { public int d; public string dd; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_1() { var code = @"class Program { static void Main(string[] args) { var s = $@"" {Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment {Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number} ""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationString_4() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here ""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 0); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task OutsideInterpolationString() { var code = @"class Program { static void Main(string[] args) { var s = $@""Comment{Program.number}Comment here"" ; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_1() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program.number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_2() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ Program .number}""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 6, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_3() { var code = @"class Program { static void Main(string[] args) { var s = $@""{ }""; } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_4() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_5() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_6() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })) .Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 12); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task InsideInterpolationSyntax_7() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}""); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement() { var code = @"class Program { static void Main(string[] args) { Console.WriteLine(((Func<int, int>)((int s) => { return number; })).Invoke(3)); } static int number; }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation: 8); } [WpfFact] [WorkItem(1339, "https://github.com/dotnet/roslyn/issues/1339")] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentAutoPropertyInitializerAsPartOfTheDeclaration() { var code = @"class Program { public int d { get; } = 3; static void Main(string[] args) { } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 3, expectedIndentation: 8); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentPatternPropertyFirst() { var code = @" class C { void Main(object o) { var y = o is Point { } } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation: 12); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartIndent)] public async Task IndentPatternPropertySecond() { var code = @" class C { void Main(object o) { var y = o is Point { X is 13, } } }"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 8, expectedIndentation: 12); } [Trait(Traits.Feature, Traits.Features.SmartIndent)] [WpfTheory] [InlineData("x", "is < 7 and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is", "< 7 and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is <", "7 and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7", "and (>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and", "(>= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (", ">= 3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>=", "3 or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3", "or > 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or", "> 50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or >", "50) or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50", ") or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50)", "or not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or", "not <= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not", "<= 0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not <=", "0;", 12)] [InlineData("x is < 7 and (>= 3 or > 50) or not <= 0", ";", 12)] public async Task IndentPatternsInLocalDeclarationCSharp9(string line1, string line2, int expectedIndentation) { var code = @$" class C {{ void M() {{ var x = 7; var y = {line1} {line2} }} }}"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 7, expectedIndentation); } [Trait(Traits.Feature, Traits.Features.SmartIndent)] [WpfTheory] [InlineData("x", "is < 7 and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is", "< 7 and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is <", "7 and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7", "and (>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and", "(>= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (", ">= 3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>=", "3 or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3", "or > 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or", "> 50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or >", "50) or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50", ") or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50)", "or not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or", "not <= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not", "<= 0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not <=", "0;", 8)] [InlineData("x is < 7 and (>= 3 or > 50) or not <= 0", ";", 8)] public async Task IndentPatternsInFieldDeclarationCSharp9(string line1, string line2, int expectedIndentation) { var code = @$" class C {{ static int x = 7; bool y = {line1} {line2} }}"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 5, expectedIndentation); } [Trait(Traits.Feature, Traits.Features.SmartIndent)] [WpfTheory] [InlineData("<", "7 and (>= 3 or > 50) or not <= 0", 12)] [InlineData("< 7", "and (>= 3 or > 50) or not <= 0", 12)] [InlineData("< 7 and", "(>= 3 or > 50) or not <= 0", 12)] [InlineData("< 7 and (", ">= 3 or > 50) or not <= 0", 12)] [InlineData("< 7 and (>=", "3 or > 50) or not <= 0", 12)] [InlineData("< 7 and (>= 3", "or > 50) or not <= 0", 12)] [InlineData("< 7 and (>= 3 or", "> 50) or not <= 0", 12)] [InlineData("< 7 and (>= 3 or >", "50) or not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50", ") or not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50)", "or not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or", "not <= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or not", "<= 0", 12)] [InlineData("< 7 and (>= 3 or > 50) or not <=", "0", 12)] public async Task IndentPatternsInSwitchCSharp9(string line1, string line2, int expectedIndentation) { var code = @$" class C {{ void M() {{ var x = 7; var y = x switch {{ {line1} {line2} => true, _ => false }}; }} }}"; await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( code, indentationLine: 9, expectedIndentation); } private static async Task AssertIndentUsingSmartTokenFormatterAsync( string code, char ch, int indentationLine, int? expectedIndentation) { await AssertIndentUsingSmartTokenFormatterAsync(code, ch, indentationLine, expectedIndentation, useTabs: false).ConfigureAwait(false); await AssertIndentUsingSmartTokenFormatterAsync(code.Replace(" ", "\t"), ch, indentationLine, expectedIndentation, useTabs: true).ConfigureAwait(false); } private static async Task AssertIndentUsingSmartTokenFormatterAsync( string code, char ch, int indentationLine, int? expectedIndentation, bool useTabs) { // create tree service using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax; var optionService = workspace.Services.GetRequiredService<IOptionService>(); Assert.True( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line.AsTextLine(), optionService, await document.GetOptionsAsync(), out _)); var actualIndentation = await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch); Assert.Equal(expectedIndentation.Value, actualIndentation); } private static async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( string code, int indentationLine, int? expectedIndentation, IndentStyle indentStyle = IndentStyle.Smart) { await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(code, indentationLine, expectedIndentation, useTabs: false, indentStyle).ConfigureAwait(false); await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(code.Replace(" ", "\t"), indentationLine, expectedIndentation, useTabs: true, indentStyle).ConfigureAwait(false); } private static async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( string code, int indentationLine, int? expectedIndentation, bool useTabs, IndentStyle indentStyle) { // create tree service using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(SmartIndent, LanguageNames.CSharp, indentStyle) .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); var hostdoc = workspace.Documents.First(); var buffer = hostdoc.GetTextBuffer(); var snapshot = buffer.CurrentSnapshot; var line = snapshot.GetLineFromLineNumber(indentationLine); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax; var optionService = workspace.Services.GetRequiredService<IOptionService>(); Assert.False( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), root, line.AsTextLine(), optionService, await document.GetOptionsAsync(), out _)); TestIndentation(workspace, indentationLine, expectedIndentation); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/VisualBasicTest/Recommendations/OnErrorStatements/ErrorKeywordRecommenderTests.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.UnitTests.Recommendations.OnErrorStatements Public Class ErrorKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorOptionsAfterOnTest() ' We can always exit a Sub/Function, so it should be there VerifyRecommendationsAreExactly(<MethodBody>On |</MethodBody>, "Error Resume Next", "Error GoTo") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Error") End Sub <Fact> <WorkItem(899057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899057")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInLambdaTest() Dim code = <File> Public Class Z Public Sub Main() Dim c = Sub() | End Sub End Class</File> VerifyRecommendationsContain(code, "Error") 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OnErrorStatements Public Class ErrorKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorOptionsAfterOnTest() ' We can always exit a Sub/Function, so it should be there VerifyRecommendationsAreExactly(<MethodBody>On |</MethodBody>, "Error Resume Next", "Error GoTo") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Error") End Sub <Fact> <WorkItem(899057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899057")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInLambdaTest() Dim code = <File> Public Class Z Public Sub Main() Dim c = Sub() | End Sub End Class</File> VerifyRecommendationsContain(code, "Error") End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/CSharp/Portable/CodeFixes/AddExplicitCast/AttributeArgumentFixer.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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddExplicitCast { internal sealed partial class CSharpAddExplicitCastCodeFixProvider { private class AttributeArgumentFixer : Fixer<AttributeArgumentSyntax, AttributeArgumentListSyntax, AttributeSyntax> { public AttributeArgumentFixer(CSharpAddExplicitCastCodeFixProvider provider) : base(provider) { } protected override ExpressionSyntax GetExpressionOfArgument(AttributeArgumentSyntax argument) => argument.Expression; protected override AttributeArgumentSyntax GenerateNewArgument(AttributeArgumentSyntax oldArgument, ITypeSymbol conversionType) => oldArgument.WithExpression(oldArgument.Expression.Cast(conversionType)); protected override AttributeArgumentListSyntax GenerateNewArgumentList(AttributeArgumentListSyntax oldArgumentList, ArrayBuilder<AttributeArgumentSyntax> newArguments) => oldArgumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); protected override SeparatedSyntaxList<AttributeArgumentSyntax> GetArgumentsOfArgumentList(AttributeArgumentListSyntax argumentList) => argumentList.Arguments; protected override SymbolInfo GetSpeculativeSymbolInfo(SemanticModel semanticModel, AttributeArgumentListSyntax newArgumentList) { var newAttribute = (AttributeSyntax)newArgumentList.Parent!; return semanticModel.GetSpeculativeSymbolInfo(newAttribute.SpanStart, newAttribute); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddExplicitCast { internal sealed partial class CSharpAddExplicitCastCodeFixProvider { private class AttributeArgumentFixer : Fixer<AttributeArgumentSyntax, AttributeArgumentListSyntax, AttributeSyntax> { public AttributeArgumentFixer(CSharpAddExplicitCastCodeFixProvider provider) : base(provider) { } protected override ExpressionSyntax GetExpressionOfArgument(AttributeArgumentSyntax argument) => argument.Expression; protected override AttributeArgumentSyntax GenerateNewArgument(AttributeArgumentSyntax oldArgument, ITypeSymbol conversionType) => oldArgument.WithExpression(oldArgument.Expression.Cast(conversionType)); protected override AttributeArgumentListSyntax GenerateNewArgumentList(AttributeArgumentListSyntax oldArgumentList, ArrayBuilder<AttributeArgumentSyntax> newArguments) => oldArgumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments)); protected override SeparatedSyntaxList<AttributeArgumentSyntax> GetArgumentsOfArgumentList(AttributeArgumentListSyntax argumentList) => argumentList.Arguments; protected override SymbolInfo GetSpeculativeSymbolInfo(SemanticModel semanticModel, AttributeArgumentListSyntax newArgumentList) { var newAttribute = (AttributeSyntax)newArgumentList.Parent!; return semanticModel.GetSpeculativeSymbolInfo(newAttribute.SpanStart, newAttribute); } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/Portable/Emit/SemanticEditKind.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.Emit { public enum SemanticEditKind { /// <summary> /// No change. /// </summary> None = 0, /// <summary> /// Symbol is updated. /// </summary> Update = 1, /// <summary> /// Symbol is inserted. /// </summary> Insert = 2, /// <summary> /// Symbol is deleted. /// </summary> Delete = 3, /// <summary> /// Existing symbol is replaced by its new version. /// </summary> Replace = 4 } }
// Licensed to the .NET Foundation under one or more 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.Emit { public enum SemanticEditKind { /// <summary> /// No change. /// </summary> None = 0, /// <summary> /// Symbol is updated. /// </summary> Update = 1, /// <summary> /// Symbol is inserted. /// </summary> Insert = 2, /// <summary> /// Symbol is deleted. /// </summary> Delete = 3, /// <summary> /// Existing symbol is replaced by its new version. /// </summary> Replace = 4 } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IncrementalParser.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.ObjectModel Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Public Class IncrementalParser Private ReadOnly _s As String = <![CDATA[ '----------------------- ' ' Copyright (c) ' '----------------------- #const BLAH = true Imports Roslyn.Compilers Imports Roslyn.Compilers.Common Imports Roslyn.Compilers.VisualBasic Public Module ParseExprSemantics Dim text = SourceText.From("") Dim tree As SyntaxTree = Nothing #const x = 1 ''' <summary> ''' This is just gibberish to test parser ''' </summary> ''' <param name="ITERS"> haha </param> ''' <remarks></remarks> Public Sub Run(ByVal ITERS As Long) Console.WriteLine() #if BLAH Console.WriteLine("==== Parsing file: " & "Sample_ExpressionSemantics.vb") Console.WriteLine("Iterations:" & ITERS) #end if Dim str = IO.File.ReadAllText("Sample_ExpressionSemantics.vb") Dim lineNumber = 28335 Dim root As SyntaxNode = Nothing dim s1 = sub () If True Then Console.WriteLine(1) : dim s2 = sub () If True Then Console.WriteLine(1) ::Console.WriteLine(1):: dim s3 = sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1) Dim sw = System.Diagnostics.Stopwatch.StartNew() For i As Integer = 0 To ITERS - 1 tree = SyntaxTree.Parse(text, Nothing) root = tree.Root Console.Write(".") Dim highWater As Integer = Math.Max(highWater, System.GC.GetTotalMemory(False)) Next Dim grouped = From node In root.GetNodesWhile(root.FullSpan, Function() True) Group By node.Kind Into Group, Count() Order By Count Descending Take 30 Console.WriteLine("Quick token cache-hits: {0} ({1:G2}%)", Stats.quickReturnedToken, 100.0 * Stats.quickReturnedToken / Stats.quickAttempts) End Sub End Module]]>.Value <Fact> Public Sub FakeEdits() Dim text As SourceText = SourceText.From(_s) Dim tree As SyntaxTree = Nothing Dim root As SyntaxNode = Nothing tree = VisualBasicSyntaxTree.ParseText(text) root = tree.GetRoot() Assert.Equal(False, root.ContainsDiagnostics) For i As Integer = 0 To text.Length - 11 Dim span = New TextSpan(i, 10) text = text.WithChanges(New TextChange(span, text.ToString(span))) tree = tree.WithChangedText(text) Dim prevRoot = root root = tree.GetRoot() Assert.True(prevRoot.IsEquivalentTo(root)) Next End Sub <Fact> Public Sub TypeAFile() Dim text As SourceText = SourceText.From("") Dim tree As SyntaxTree = Nothing tree = VisualBasicSyntaxTree.ParseText(text) Assert.Equal(False, tree.GetRoot().ContainsDiagnostics) For i As Integer = 0 To _s.Length - 1 ' add next character in file 's' to text Dim newText = text.WithChanges(New TextChange(New TextSpan(text.Length, 0), _s.Substring(i, 1))) Dim newTree = tree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) text = newText tree = newTree Next End Sub <Fact> Public Sub Preprocessor() Dim oldText = SourceText.From(_s) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' commenting out the #const Dim pos = _s.IndexOf("#const", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) ' removes ' from the '#const Dim newString = newText.ToString() pos = newString.IndexOf("'#const", StringComparison.Ordinal) Dim anotherText = newText.WithChanges(New TextChange(New TextSpan(pos, 1), "")) newTree = newTree.WithChangedText(anotherText) tmpTree = VisualBasicSyntaxTree.ParseText(anotherText) VerifyEquivalent(newTree, tmpTree) End Sub #Region "Regressions" <WorkItem(899264, "DevDiv/Personal")> <Fact> Public Sub IncParseWithEventsFollowingProperty() 'Unable to verify this using CDATA, since CDATA value only has Cr appended at end of each line, 'where as this bug is reproducible only with CrLf at the end of each line Dim code As String = "Public Class HasPublicMembersToConflictWith" & vbCrLf & "Public ConflictWithProp" & vbCrLf & "" & vbCrLf & "Public Property _ConflictWithBF() As String" & vbCrLf & " Get" & vbCrLf & " End Get" & vbCrLf & " Set(value As String)" & vbCrLf & " End Set" & vbCrLf & "End Property" & vbCrLf & "" & vbCrLf & "Public WithEvents ConflictWithBoth As Ob" ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "j", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899596, "DevDiv/Personal")> <Fact> Public Sub IncParseClassFollowingDocComments() Dim code As String = <![CDATA[Class VBQATestcase '''----------------------------------------------------------------------------- ''' <summary> '''Text ''' </summary> '''-----------------------------------------------------------------------------]]>.Value ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf & "Pub", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899918, "DevDiv/Personal")> <Fact> Public Sub IncParseDirInElse() Dim code As String = "Sub Sub1()" & vbCr & "If true Then" & vbCr & "goo("""")" & vbCr & "Else" & vbCr & vbCr & "#If Not ULTRAVIOLET Then" & vbCr ParseAndVerify(code, <errors> <error id="30012"/> <error id="30081"/> <error id="30026"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899938, "DevDiv/Personal")> <Fact> Public Sub IncParseNamespaceFollowingEvent() Dim code As String = "Class cls1" & vbCrLf & "Custom Event myevent As del" & vbCrLf & "End Event" & vbCrLf & "End Class" & vbCrLf & "Namespace r" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "e", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(900209, "DevDiv/Personal")> <Fact> Public Sub IncParseCaseElse() Dim code As String = (<![CDATA[ Sub main() Select Case 5 Case Else vvv = 6 Case Else vvv = 7 ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901386, "DevDiv/Personal")> <Fact> Public Sub IncParseExplicitOnGroupBy() Dim code As String = (<![CDATA[ Option Explicit On Sub goo() Dim q2 = From x In col let y = x Group x, y By]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901639, "DevDiv/Personal")> <Fact> Public Sub IncParseExprLambdaInSubContext() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParseExprLambdaInSubContext2() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then Else End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901645, "DevDiv/Personal")> <Fact> Public Sub IncParseExitFunction() Dim code As String = (<![CDATA[Function If strSwitches <> "" Then strCLine = strCLine & " " & strSwitches End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Exit ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901655, "DevDiv/Personal")> <Fact> Public Sub IncParseDateLiteral() IncParseAndVerify(New IncParseNode With { .oldText = "", .changeText = "#10/18/1969# hello 123", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParsePPElse() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#End If", .changeSpan = New TextSpan(code.IndexOf("Next roleName", StringComparison.Ordinal) + 15, 2), .changeType = ChangeType.Replace}) End Sub <Fact> Public Sub IncParsePPElse1() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName #End IF End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#If true " & vbCrLf, .changeSpan = New TextSpan(code.IndexOf("#Else", StringComparison.Ordinal), 0), .changeType = ChangeType.Replace}) End Sub <WorkItem(901669, "DevDiv/Personal")> <Fact> Public Sub ParseXmlTagWithExprHole() Dim code As String = (<![CDATA[e a=<%= b %>>]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "<", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901671, "DevDiv/Personal")> <Fact> Public Sub IncParseEndBeforeSubWithX() Dim code As String = (<![CDATA[Sub End Class X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901676, "DevDiv/Personal")> <Fact> Public Sub IncParseInterfaceFollByConstructs() Dim code As String = (<![CDATA[ Public Interface I2 End Interface Sub SEHIllegal501() Try Catch End Try Exit Sub End Sub X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901680, "DevDiv/Personal")> <Fact> Public Sub IncParseLCFunctionCompoundAsn() Dim code As String = (<![CDATA[Public Function goo() As String For i As Integer = 0 To 1 total += y(i) Next End Function]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "> _" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(902710, "DevDiv/Personal")> <Fact> Public Sub IncParseInsertFunctionBeforeEndClass() Dim code As String = (<![CDATA[End Class MustInherit Class C10 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Function" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903134, "DevDiv/Personal")> <Fact> Public Sub InsertSubBeforeCustomEvent() Dim code As String = (<![CDATA[ Custom Event e As del AddHandler(ByVal value As del) End AddHandler End Event]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903555, "DevDiv/Personal")> <Fact> Public Sub ParseMergedForEachAndDecl() Dim code As String = (<![CDATA[#Region "abc" Function goo() As Boolean Dim roleName As Object For Each roleName In wbirFields Next roleName End Function #End Region]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Dim roleName As Object", StringComparison.Ordinal) + 22, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903805, "DevDiv/Personal")> <Fact> Public Sub ParseEnumWithoutEnd() Dim code As String = (<![CDATA[Public Class Class2 Protected Enum e e1 e2 End Enum Public Function Goo(ByVal arg1 As e) As e End Function End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("e2", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903826, "DevDiv/Personal")> <Fact> Public Sub IncParseWrongSelectFollByIf() Dim code As String = (<![CDATA[ Sub goo() Select Case lng Case 44 int1 = 4 End Select If true Then End If End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(code.IndexOf("End ", StringComparison.Ordinal), 4), .changeType = ChangeType.Remove}) End Sub <WorkItem(904768, "DevDiv/Personal")> <Fact> Public Sub IncParseDoLoop() Dim code As String = (<![CDATA[ Sub AnonTConStmnt() Do i += 1 Loop Until true End Sub ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Do", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(904771, "DevDiv/Personal")> <Fact> Public Sub IncParseClassWithOpDecl() Dim code As String = (<![CDATA[ Friend Module m1 Class Class1 Shared Operator -(ByVal x As Class1) As Boolean End Operator End Class End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Class ", .changeSpan = New TextSpan(code.IndexOf("Class ", StringComparison.Ordinal), 6), .changeType = ChangeType.Remove}) End Sub <WorkItem(904782, "DevDiv/Personal")> <Fact> Public Sub IncParsePropFollIncompleteLambda() Dim code As String = (<![CDATA[ Class c1 Public Function goo() As Object Dim res = Function(x As Integer) c1.Goo(x) End Function Default Public Property Prop(ByVal y As String) As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ")", .changeSpan = New TextSpan(code.IndexOf("x As Integer)", StringComparison.Ordinal) + 12, 1), .changeType = ChangeType.Remove}) End Sub <WorkItem(904792, "DevDiv/Personal")> <Fact> Public Sub IncParseErroneousGroupByQuery() Dim code As String = (<![CDATA[ Sub goo() Dim q2 = From i In str Group i By key1 = x Dim q3 =From j In str Group By key = i End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = " By", .changeSpan = New TextSpan(code.IndexOf(" By key1", StringComparison.Ordinal), 3), .changeType = ChangeType.Remove}) End Sub <WorkItem(904804, "DevDiv/Personal")> <Fact> Public Sub IncParseSetAfterIncompleteSub() Dim code As String = (<![CDATA[Sub goo() End Sub Public WriteOnly Property bar() as short Set End Set End Property]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("End Sub", StringComparison.Ordinal) + 7, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(911100, "DevDiv/Personal")> <Fact> Public Sub IncParseEmbeddedIfsInsideCondCompile() Dim code As String = "Sub bar() " & vbCrLf & "#If true Then" & vbCrLf & "if true Then goo()" & vbCrLf & "If Command() <" & vbCrLf IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ">", .changeSpan = New TextSpan(code.IndexOf("If Command() <", StringComparison.Ordinal) + 14, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(911103, "DevDiv/Personal")> <Fact> Public Sub IncParseErrorIfStatement() Dim code As String = "Public Sub Run() " & vbCrLf & "If NewTextPI.DTE Is Nothing Then End" & vbCrLf & "End Sub" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "NewTextPI", .changeSpan = New TextSpan(code.IndexOf("NewTextPI.DTE", StringComparison.Ordinal), 9), .changeType = ChangeType.Remove}) End Sub <WorkItem(537168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537168")> <Fact> Public Sub IncParseSubBeforePartialClass() Dim code As String = (<![CDATA[End Class Partial Class class3 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(537172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537172")> <Fact> Public Sub IncParseInterfaceDeleteWithColon() Dim code As String = (<![CDATA[Interface I : Sub Goo() : End Interface]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface ", .changeSpan = New TextSpan(0, 10), .changeType = ChangeType.Remove}) End Sub <WorkItem(537174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537174")> <Fact> Public Sub IncParseMissingEndAddHandler() Dim code As String = (<![CDATA[ Class C Custom Event e As del AddHandler(ByVal value As del) End AddHandler RemoveHandler(ByVal value As del) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]>).Value Dim change = "End AddHandler" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = change, .changeSpan = New TextSpan(code.IndexOf(change, StringComparison.Ordinal), change.Length), .changeType = ChangeType.Remove}) End Sub <WorkItem(539038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539038")> <Fact> Public Sub IncParseInvalidText() Dim code As String = (<![CDATA[1. Verify that INT accepts an constant of each type as the ' argument.]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "os: ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(539053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539053")> <Fact> Public Sub IncParseAddSubValid() Dim code As String = (<![CDATA[Class CGoo Public S() Dim x As Integer = 0 End Sub End Class]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(22, 0), " Sub ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Dim exp1 = newTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Dim inc1 = incTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.SubBlock, exp1.Kind()) Assert.Equal(exp1.Kind(), inc1.Kind()) Dim exp2 = exp1.ChildNodesAndTokens()(1) Dim inc2 = inc1.ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.LocalDeclarationStatement, exp2.Kind()) Assert.Equal(exp2.Kind(), inc2.Kind()) ' this XML output is too much 'IncParseAndVerify(New IncParseNode With { '.oldText = code, '.changeText = " Sub ", '.changeSpan = New TextSpan(22, 0), '.changeType = ChangeType.Insert}) End Sub <WorkItem(538577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538577")> <Fact> Public Sub IncParseAddSpaceAfterForNext() Dim code As String = (<![CDATA[Module M Sub Main() Dim i(1) As Integer For i(0) = 1 To 10 For j = 1 To 10 Next j, i(0) End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(103, 0), " ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(False, oldTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, newTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incTree, newTree) End Sub <Fact> <WorkItem(540667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540667")> Public Sub IncrementalParseAddSpaceInSingleLineIf() ' The code below intentionally is missing a space between the "Then" and "Console" Dim code As String = (<![CDATA[ Module M Sub Main() If False ThenConsole.WriteLine("FIRST") : Console.WriteLine("TEST") Else Console.WriteLine("TRUE!") : 'comment End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim insertionPoint = code.IndexOf("Console", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, 0), " ")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(False, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub <Fact> <WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")> Public Sub IncrementalParseInterpolationInSingleLineIf() Dim code As String = (<![CDATA[ Module Module1 Sub Test1(val1 As Integer) If val1 = 1 Then System.Console.WriteLine($"abc '" & sServiceName & "'") End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Const replace = """ &" Dim insertionPoint = code.IndexOf(replace, StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, replace.Length), "{")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(True, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(True, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub #End Region <WorkItem(543489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543489")> <Fact> Public Sub Bug11296() Dim source As String = <![CDATA[ Module M Sub Main() GoTo 100 Dim Flag1 = 1 If Flag1 = 1 Then Flag1 = 100 Else 100: End If End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Assert.Equal(1, oldTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", oldTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[131..134)", oldTree.GetDiagnostics()(0).Location.SourceSpan.ToString) ' commenting out the goto Dim pos = source.IndexOf("GoTo 100", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(1, tmpTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", tmpTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[132..135)", tmpTree.GetDiagnostics()(0).Location.SourceSpan.ToString) End Sub <Fact> Public Sub IncParseTypeNewLine() Dim code As String = (<![CDATA[ Module m Sub s End Sub End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(15, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(545667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545667")> <Fact> Public Sub Bug14266() Dim source = <![CDATA[ Enum E A End Enum ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert a single character at the beginning. Dim newText = oldText.Replace(start:=0, length:=0, newText:="B") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546680")> <Fact> Public Sub Bug16533() Dim source = <![CDATA[ Module M Sub M() If True Then M() Else : End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Replace "True" with "True". Dim str = "True" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=str) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, oldTree) End Sub <WorkItem(546685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546685")> <Fact> Public Sub MultiLineIf() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should not have been reused. Assert.True(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes before a multi-line If should ''' not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_2() Dim source = <![CDATA[ Module M Sub M() Dim b = False b = True If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "False" to "True". Dim position = oldText.ToString().IndexOf("False", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=5, newText:="True") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes sufficiently far after a multi-line If ''' should not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_3() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If While b End While End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546692")> <Fact> Public Sub Bug16575() Dim source = <![CDATA[ Module M Sub M() If True Then Else Dim x = 1 : Dim y = x If True Then Else Dim x = 1 : Dim y = x End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add newline after first single line If Dim str = "y = x" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) + str.Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546698")> <Fact> Public Sub Bug16596() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Dim x = Sub() If True Then Return : 'Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Uncomment "Else". Dim position = oldText.ToString().IndexOf("'Else", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530662")> <Fact> Public Sub Bug16662() Dim source = ToText(<![CDATA[ Module M Sub M() ''' <[ 1: X End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove "X". Dim position = oldText.ToString().IndexOf("X"c) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546774")> <Fact> Public Sub Bug16786() Dim source = <![CDATA[ Namespace N ''' <summary/> Class A End Class End Namespace Class B End Class Class C End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Append "Class". Dim position = oldText.ToString().Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf & "Class") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Original Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.NamespaceBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530841")> <Fact> Public Sub Bug17031() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Sub M()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + str.Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(531017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531017")> <Fact> Public Sub Bug17409() Dim source = ToText(<![CDATA[ Module M Sub M() Dim ch As Char Dim ch As Char Select Case ch Case "~"c Case Else End Select End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove second instance of "Dim ch As Char". Const str = "Dim ch As Char" Dim position = oldText.ToString().LastIndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=String.Empty) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs() Dim code As String = <![CDATA[ Module M Public obj0 As Object Public obj1 A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' Remove first N characters. Dim span = New TextSpan(0, code.IndexOf("j0", StringComparison.Ordinal)) Dim change = New TextChange(span, "") Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Dim children1 = newTree.GetRoot().ChildNodesAndTokens() Dim children2 = fulltree.GetRoot().ChildNodesAndTokens() Assert.Equal(children2.Count, children1.Count) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs02() Dim code As String = <![CDATA[ Module M Sub M() Try Catch ex A]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547251")> Public Sub IncParseAddRemoveStopAtAofPropAs() Dim code As String = <![CDATA[Class C Inherits Attribute ]]>.Value Dim code1 As String = <![CDATA[ Property goo() A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' insert code1 after code Dim span = New TextSpan(oldIText.Length, 0) Dim change = New TextChange(span, code1) Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) ' remove span = New TextSpan(0, code1.Length) change = New TextChange(span, "") newIText = newIText.WithChanges(change) ' InvalidCastException newTree = newTree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Assert.Equal(fulltree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547303")> Public Sub IncParseAddRemoveStopAtTofThen() Dim code As String = <![CDATA[ Module M Sub M() If True Then ElseIf False T]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <WorkItem(571105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571105")> <Fact()> Public Sub IncParseInsertLineBreakBeforeLambda() Dim code As String = <![CDATA[ Module M Sub F() Dim a1 = If(Sub() End Sub, Nothing) End Sub End Module]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldText = tree.GetText() ' insert line break after '=' Dim span = New TextSpan(code.IndexOf("="c), 0) Dim change = New TextChange(span, vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = tree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(578279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578279")> <Fact()> Public Sub IncParseInsertLineBreakBetweenEndSub() Dim code As String = <![CDATA[Class C Sub M() En Sub Private F = 1 End Class]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' insert line break Dim position = code.IndexOf("En ", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "End" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub InsertWithinLookAhead() Dim code As String = <![CDATA[ Module M Function F(s As String) Return From c In s End Function End Module]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert "Select c" at end of method. Dim position = code.IndexOf(" End Function", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 0), " Select c" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Async & Iterator" <Fact> Public Sub AsyncToSyncMethod() Dim source = ToText(<![CDATA[ Class C Async Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Async Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethod() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Async Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #End Region <WorkItem(554442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554442")> <Fact> Public Sub SplitCommentAtPreprocessorSymbol() Dim source = ToText(<![CDATA[ Module M Function F() ' comment # 1 and # 2 ' comment ' comment Return Nothing End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Split comment at "#". Dim position = oldText.ToString().IndexOf("#"c) Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(586698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586698")> <Fact> Public Sub SortUsings() Dim oldSource = ToText(<![CDATA[ Imports System.Linq Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim newSource = ToText(<![CDATA[ Imports System Imports System.Linq Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Changes: ' 1. "" => "System\r\nImports " ' 2. "System\r\nImports " => "" Dim newText = oldText.WithChanges( New TextChange(TextSpan.FromBounds(8, 8), "System" + vbCrLf + "Imports "), New TextChange(TextSpan.FromBounds(29, 45), "")) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub Reformat() Dim oldSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1 , 2 , 3 End Select End Sub End Class ]]>) Dim newSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1, 2, 3 End Select End Sub End Class ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim startOfNew = newSource.IndexOf("Dim", StringComparison.Ordinal) Dim endOfNew = newSource.LastIndexOf("Select", StringComparison.Ordinal) + 6 Dim startOfOld = startOfNew Dim endOfOld = oldSource.Length - newSource.Length + endOfNew Dim newText = oldText.Replace(TextSpan.FromBounds(startOfOld, endOfOld), newSource.Substring(startOfNew, endOfNew - startOfNew + 1)) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(604044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604044")> <Fact> Public Sub BunchALabels() Dim source = ToText(<![CDATA[ Module Program Sub Main() &HF: &HFF: &HFFF: &HFFFF: &HFFFFF: &HFFFFFF: &HFFFFFFF: &HFFFFFFFF: &HFFFFFFFFF: &HFFFFFFFFFF: End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add enter after &HFFFFFFFFFF:. Dim position = oldText.ToString().IndexOf("&HFFFFFFFFFF:", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + "&HFFFFFFFFFF:".Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(625612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625612")> <Fact()> Public Sub LabelAfterColon() ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following a colon within a single-line statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() If True Then M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) End Sub Private Sub LabelAfterColonCore(valid As Boolean, code As String) Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim diagnostics = oldTree.GetDiagnostics() Assert.Equal(valid, diagnostics.Count = 0) ' Replace "70". Dim position = code.IndexOf("70", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "71") Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(529260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260")> <Fact()> Public Sub DoNotReuseAnnotatedNodes() Dim text As String = <![CDATA[ Class C End Class Class D End Class ]]>.Value.Replace(vbCr, vbCrLf) ' NOTE: We're using the class statement, rather than the block, because the ' change region is expanded enough to impinge on the block. Dim extractGreenClassC As Func(Of SyntaxTree, Syntax.InternalSyntax.VisualBasicSyntaxNode) = Function(tree) DirectCast(tree.GetRoot().DescendantNodes().First(Function(n) n.IsKind(SyntaxKind.ClassStatement)), VisualBasicSyntaxNode).VbGreen '''''''''' ' Check reuse after a trivial change in an unannotated tree. '''''''''' Dim oldTree1 = VisualBasicSyntaxTree.ParseText(text) Dim newTree1 = oldTree1.WithInsertAt(text.Length, " ") ' Class declaration is reused. Assert.Same(extractGreenClassC(oldTree1), extractGreenClassC(newTree1)) '''''''''' ' Check reuse after a trivial change in an annotated tree. '''''''''' Dim tempTree2 = VisualBasicSyntaxTree.ParseText(text) Dim tempRoot2 = tempTree2.GetRoot() Dim tempToken2 = tempRoot2.DescendantTokens().First(Function(t) t.Kind = SyntaxKind.IdentifierToken) Dim oldRoot2 = tempRoot2.ReplaceToken(tempToken2, tempToken2.WithAdditionalAnnotations(New SyntaxAnnotation())) Assert.True(oldRoot2.ContainsAnnotations, "Should contain annotations.") Assert.Equal(text, oldRoot2.ToFullString()) Dim oldTree2 = VisualBasicSyntaxTree.Create(DirectCast(oldRoot2, VisualBasicSyntaxNode), DirectCast(tempTree2.Options, VisualBasicParseOptions), tempTree2.FilePath, Encoding.UTF8) Dim newTree2 = oldTree2.WithInsertAt(text.Length, " ") Dim oldClassC2 = extractGreenClassC(oldTree2) Dim newClassC2 = extractGreenClassC(newTree2) Assert.True(oldClassC2.ContainsAnnotations, "Should contain annotations") Assert.False(newClassC2.ContainsAnnotations, "Annotations should have been removed.") ' Class declaration is not reused... Assert.NotSame(oldClassC2, newClassC2) ' ...even though the text is the same. Assert.Equal(oldClassC2.ToFullString(), newClassC2.ToFullString()) Dim oldToken2 = DirectCast(oldClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Dim newToken2 = DirectCast(newClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Assert.True(oldToken2.ContainsAnnotations, "Should contain annotations") Assert.False(newToken2.ContainsAnnotations, "Annotations should have been removed.") ' Token is not reused... Assert.NotSame(oldToken2, newToken2) ' ...even though the text is the same. Assert.Equal(oldToken2.ToFullString(), newToken2.ToFullString()) End Sub <Fact> Public Sub IncrementalParsing_NamespaceBlock_TryLinkSyntaxMethodsBlock() 'Sub Block 'Function Block 'Property Block Dim source = ToText(<![CDATA[ Namespace N Module M Function F() as Boolean Return True End Function Sub M() End Sub Function Fn() as Boolean Return True End Function Property as Integer = 1 End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module M" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxClass() 'Class Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Public Class C1 End Class Class C2 End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxStructure() 'Structure Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Structure S2 1 Dim i as integer End Structure Public Structure S2 Dim i as integer End Structure End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxOptionStatement() 'Option Statement Dim source = ToText(<![CDATA[ Option Strict Off Option Infer On Option Explicit On ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxImports() 'Imports Statement Dim source = ToText(<![CDATA[ Imports System Imports System.Collections Imports Microsoft.Visualbasic ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxDelegateSub() 'ExecutableStatementBlock -> DelegateSub Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Dim x = Nothing Delegate Sub Goo() Public Delegate Sub GooWithModifier() End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxOperatorBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() Dim x As New SomeClass Dim y As Boolean = -x End Sub Class SomeClass Dim member As Long = 2 Public Overloads Shared Operator -(ByVal value As SomeClass) As Boolean If value.member Mod 5 = 0 Then Return True End If Return False End Operator End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxEventBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxPropertyBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Property abc As Integer Set(value As Integer) End Set Get End Get End Property End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceModuleBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs End Namespace Module Module1 Dim x End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceNamespaceBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs Namespace vs2 End Namespace End Namespace Namespace vs3 End Namespace End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxItems() Dim source = ToText(<![CDATA[ Class SomeClass Dim member As Long = 2 Sub abc() 'Remove Dim xyz as integer = 2 IF member = 1 then Console.writeline("TEST"); Dim SingleLineDeclare as integer = 2 End Sub Dim member2 As Long = 2 Dim member3 As Long = 2 Enum EnumItem Item1 End Enum End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Sub abc() 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_PropertyContextBlock_TryLinkSyntaxSetAccessor() 'PropertyContextBlock -> SetAccessor Dim source = ToText(<![CDATA[ Class C Private _p As Integer = 0 Property p2 As Integer Set(value As Integer) End Set Get End Get End Property Private _d As Integer = 1 End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Property" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_BlockContext_TryLinkSyntaxSelectBlock() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Bar() End Sub Function Goo(i As Integer) As Integer Dim y As Integer = i Select Case y Case 1 Case 2, 3 Case Else End Select Return y + 1 Try Catch ex As exception End Try If y = 1 Then Console.WriteLine("Test") Y = 1 While y <= 10 y = y + 1 End While Using f As New Goo End Using Dim Obj_C As New OtherClass With Obj_C End With SyncLock Obj_C End SyncLock Select Case y Case 10 Case Else End Select y = 0 Do y = y + 1 If y >= 3 Then Exit Do Loop y = 0 Do While y < 4 y = y + 1 Loop y = 0 Do Until y > 5 y = y + 1 Loop End Function End Module Class Goo Implements IDisposable #Region "IDisposable Support" Private disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then End If End If Me.disposedValue = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class Class OtherClass End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Select" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax1() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "RemoveHandler(ByVal value As EventHandler)" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax2() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 _P = _P +1 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "_P = 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxClass() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Class C End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxEnum() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Public Enum TestEnum Item End Enum End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CaseBlockContext_TryLinkSyntaxCase() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim i As Integer Dim y As Integer Select Case i Case 1 _p = 1 Case 2, 3 _p = 2 Case Else _p = 3 End Select End Sub Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Case 2, 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CatchContext_TryLinkSyntaxCatch() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim x1 As Integer = 1 Try x1 = 2 Catch ex As NullReferenceException Dim z = 1 Catch ex As ArgumentException 'Remove Dim z = 1 Catch ex As Exception _p = 3 Dim s = Bar() Finally _p = 4 End Try End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Catch ex As ArgumentException 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_NamespaceBlockContext_TryLinkSyntaxModule() Dim source = ToText(<![CDATA[ Namespace NS1 Module ModuleTemp 'Remove End Module Module Module1 'Remove Sub Goo() Dim x1 As Integer = 1 End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module ModuleTemp 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_IfBlockContext_TryLinkSyntax() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Goo() If x = 1 Then _p=1 elseIf x = 2 Then _p=2 elseIf x = 3 Then _p=3 else If y = 1 Then _p=2 End If End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "elseIf x = 2 Then" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact()> Public Sub Bug719787_EOF() Dim source = <![CDATA[ Namespace N Class C Property P As Integer End Class Structure S Private F As Object End Structure End Namespace ]]>.Value.Trim() ' Add two line breaks at end. source += vbCrLf Dim position = source.Length source += vbCrLf Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add "Delegate" to end of file between line breaks. Dim newText = oldText.Replace(start:=position, length:=0, newText:="Delegate") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Most of the Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.StructureStatement))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact> Public Sub Bug719787_MultiLineIf() Dim source = <![CDATA[ Class C Sub M() If e1 Then If e2 Then M11() Else M12() End If ElseIf e2 Then If e2 Then M21() Else M22() End If ElseIf e3 Then If e2 Then M31() Else M32() End If ElseIf e4 Then If e2 Then M41() Else M42() End If Else If e2 Then M51() Else M52() End If End If End Sub ' Comment End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim toReplace = "' Comment" Dim position = source.IndexOf(toReplace, StringComparison.Ordinal) ' Replace "' Comment" with "Property" Dim newText = oldText.Replace(start:=position, length:=toReplace.Length, newText:="Property") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' The ElseIfBlocks should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.ElseIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Helpers" Private Shared Function GetTokens(root As SyntaxNode) As InternalSyntax.VisualBasicSyntaxNode() Return root.DescendantTokens().Select(Function(t) DirectCast(t.Node, InternalSyntax.VisualBasicSyntaxNode)).ToArray() End Function Private Shared Sub VerifyTokensEquivalent(rootA As SyntaxNode, rootB As SyntaxNode) Dim tokensA = GetTokens(rootA) Dim tokensB = GetTokens(rootB) Assert.Equal(tokensA.Count, tokensB.Count) For i = 0 To tokensA.Count - 1 Dim tokenA = tokensA(i) Dim tokenB = tokensB(i) Assert.Equal(tokenA.Kind, tokenB.Kind) Assert.Equal(tokenA.ToFullString(), tokenB.ToFullString()) Next End Sub Private Shared Sub VerifyEquivalent(treeA As SyntaxTree, treeB As SyntaxTree) Dim rootA = treeA.GetRoot() Dim rootB = treeB.GetRoot() VerifyTokensEquivalent(rootA, rootB) Dim diagnosticsA = treeA.GetDiagnostics() Dim diagnosticsB = treeB.GetDiagnostics() Assert.True(rootA.IsEquivalentTo(rootB)) Assert.Equal(diagnosticsA.Count, diagnosticsB.Count) For i = 0 To diagnosticsA.Count - 1 Assert.Equal(diagnosticsA(i).Inspect(), diagnosticsB(i).Inspect()) Next End Sub Private Shared Function ToText(code As XCData) As String Dim str = code.Value.Trim() ' Normalize line terminators. Dim builder = ArrayBuilder(Of Char).GetInstance() For i = 0 To str.Length - 1 Dim c = str(i) If (c = vbLf(0)) AndAlso ((i = str.Length - 1) OrElse (str(i + 1) <> vbCr(0))) Then builder.AddRange(vbCrLf) Else builder.Add(c) End If Next Return New String(builder.ToArrayAndFree()) End Function #End Region End Class
' Licensed to the .NET Foundation under one or more 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.ObjectModel Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Public Class IncrementalParser Private ReadOnly _s As String = <![CDATA[ '----------------------- ' ' Copyright (c) ' '----------------------- #const BLAH = true Imports Roslyn.Compilers Imports Roslyn.Compilers.Common Imports Roslyn.Compilers.VisualBasic Public Module ParseExprSemantics Dim text = SourceText.From("") Dim tree As SyntaxTree = Nothing #const x = 1 ''' <summary> ''' This is just gibberish to test parser ''' </summary> ''' <param name="ITERS"> haha </param> ''' <remarks></remarks> Public Sub Run(ByVal ITERS As Long) Console.WriteLine() #if BLAH Console.WriteLine("==== Parsing file: " & "Sample_ExpressionSemantics.vb") Console.WriteLine("Iterations:" & ITERS) #end if Dim str = IO.File.ReadAllText("Sample_ExpressionSemantics.vb") Dim lineNumber = 28335 Dim root As SyntaxNode = Nothing dim s1 = sub () If True Then Console.WriteLine(1) : dim s2 = sub () If True Then Console.WriteLine(1) ::Console.WriteLine(1):: dim s3 = sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1) Dim sw = System.Diagnostics.Stopwatch.StartNew() For i As Integer = 0 To ITERS - 1 tree = SyntaxTree.Parse(text, Nothing) root = tree.Root Console.Write(".") Dim highWater As Integer = Math.Max(highWater, System.GC.GetTotalMemory(False)) Next Dim grouped = From node In root.GetNodesWhile(root.FullSpan, Function() True) Group By node.Kind Into Group, Count() Order By Count Descending Take 30 Console.WriteLine("Quick token cache-hits: {0} ({1:G2}%)", Stats.quickReturnedToken, 100.0 * Stats.quickReturnedToken / Stats.quickAttempts) End Sub End Module]]>.Value <Fact> Public Sub FakeEdits() Dim text As SourceText = SourceText.From(_s) Dim tree As SyntaxTree = Nothing Dim root As SyntaxNode = Nothing tree = VisualBasicSyntaxTree.ParseText(text) root = tree.GetRoot() Assert.Equal(False, root.ContainsDiagnostics) For i As Integer = 0 To text.Length - 11 Dim span = New TextSpan(i, 10) text = text.WithChanges(New TextChange(span, text.ToString(span))) tree = tree.WithChangedText(text) Dim prevRoot = root root = tree.GetRoot() Assert.True(prevRoot.IsEquivalentTo(root)) Next End Sub <Fact> Public Sub TypeAFile() Dim text As SourceText = SourceText.From("") Dim tree As SyntaxTree = Nothing tree = VisualBasicSyntaxTree.ParseText(text) Assert.Equal(False, tree.GetRoot().ContainsDiagnostics) For i As Integer = 0 To _s.Length - 1 ' add next character in file 's' to text Dim newText = text.WithChanges(New TextChange(New TextSpan(text.Length, 0), _s.Substring(i, 1))) Dim newTree = tree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) text = newText tree = newTree Next End Sub <Fact> Public Sub Preprocessor() Dim oldText = SourceText.From(_s) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' commenting out the #const Dim pos = _s.IndexOf("#const", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) ' removes ' from the '#const Dim newString = newText.ToString() pos = newString.IndexOf("'#const", StringComparison.Ordinal) Dim anotherText = newText.WithChanges(New TextChange(New TextSpan(pos, 1), "")) newTree = newTree.WithChangedText(anotherText) tmpTree = VisualBasicSyntaxTree.ParseText(anotherText) VerifyEquivalent(newTree, tmpTree) End Sub #Region "Regressions" <WorkItem(899264, "DevDiv/Personal")> <Fact> Public Sub IncParseWithEventsFollowingProperty() 'Unable to verify this using CDATA, since CDATA value only has Cr appended at end of each line, 'where as this bug is reproducible only with CrLf at the end of each line Dim code As String = "Public Class HasPublicMembersToConflictWith" & vbCrLf & "Public ConflictWithProp" & vbCrLf & "" & vbCrLf & "Public Property _ConflictWithBF() As String" & vbCrLf & " Get" & vbCrLf & " End Get" & vbCrLf & " Set(value As String)" & vbCrLf & " End Set" & vbCrLf & "End Property" & vbCrLf & "" & vbCrLf & "Public WithEvents ConflictWithBoth As Ob" ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "j", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899596, "DevDiv/Personal")> <Fact> Public Sub IncParseClassFollowingDocComments() Dim code As String = <![CDATA[Class VBQATestcase '''----------------------------------------------------------------------------- ''' <summary> '''Text ''' </summary> '''-----------------------------------------------------------------------------]]>.Value ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf & "Pub", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899918, "DevDiv/Personal")> <Fact> Public Sub IncParseDirInElse() Dim code As String = "Sub Sub1()" & vbCr & "If true Then" & vbCr & "goo("""")" & vbCr & "Else" & vbCr & vbCr & "#If Not ULTRAVIOLET Then" & vbCr ParseAndVerify(code, <errors> <error id="30012"/> <error id="30081"/> <error id="30026"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899938, "DevDiv/Personal")> <Fact> Public Sub IncParseNamespaceFollowingEvent() Dim code As String = "Class cls1" & vbCrLf & "Custom Event myevent As del" & vbCrLf & "End Event" & vbCrLf & "End Class" & vbCrLf & "Namespace r" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "e", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(900209, "DevDiv/Personal")> <Fact> Public Sub IncParseCaseElse() Dim code As String = (<![CDATA[ Sub main() Select Case 5 Case Else vvv = 6 Case Else vvv = 7 ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901386, "DevDiv/Personal")> <Fact> Public Sub IncParseExplicitOnGroupBy() Dim code As String = (<![CDATA[ Option Explicit On Sub goo() Dim q2 = From x In col let y = x Group x, y By]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901639, "DevDiv/Personal")> <Fact> Public Sub IncParseExprLambdaInSubContext() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParseExprLambdaInSubContext2() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then Else End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901645, "DevDiv/Personal")> <Fact> Public Sub IncParseExitFunction() Dim code As String = (<![CDATA[Function If strSwitches <> "" Then strCLine = strCLine & " " & strSwitches End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Exit ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901655, "DevDiv/Personal")> <Fact> Public Sub IncParseDateLiteral() IncParseAndVerify(New IncParseNode With { .oldText = "", .changeText = "#10/18/1969# hello 123", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParsePPElse() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#End If", .changeSpan = New TextSpan(code.IndexOf("Next roleName", StringComparison.Ordinal) + 15, 2), .changeType = ChangeType.Replace}) End Sub <Fact> Public Sub IncParsePPElse1() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName #End IF End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#If true " & vbCrLf, .changeSpan = New TextSpan(code.IndexOf("#Else", StringComparison.Ordinal), 0), .changeType = ChangeType.Replace}) End Sub <WorkItem(901669, "DevDiv/Personal")> <Fact> Public Sub ParseXmlTagWithExprHole() Dim code As String = (<![CDATA[e a=<%= b %>>]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "<", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901671, "DevDiv/Personal")> <Fact> Public Sub IncParseEndBeforeSubWithX() Dim code As String = (<![CDATA[Sub End Class X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901676, "DevDiv/Personal")> <Fact> Public Sub IncParseInterfaceFollByConstructs() Dim code As String = (<![CDATA[ Public Interface I2 End Interface Sub SEHIllegal501() Try Catch End Try Exit Sub End Sub X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901680, "DevDiv/Personal")> <Fact> Public Sub IncParseLCFunctionCompoundAsn() Dim code As String = (<![CDATA[Public Function goo() As String For i As Integer = 0 To 1 total += y(i) Next End Function]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "> _" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(902710, "DevDiv/Personal")> <Fact> Public Sub IncParseInsertFunctionBeforeEndClass() Dim code As String = (<![CDATA[End Class MustInherit Class C10 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Function" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903134, "DevDiv/Personal")> <Fact> Public Sub InsertSubBeforeCustomEvent() Dim code As String = (<![CDATA[ Custom Event e As del AddHandler(ByVal value As del) End AddHandler End Event]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903555, "DevDiv/Personal")> <Fact> Public Sub ParseMergedForEachAndDecl() Dim code As String = (<![CDATA[#Region "abc" Function goo() As Boolean Dim roleName As Object For Each roleName In wbirFields Next roleName End Function #End Region]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Dim roleName As Object", StringComparison.Ordinal) + 22, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903805, "DevDiv/Personal")> <Fact> Public Sub ParseEnumWithoutEnd() Dim code As String = (<![CDATA[Public Class Class2 Protected Enum e e1 e2 End Enum Public Function Goo(ByVal arg1 As e) As e End Function End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("e2", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903826, "DevDiv/Personal")> <Fact> Public Sub IncParseWrongSelectFollByIf() Dim code As String = (<![CDATA[ Sub goo() Select Case lng Case 44 int1 = 4 End Select If true Then End If End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(code.IndexOf("End ", StringComparison.Ordinal), 4), .changeType = ChangeType.Remove}) End Sub <WorkItem(904768, "DevDiv/Personal")> <Fact> Public Sub IncParseDoLoop() Dim code As String = (<![CDATA[ Sub AnonTConStmnt() Do i += 1 Loop Until true End Sub ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Do", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(904771, "DevDiv/Personal")> <Fact> Public Sub IncParseClassWithOpDecl() Dim code As String = (<![CDATA[ Friend Module m1 Class Class1 Shared Operator -(ByVal x As Class1) As Boolean End Operator End Class End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Class ", .changeSpan = New TextSpan(code.IndexOf("Class ", StringComparison.Ordinal), 6), .changeType = ChangeType.Remove}) End Sub <WorkItem(904782, "DevDiv/Personal")> <Fact> Public Sub IncParsePropFollIncompleteLambda() Dim code As String = (<![CDATA[ Class c1 Public Function goo() As Object Dim res = Function(x As Integer) c1.Goo(x) End Function Default Public Property Prop(ByVal y As String) As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ")", .changeSpan = New TextSpan(code.IndexOf("x As Integer)", StringComparison.Ordinal) + 12, 1), .changeType = ChangeType.Remove}) End Sub <WorkItem(904792, "DevDiv/Personal")> <Fact> Public Sub IncParseErroneousGroupByQuery() Dim code As String = (<![CDATA[ Sub goo() Dim q2 = From i In str Group i By key1 = x Dim q3 =From j In str Group By key = i End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = " By", .changeSpan = New TextSpan(code.IndexOf(" By key1", StringComparison.Ordinal), 3), .changeType = ChangeType.Remove}) End Sub <WorkItem(904804, "DevDiv/Personal")> <Fact> Public Sub IncParseSetAfterIncompleteSub() Dim code As String = (<![CDATA[Sub goo() End Sub Public WriteOnly Property bar() as short Set End Set End Property]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("End Sub", StringComparison.Ordinal) + 7, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(911100, "DevDiv/Personal")> <Fact> Public Sub IncParseEmbeddedIfsInsideCondCompile() Dim code As String = "Sub bar() " & vbCrLf & "#If true Then" & vbCrLf & "if true Then goo()" & vbCrLf & "If Command() <" & vbCrLf IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ">", .changeSpan = New TextSpan(code.IndexOf("If Command() <", StringComparison.Ordinal) + 14, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(911103, "DevDiv/Personal")> <Fact> Public Sub IncParseErrorIfStatement() Dim code As String = "Public Sub Run() " & vbCrLf & "If NewTextPI.DTE Is Nothing Then End" & vbCrLf & "End Sub" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "NewTextPI", .changeSpan = New TextSpan(code.IndexOf("NewTextPI.DTE", StringComparison.Ordinal), 9), .changeType = ChangeType.Remove}) End Sub <WorkItem(537168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537168")> <Fact> Public Sub IncParseSubBeforePartialClass() Dim code As String = (<![CDATA[End Class Partial Class class3 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(537172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537172")> <Fact> Public Sub IncParseInterfaceDeleteWithColon() Dim code As String = (<![CDATA[Interface I : Sub Goo() : End Interface]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface ", .changeSpan = New TextSpan(0, 10), .changeType = ChangeType.Remove}) End Sub <WorkItem(537174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537174")> <Fact> Public Sub IncParseMissingEndAddHandler() Dim code As String = (<![CDATA[ Class C Custom Event e As del AddHandler(ByVal value As del) End AddHandler RemoveHandler(ByVal value As del) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]>).Value Dim change = "End AddHandler" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = change, .changeSpan = New TextSpan(code.IndexOf(change, StringComparison.Ordinal), change.Length), .changeType = ChangeType.Remove}) End Sub <WorkItem(539038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539038")> <Fact> Public Sub IncParseInvalidText() Dim code As String = (<![CDATA[1. Verify that INT accepts an constant of each type as the ' argument.]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "os: ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(539053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539053")> <Fact> Public Sub IncParseAddSubValid() Dim code As String = (<![CDATA[Class CGoo Public S() Dim x As Integer = 0 End Sub End Class]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(22, 0), " Sub ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Dim exp1 = newTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Dim inc1 = incTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.SubBlock, exp1.Kind()) Assert.Equal(exp1.Kind(), inc1.Kind()) Dim exp2 = exp1.ChildNodesAndTokens()(1) Dim inc2 = inc1.ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.LocalDeclarationStatement, exp2.Kind()) Assert.Equal(exp2.Kind(), inc2.Kind()) ' this XML output is too much 'IncParseAndVerify(New IncParseNode With { '.oldText = code, '.changeText = " Sub ", '.changeSpan = New TextSpan(22, 0), '.changeType = ChangeType.Insert}) End Sub <WorkItem(538577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538577")> <Fact> Public Sub IncParseAddSpaceAfterForNext() Dim code As String = (<![CDATA[Module M Sub Main() Dim i(1) As Integer For i(0) = 1 To 10 For j = 1 To 10 Next j, i(0) End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(103, 0), " ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(False, oldTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, newTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incTree, newTree) End Sub <Fact> <WorkItem(540667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540667")> Public Sub IncrementalParseAddSpaceInSingleLineIf() ' The code below intentionally is missing a space between the "Then" and "Console" Dim code As String = (<![CDATA[ Module M Sub Main() If False ThenConsole.WriteLine("FIRST") : Console.WriteLine("TEST") Else Console.WriteLine("TRUE!") : 'comment End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim insertionPoint = code.IndexOf("Console", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, 0), " ")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(False, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub <Fact> <WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")> Public Sub IncrementalParseInterpolationInSingleLineIf() Dim code As String = (<![CDATA[ Module Module1 Sub Test1(val1 As Integer) If val1 = 1 Then System.Console.WriteLine($"abc '" & sServiceName & "'") End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Const replace = """ &" Dim insertionPoint = code.IndexOf(replace, StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, replace.Length), "{")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(True, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(True, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub #End Region <WorkItem(543489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543489")> <Fact> Public Sub Bug11296() Dim source As String = <![CDATA[ Module M Sub Main() GoTo 100 Dim Flag1 = 1 If Flag1 = 1 Then Flag1 = 100 Else 100: End If End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Assert.Equal(1, oldTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", oldTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[131..134)", oldTree.GetDiagnostics()(0).Location.SourceSpan.ToString) ' commenting out the goto Dim pos = source.IndexOf("GoTo 100", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(1, tmpTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", tmpTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[132..135)", tmpTree.GetDiagnostics()(0).Location.SourceSpan.ToString) End Sub <Fact> Public Sub IncParseTypeNewLine() Dim code As String = (<![CDATA[ Module m Sub s End Sub End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(15, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(545667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545667")> <Fact> Public Sub Bug14266() Dim source = <![CDATA[ Enum E A End Enum ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert a single character at the beginning. Dim newText = oldText.Replace(start:=0, length:=0, newText:="B") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546680")> <Fact> Public Sub Bug16533() Dim source = <![CDATA[ Module M Sub M() If True Then M() Else : End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Replace "True" with "True". Dim str = "True" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=str) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, oldTree) End Sub <WorkItem(546685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546685")> <Fact> Public Sub MultiLineIf() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should not have been reused. Assert.True(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes before a multi-line If should ''' not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_2() Dim source = <![CDATA[ Module M Sub M() Dim b = False b = True If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "False" to "True". Dim position = oldText.ToString().IndexOf("False", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=5, newText:="True") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes sufficiently far after a multi-line If ''' should not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_3() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If While b End While End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546692")> <Fact> Public Sub Bug16575() Dim source = <![CDATA[ Module M Sub M() If True Then Else Dim x = 1 : Dim y = x If True Then Else Dim x = 1 : Dim y = x End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add newline after first single line If Dim str = "y = x" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) + str.Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546698")> <Fact> Public Sub Bug16596() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Dim x = Sub() If True Then Return : 'Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Uncomment "Else". Dim position = oldText.ToString().IndexOf("'Else", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530662")> <Fact> Public Sub Bug16662() Dim source = ToText(<![CDATA[ Module M Sub M() ''' <[ 1: X End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove "X". Dim position = oldText.ToString().IndexOf("X"c) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546774")> <Fact> Public Sub Bug16786() Dim source = <![CDATA[ Namespace N ''' <summary/> Class A End Class End Namespace Class B End Class Class C End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Append "Class". Dim position = oldText.ToString().Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf & "Class") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Original Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.NamespaceBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530841")> <Fact> Public Sub Bug17031() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Sub M()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + str.Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(531017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531017")> <Fact> Public Sub Bug17409() Dim source = ToText(<![CDATA[ Module M Sub M() Dim ch As Char Dim ch As Char Select Case ch Case "~"c Case Else End Select End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove second instance of "Dim ch As Char". Const str = "Dim ch As Char" Dim position = oldText.ToString().LastIndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=String.Empty) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs() Dim code As String = <![CDATA[ Module M Public obj0 As Object Public obj1 A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' Remove first N characters. Dim span = New TextSpan(0, code.IndexOf("j0", StringComparison.Ordinal)) Dim change = New TextChange(span, "") Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Dim children1 = newTree.GetRoot().ChildNodesAndTokens() Dim children2 = fulltree.GetRoot().ChildNodesAndTokens() Assert.Equal(children2.Count, children1.Count) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs02() Dim code As String = <![CDATA[ Module M Sub M() Try Catch ex A]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547251")> Public Sub IncParseAddRemoveStopAtAofPropAs() Dim code As String = <![CDATA[Class C Inherits Attribute ]]>.Value Dim code1 As String = <![CDATA[ Property goo() A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' insert code1 after code Dim span = New TextSpan(oldIText.Length, 0) Dim change = New TextChange(span, code1) Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) ' remove span = New TextSpan(0, code1.Length) change = New TextChange(span, "") newIText = newIText.WithChanges(change) ' InvalidCastException newTree = newTree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Assert.Equal(fulltree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547303")> Public Sub IncParseAddRemoveStopAtTofThen() Dim code As String = <![CDATA[ Module M Sub M() If True Then ElseIf False T]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <WorkItem(571105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571105")> <Fact()> Public Sub IncParseInsertLineBreakBeforeLambda() Dim code As String = <![CDATA[ Module M Sub F() Dim a1 = If(Sub() End Sub, Nothing) End Sub End Module]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldText = tree.GetText() ' insert line break after '=' Dim span = New TextSpan(code.IndexOf("="c), 0) Dim change = New TextChange(span, vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = tree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(578279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578279")> <Fact()> Public Sub IncParseInsertLineBreakBetweenEndSub() Dim code As String = <![CDATA[Class C Sub M() En Sub Private F = 1 End Class]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' insert line break Dim position = code.IndexOf("En ", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "End" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub InsertWithinLookAhead() Dim code As String = <![CDATA[ Module M Function F(s As String) Return From c In s End Function End Module]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert "Select c" at end of method. Dim position = code.IndexOf(" End Function", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 0), " Select c" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Async & Iterator" <Fact> Public Sub AsyncToSyncMethod() Dim source = ToText(<![CDATA[ Class C Async Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Async Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethod() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Async Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #End Region <WorkItem(554442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554442")> <Fact> Public Sub SplitCommentAtPreprocessorSymbol() Dim source = ToText(<![CDATA[ Module M Function F() ' comment # 1 and # 2 ' comment ' comment Return Nothing End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Split comment at "#". Dim position = oldText.ToString().IndexOf("#"c) Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(586698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586698")> <Fact> Public Sub SortUsings() Dim oldSource = ToText(<![CDATA[ Imports System.Linq Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim newSource = ToText(<![CDATA[ Imports System Imports System.Linq Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Changes: ' 1. "" => "System\r\nImports " ' 2. "System\r\nImports " => "" Dim newText = oldText.WithChanges( New TextChange(TextSpan.FromBounds(8, 8), "System" + vbCrLf + "Imports "), New TextChange(TextSpan.FromBounds(29, 45), "")) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub Reformat() Dim oldSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1 , 2 , 3 End Select End Sub End Class ]]>) Dim newSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1, 2, 3 End Select End Sub End Class ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim startOfNew = newSource.IndexOf("Dim", StringComparison.Ordinal) Dim endOfNew = newSource.LastIndexOf("Select", StringComparison.Ordinal) + 6 Dim startOfOld = startOfNew Dim endOfOld = oldSource.Length - newSource.Length + endOfNew Dim newText = oldText.Replace(TextSpan.FromBounds(startOfOld, endOfOld), newSource.Substring(startOfNew, endOfNew - startOfNew + 1)) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(604044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604044")> <Fact> Public Sub BunchALabels() Dim source = ToText(<![CDATA[ Module Program Sub Main() &HF: &HFF: &HFFF: &HFFFF: &HFFFFF: &HFFFFFF: &HFFFFFFF: &HFFFFFFFF: &HFFFFFFFFF: &HFFFFFFFFFF: End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add enter after &HFFFFFFFFFF:. Dim position = oldText.ToString().IndexOf("&HFFFFFFFFFF:", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + "&HFFFFFFFFFF:".Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(625612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625612")> <Fact()> Public Sub LabelAfterColon() ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following a colon within a single-line statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() If True Then M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) End Sub Private Sub LabelAfterColonCore(valid As Boolean, code As String) Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim diagnostics = oldTree.GetDiagnostics() Assert.Equal(valid, diagnostics.Count = 0) ' Replace "70". Dim position = code.IndexOf("70", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "71") Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(529260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260")> <Fact()> Public Sub DoNotReuseAnnotatedNodes() Dim text As String = <![CDATA[ Class C End Class Class D End Class ]]>.Value.Replace(vbCr, vbCrLf) ' NOTE: We're using the class statement, rather than the block, because the ' change region is expanded enough to impinge on the block. Dim extractGreenClassC As Func(Of SyntaxTree, Syntax.InternalSyntax.VisualBasicSyntaxNode) = Function(tree) DirectCast(tree.GetRoot().DescendantNodes().First(Function(n) n.IsKind(SyntaxKind.ClassStatement)), VisualBasicSyntaxNode).VbGreen '''''''''' ' Check reuse after a trivial change in an unannotated tree. '''''''''' Dim oldTree1 = VisualBasicSyntaxTree.ParseText(text) Dim newTree1 = oldTree1.WithInsertAt(text.Length, " ") ' Class declaration is reused. Assert.Same(extractGreenClassC(oldTree1), extractGreenClassC(newTree1)) '''''''''' ' Check reuse after a trivial change in an annotated tree. '''''''''' Dim tempTree2 = VisualBasicSyntaxTree.ParseText(text) Dim tempRoot2 = tempTree2.GetRoot() Dim tempToken2 = tempRoot2.DescendantTokens().First(Function(t) t.Kind = SyntaxKind.IdentifierToken) Dim oldRoot2 = tempRoot2.ReplaceToken(tempToken2, tempToken2.WithAdditionalAnnotations(New SyntaxAnnotation())) Assert.True(oldRoot2.ContainsAnnotations, "Should contain annotations.") Assert.Equal(text, oldRoot2.ToFullString()) Dim oldTree2 = VisualBasicSyntaxTree.Create(DirectCast(oldRoot2, VisualBasicSyntaxNode), DirectCast(tempTree2.Options, VisualBasicParseOptions), tempTree2.FilePath, Encoding.UTF8) Dim newTree2 = oldTree2.WithInsertAt(text.Length, " ") Dim oldClassC2 = extractGreenClassC(oldTree2) Dim newClassC2 = extractGreenClassC(newTree2) Assert.True(oldClassC2.ContainsAnnotations, "Should contain annotations") Assert.False(newClassC2.ContainsAnnotations, "Annotations should have been removed.") ' Class declaration is not reused... Assert.NotSame(oldClassC2, newClassC2) ' ...even though the text is the same. Assert.Equal(oldClassC2.ToFullString(), newClassC2.ToFullString()) Dim oldToken2 = DirectCast(oldClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Dim newToken2 = DirectCast(newClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Assert.True(oldToken2.ContainsAnnotations, "Should contain annotations") Assert.False(newToken2.ContainsAnnotations, "Annotations should have been removed.") ' Token is not reused... Assert.NotSame(oldToken2, newToken2) ' ...even though the text is the same. Assert.Equal(oldToken2.ToFullString(), newToken2.ToFullString()) End Sub <Fact> Public Sub IncrementalParsing_NamespaceBlock_TryLinkSyntaxMethodsBlock() 'Sub Block 'Function Block 'Property Block Dim source = ToText(<![CDATA[ Namespace N Module M Function F() as Boolean Return True End Function Sub M() End Sub Function Fn() as Boolean Return True End Function Property as Integer = 1 End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module M" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxClass() 'Class Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Public Class C1 End Class Class C2 End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxStructure() 'Structure Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Structure S2 1 Dim i as integer End Structure Public Structure S2 Dim i as integer End Structure End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxOptionStatement() 'Option Statement Dim source = ToText(<![CDATA[ Option Strict Off Option Infer On Option Explicit On ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxImports() 'Imports Statement Dim source = ToText(<![CDATA[ Imports System Imports System.Collections Imports Microsoft.Visualbasic ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxDelegateSub() 'ExecutableStatementBlock -> DelegateSub Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Dim x = Nothing Delegate Sub Goo() Public Delegate Sub GooWithModifier() End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxOperatorBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() Dim x As New SomeClass Dim y As Boolean = -x End Sub Class SomeClass Dim member As Long = 2 Public Overloads Shared Operator -(ByVal value As SomeClass) As Boolean If value.member Mod 5 = 0 Then Return True End If Return False End Operator End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxEventBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxPropertyBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Property abc As Integer Set(value As Integer) End Set Get End Get End Property End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceModuleBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs End Namespace Module Module1 Dim x End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceNamespaceBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs Namespace vs2 End Namespace End Namespace Namespace vs3 End Namespace End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxItems() Dim source = ToText(<![CDATA[ Class SomeClass Dim member As Long = 2 Sub abc() 'Remove Dim xyz as integer = 2 IF member = 1 then Console.writeline("TEST"); Dim SingleLineDeclare as integer = 2 End Sub Dim member2 As Long = 2 Dim member3 As Long = 2 Enum EnumItem Item1 End Enum End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Sub abc() 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_PropertyContextBlock_TryLinkSyntaxSetAccessor() 'PropertyContextBlock -> SetAccessor Dim source = ToText(<![CDATA[ Class C Private _p As Integer = 0 Property p2 As Integer Set(value As Integer) End Set Get End Get End Property Private _d As Integer = 1 End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Property" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_BlockContext_TryLinkSyntaxSelectBlock() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Bar() End Sub Function Goo(i As Integer) As Integer Dim y As Integer = i Select Case y Case 1 Case 2, 3 Case Else End Select Return y + 1 Try Catch ex As exception End Try If y = 1 Then Console.WriteLine("Test") Y = 1 While y <= 10 y = y + 1 End While Using f As New Goo End Using Dim Obj_C As New OtherClass With Obj_C End With SyncLock Obj_C End SyncLock Select Case y Case 10 Case Else End Select y = 0 Do y = y + 1 If y >= 3 Then Exit Do Loop y = 0 Do While y < 4 y = y + 1 Loop y = 0 Do Until y > 5 y = y + 1 Loop End Function End Module Class Goo Implements IDisposable #Region "IDisposable Support" Private disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then End If End If Me.disposedValue = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class Class OtherClass End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Select" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax1() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "RemoveHandler(ByVal value As EventHandler)" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax2() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 _P = _P +1 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "_P = 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxClass() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Class C End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxEnum() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Public Enum TestEnum Item End Enum End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CaseBlockContext_TryLinkSyntaxCase() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim i As Integer Dim y As Integer Select Case i Case 1 _p = 1 Case 2, 3 _p = 2 Case Else _p = 3 End Select End Sub Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Case 2, 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CatchContext_TryLinkSyntaxCatch() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim x1 As Integer = 1 Try x1 = 2 Catch ex As NullReferenceException Dim z = 1 Catch ex As ArgumentException 'Remove Dim z = 1 Catch ex As Exception _p = 3 Dim s = Bar() Finally _p = 4 End Try End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Catch ex As ArgumentException 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_NamespaceBlockContext_TryLinkSyntaxModule() Dim source = ToText(<![CDATA[ Namespace NS1 Module ModuleTemp 'Remove End Module Module Module1 'Remove Sub Goo() Dim x1 As Integer = 1 End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module ModuleTemp 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_IfBlockContext_TryLinkSyntax() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Goo() If x = 1 Then _p=1 elseIf x = 2 Then _p=2 elseIf x = 3 Then _p=3 else If y = 1 Then _p=2 End If End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "elseIf x = 2 Then" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact()> Public Sub Bug719787_EOF() Dim source = <![CDATA[ Namespace N Class C Property P As Integer End Class Structure S Private F As Object End Structure End Namespace ]]>.Value.Trim() ' Add two line breaks at end. source += vbCrLf Dim position = source.Length source += vbCrLf Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add "Delegate" to end of file between line breaks. Dim newText = oldText.Replace(start:=position, length:=0, newText:="Delegate") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Most of the Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.StructureStatement))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact> Public Sub Bug719787_MultiLineIf() Dim source = <![CDATA[ Class C Sub M() If e1 Then If e2 Then M11() Else M12() End If ElseIf e2 Then If e2 Then M21() Else M22() End If ElseIf e3 Then If e2 Then M31() Else M32() End If ElseIf e4 Then If e2 Then M41() Else M42() End If Else If e2 Then M51() Else M52() End If End If End Sub ' Comment End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim toReplace = "' Comment" Dim position = source.IndexOf(toReplace, StringComparison.Ordinal) ' Replace "' Comment" with "Property" Dim newText = oldText.Replace(start:=position, length:=toReplace.Length, newText:="Property") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' The ElseIfBlocks should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.ElseIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Helpers" Private Shared Function GetTokens(root As SyntaxNode) As InternalSyntax.VisualBasicSyntaxNode() Return root.DescendantTokens().Select(Function(t) DirectCast(t.Node, InternalSyntax.VisualBasicSyntaxNode)).ToArray() End Function Private Shared Sub VerifyTokensEquivalent(rootA As SyntaxNode, rootB As SyntaxNode) Dim tokensA = GetTokens(rootA) Dim tokensB = GetTokens(rootB) Assert.Equal(tokensA.Count, tokensB.Count) For i = 0 To tokensA.Count - 1 Dim tokenA = tokensA(i) Dim tokenB = tokensB(i) Assert.Equal(tokenA.Kind, tokenB.Kind) Assert.Equal(tokenA.ToFullString(), tokenB.ToFullString()) Next End Sub Private Shared Sub VerifyEquivalent(treeA As SyntaxTree, treeB As SyntaxTree) Dim rootA = treeA.GetRoot() Dim rootB = treeB.GetRoot() VerifyTokensEquivalent(rootA, rootB) Dim diagnosticsA = treeA.GetDiagnostics() Dim diagnosticsB = treeB.GetDiagnostics() Assert.True(rootA.IsEquivalentTo(rootB)) Assert.Equal(diagnosticsA.Count, diagnosticsB.Count) For i = 0 To diagnosticsA.Count - 1 Assert.Equal(diagnosticsA(i).Inspect(), diagnosticsB(i).Inspect()) Next End Sub Private Shared Function ToText(code As XCData) As String Dim str = code.Value.Trim() ' Normalize line terminators. Dim builder = ArrayBuilder(Of Char).GetInstance() For i = 0 To str.Length - 1 Dim c = str(i) If (c = vbLf(0)) AndAlso ((i = str.Length - 1) OrElse (str(i + 1) <> vbCr(0))) Then builder.AddRange(vbCrLf) Else builder.Add(c) End If Next Return New String(builder.ToArrayAndFree()) End Function #End Region End Class
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Portable/Emit/SpecializedMethodReference.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.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a method of a generic type instantiation. ''' e.g. ''' A{int}.M() ''' A.B{int}.C.M() ''' </summary> Friend Class SpecializedMethodReference Inherits MethodReference Implements Microsoft.Cci.ISpecializedMethodReference Public Sub New(underlyingMethod As MethodSymbol) MyBase.New(underlyingMethod) End Sub Public Overrides Sub Dispatch(visitor As Microsoft.Cci.MetadataVisitor) visitor.Visit(DirectCast(Me, Microsoft.Cci.ISpecializedMethodReference)) End Sub Private ReadOnly Property ISpecializedMethodReferenceUnspecializedVersion As Microsoft.Cci.IMethodReference Implements Microsoft.Cci.ISpecializedMethodReference.UnspecializedVersion Get Return m_UnderlyingMethod.OriginalDefinition.GetCciAdapter() End Get End Property Public Overrides ReadOnly Property AsSpecializedMethodReference As Microsoft.Cci.ISpecializedMethodReference Get Return Me 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 Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a method of a generic type instantiation. ''' e.g. ''' A{int}.M() ''' A.B{int}.C.M() ''' </summary> Friend Class SpecializedMethodReference Inherits MethodReference Implements Microsoft.Cci.ISpecializedMethodReference Public Sub New(underlyingMethod As MethodSymbol) MyBase.New(underlyingMethod) End Sub Public Overrides Sub Dispatch(visitor As Microsoft.Cci.MetadataVisitor) visitor.Visit(DirectCast(Me, Microsoft.Cci.ISpecializedMethodReference)) End Sub Private ReadOnly Property ISpecializedMethodReferenceUnspecializedVersion As Microsoft.Cci.IMethodReference Implements Microsoft.Cci.ISpecializedMethodReference.UnspecializedVersion Get Return m_UnderlyingMethod.OriginalDefinition.GetCciAdapter() End Get End Property Public Overrides ReadOnly Property AsSpecializedMethodReference As Microsoft.Cci.ISpecializedMethodReference Get Return Me End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Analyzers/Core/Analyzers/NewLines/ConsecutiveStatementPlacement/AbstractConsecutiveStatementPlacementDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement { internal abstract class AbstractConsecutiveStatementPlacementDiagnosticAnalyzer<TExecutableStatementSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TExecutableStatementSyntax : SyntaxNode { private readonly ISyntaxFacts _syntaxFacts; protected AbstractConsecutiveStatementPlacementDiagnosticAnalyzer(ISyntaxFacts syntaxFacts) : base(IDEDiagnosticIds.ConsecutiveStatementPlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveStatementPlacement, CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, LanguageNames.CSharp, new LocalizableResourceString( nameof(AnalyzersResources.Blank_line_required_between_block_and_subsequent_statement), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; } protected abstract bool IsBlockLikeStatement(SyntaxNode node); protected abstract Location GetDiagnosticLocation(SyntaxNode block); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree); private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var cancellationToken = context.CancellationToken; var tree = context.Tree; var option = context.GetOption(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, tree.Options.Language); if (option.Value) return; Recurse(context, option.Notification.Severity, tree.GetRoot(cancellationToken), cancellationToken); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node, CancellationToken cancellationToken) { if (node.ContainsDiagnostics && node.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return; if (IsBlockLikeStatement(node)) ProcessBlockLikeStatement(context, severity, node); foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) Recurse(context, severity, child.AsNode()!, cancellationToken); } } private void ProcessBlockLikeStatement(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode block) { // Don't examine broken blocks. var endToken = block.GetLastToken(); if (endToken.IsMissing) return; // If the close brace itself doesn't have a newline, then ignore this. This is a case of series of // statements on the same line. if (!endToken.TrailingTrivia.Any()) return; if (!_syntaxFacts.IsEndOfLineTrivia(endToken.TrailingTrivia.Last())) return; // Grab whatever comes after the close brace. If it's not the start of a statement, ignore it. var nextToken = endToken.GetNextToken(); var nextTokenContainingStatement = nextToken.Parent?.FirstAncestorOrSelf<TExecutableStatementSyntax>(); if (nextTokenContainingStatement == null) return; if (nextToken != nextTokenContainingStatement.GetFirstToken()) return; // There has to be at least a blank line between the end of the block and the start of the next statement. foreach (var trivia in nextToken.LeadingTrivia) { // If there's a blank line between the brace and the next token, we're all set. if (_syntaxFacts.IsEndOfLineTrivia(trivia)) return; if (_syntaxFacts.IsWhitespaceTrivia(trivia)) continue; // got something that wasn't whitespace. Bail out as we don't want to place any restrictions on this code. return; } context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, GetDiagnosticLocation(block), severity, additionalLocations: ImmutableArray.Create(nextToken.GetLocation()), properties: 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. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement { internal abstract class AbstractConsecutiveStatementPlacementDiagnosticAnalyzer<TExecutableStatementSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TExecutableStatementSyntax : SyntaxNode { private readonly ISyntaxFacts _syntaxFacts; protected AbstractConsecutiveStatementPlacementDiagnosticAnalyzer(ISyntaxFacts syntaxFacts) : base(IDEDiagnosticIds.ConsecutiveStatementPlacementDiagnosticId, EnforceOnBuildValues.ConsecutiveStatementPlacement, CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, LanguageNames.CSharp, new LocalizableResourceString( nameof(AnalyzersResources.Blank_line_required_between_block_and_subsequent_statement), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; } protected abstract bool IsBlockLikeStatement(SyntaxNode node); protected abstract Location GetDiagnosticLocation(SyntaxNode block); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree); private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var cancellationToken = context.CancellationToken; var tree = context.Tree; var option = context.GetOption(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, tree.Options.Language); if (option.Value) return; Recurse(context, option.Notification.Severity, tree.GetRoot(cancellationToken), cancellationToken); } private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node, CancellationToken cancellationToken) { if (node.ContainsDiagnostics && node.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return; if (IsBlockLikeStatement(node)) ProcessBlockLikeStatement(context, severity, node); foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) Recurse(context, severity, child.AsNode()!, cancellationToken); } } private void ProcessBlockLikeStatement(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode block) { // Don't examine broken blocks. var endToken = block.GetLastToken(); if (endToken.IsMissing) return; // If the close brace itself doesn't have a newline, then ignore this. This is a case of series of // statements on the same line. if (!endToken.TrailingTrivia.Any()) return; if (!_syntaxFacts.IsEndOfLineTrivia(endToken.TrailingTrivia.Last())) return; // Grab whatever comes after the close brace. If it's not the start of a statement, ignore it. var nextToken = endToken.GetNextToken(); var nextTokenContainingStatement = nextToken.Parent?.FirstAncestorOrSelf<TExecutableStatementSyntax>(); if (nextTokenContainingStatement == null) return; if (nextToken != nextTokenContainingStatement.GetFirstToken()) return; // There has to be at least a blank line between the end of the block and the start of the next statement. foreach (var trivia in nextToken.LeadingTrivia) { // If there's a blank line between the brace and the next token, we're all set. if (_syntaxFacts.IsEndOfLineTrivia(trivia)) return; if (_syntaxFacts.IsWhitespaceTrivia(trivia)) continue; // got something that wasn't whitespace. Bail out as we don't want to place any restrictions on this code. return; } context.ReportDiagnostic(DiagnosticHelper.Create( this.Descriptor, GetDiagnosticLocation(block), severity, additionalLocations: ImmutableArray.Create(nextToken.GetLocation()), properties: null)); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/VisualBasicTest/Recommendations/Queries/EqualsKeywordRecommenderTests.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.UnitTests.Recommendations.Queries Public Class EqualsKeywordRecommenderTests <WorkItem(543136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543136")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EqualsAfterJoinInOnIdentifierTest() Dim method = <MethodBody> Dim arr = New Integer() {4, 5} Dim q2 = From num In arr Join n1 In arr On num | </MethodBody> VerifyRecommendationsAreExactly(method, "Equals") End Sub <WorkItem(543136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543136")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EqualsAfterJoinInOnBinaryExpressionTest() Dim method = <MethodBody> Dim arr = New Integer() {4, 5} Dim q2 = From num In arr Join n1 In arr On num + 5L | </MethodBody> VerifyRecommendationsAreExactly(method, "Equals") 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Queries Public Class EqualsKeywordRecommenderTests <WorkItem(543136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543136")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EqualsAfterJoinInOnIdentifierTest() Dim method = <MethodBody> Dim arr = New Integer() {4, 5} Dim q2 = From num In arr Join n1 In arr On num | </MethodBody> VerifyRecommendationsAreExactly(method, "Equals") End Sub <WorkItem(543136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543136")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EqualsAfterJoinInOnBinaryExpressionTest() Dim method = <MethodBody> Dim arr = New Integer() {4, 5} Dim q2 = From num In arr Join n1 In arr On num + 5L | </MethodBody> VerifyRecommendationsAreExactly(method, "Equals") End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/ExtractMethod/VariableStyle.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.ExtractMethod { internal class VariableStyle { public ParameterStyle ParameterStyle { get; private set; } public ReturnStyle ReturnStyle { get; private set; } public static readonly VariableStyle None = new VariableStyle() { ParameterStyle = ParameterStyle.None, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle InputOnly = new VariableStyle() { ParameterStyle = ParameterStyle.InputOnly, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle Delete = new VariableStyle() { ParameterStyle = ParameterStyle.Delete, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle MoveOut = new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle SplitOut = new VariableStyle() { ParameterStyle = ParameterStyle.SplitOut, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle MoveIn = new VariableStyle() { ParameterStyle = ParameterStyle.MoveIn, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle SplitIn = new VariableStyle() { ParameterStyle = ParameterStyle.SplitIn, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle NotUsed = new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.Initialization }; public static readonly VariableStyle Ref = new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.AssignmentWithInput }; public static readonly VariableStyle OnlyAsRefParam = new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle Out = new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithNoInput }; public static readonly VariableStyle OutWithErrorInput = new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithInput }; public static readonly VariableStyle OutWithMoveOut = new VariableStyle() { ParameterStyle = ParameterStyle.OutWithMoveOut, ReturnStyle = ReturnStyle.Initialization }; } }
// Licensed to the .NET Foundation under one or more 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.ExtractMethod { internal class VariableStyle { public ParameterStyle ParameterStyle { get; private set; } public ReturnStyle ReturnStyle { get; private set; } public static readonly VariableStyle None = new VariableStyle() { ParameterStyle = ParameterStyle.None, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle InputOnly = new VariableStyle() { ParameterStyle = ParameterStyle.InputOnly, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle Delete = new VariableStyle() { ParameterStyle = ParameterStyle.Delete, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle MoveOut = new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle SplitOut = new VariableStyle() { ParameterStyle = ParameterStyle.SplitOut, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle MoveIn = new VariableStyle() { ParameterStyle = ParameterStyle.MoveIn, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle SplitIn = new VariableStyle() { ParameterStyle = ParameterStyle.SplitIn, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle NotUsed = new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.Initialization }; public static readonly VariableStyle Ref = new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.AssignmentWithInput }; public static readonly VariableStyle OnlyAsRefParam = new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.None }; public static readonly VariableStyle Out = new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithNoInput }; public static readonly VariableStyle OutWithErrorInput = new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithInput }; public static readonly VariableStyle OutWithMoveOut = new VariableStyle() { ParameterStyle = ParameterStyle.OutWithMoveOut, ReturnStyle = ReturnStyle.Initialization }; } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Test/Syntax/Parser/XmlDocComments.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 Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseXmlDocComments Inherits BasicTestBase <Fact()> Public Sub ParseOneLineText() ParseAndVerify(<![CDATA[ ''' hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocText() ParseAndVerify(<![CDATA['''hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocElement() ParseAndVerify(<![CDATA['''<qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocComment() ParseAndVerify(<![CDATA['''<!-- qqqqq --> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultilineXmlDocElement() ParseAndVerify(<![CDATA[ ''' '''<qqq> '''<aaa>blah '''</aaa> '''</qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultiLineText() Dim multiline = ParseAndVerify(<![CDATA[ ''' hello doc comments! ''' hello doc comments! Module m1 End Module ]]>).GetRoot() Dim comments = multiline.GetFirstToken.LeadingTrivia Assert.Equal(4, comments.Count) Dim struct = DirectCast(comments(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.DoesNotContain(vbCr, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.DoesNotContain(vbLf, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.Equal(" hello doc comments! hello doc comments!", struct.GetInteriorXml) End Sub <Fact> Public Sub ParseOneLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ", txt) End Sub <Fact()> Public Sub ParseTwoLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim docComment1 = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.Same(docComment, docComment1) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> " & " hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>", txt) End Sub <Fact> Public Sub XmlDocCommentsSpanLines() ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq '''--> <qqq> blah </qqq> ''' hello doc comments! <!-- ''' qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub XmlDocCommentsAttrSpanLines() ParseAndVerify(<![CDATA[ ''' <qqq a '''= ''' '''" '''h ''' &lt; ''' " '''> blah </qqq> Module m1 End Module ]]>) End Sub <WorkItem(893656, "DevDiv/Personal")> <WorkItem(923711, "DevDiv/Personal")> <Fact> Public Sub TickTickTickKind() ParseAndVerify( " '''<qqq> blah </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlElementStartTag).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & "'''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & " '''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & "'''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & " '''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <WorkItem(900384, "DevDiv/Personal")> <Fact> Public Sub InvalidCastExceptionWithEvent() ParseAndVerify(<![CDATA[Class Goo ''' <summary> ''' Goo ''' </summary> Custom Event eventName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class ]]>) End Sub <WorkItem(904414, "DevDiv/Personal")> <Fact> Public Sub ParseMalformedDocComments() ParseAndVerify(<![CDATA[ Module M1 '''<doc> ''' <></> ''' </> '''</doc> '''</root> Sub Main() End Sub End Module Module M2 '''</root> '''<!--* Missing start tag and no content --> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(904903, "DevDiv/Personal")> <Fact> Public Sub ParseShortEndTag() ParseAndVerify(<![CDATA[ '''<qqq> '''<a><b></></> '''</> Module m1 End Module ]]>) End Sub <WorkItem(927580, "DevDiv/Personal")> <WorkItem(927696, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocBadNamespacePrefix() ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>) ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927781, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedEndTag() ParseAndVerify(<![CDATA[Module M1 '''<test> '''</test Sub Main() End Sub '''<doc></doc/> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927785, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedPI() ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, <errors> <error id="30622"/> </errors>) ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="30622"/> </errors>) End Sub <WorkItem(929146, "DevDiv/Personal")> <WorkItem(929147, "DevDiv/Personal")> <WorkItem(929684, "DevDiv/Personal")> <Fact> Public Sub ParseDTDInXmlDoc() ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>) ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(930282, "DevDiv/Personal")> <Fact> Public Sub ParseIncorrectCharactersInDocComment() '!!!!!!!!!!!!!! BELOW TEXT CONTAINS INVISIBLE UNICODE CHARACTERS !!!!!!!!!!!!!! ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>") ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>", VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub Bug16663() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' < 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' </> 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' <?p 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub ParseXmlNameWithLeadingSpaces() ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <WorkItem(547297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547297")> <Fact> Public Sub ParseOpenBracket() ParseAndVerify(<![CDATA[ ''' < Module M End Module ]]>) End Sub <WorkItem(697115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697115")> <Fact()> Public Sub Bug697115() ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.None), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Parse), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) End Sub <WorkItem(697269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697269")> <Fact()> Public Sub Bug697269() ParseAndVerify(<![CDATA[ '''<?a Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<?a '''b c<x/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<x><? Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> </errors>) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestDocumentationComment() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class.\r\n" & "''' </summary>\r\n" & "''' <threadsafety static=""true"" instance=""false""/>\r\n" & "''' <preliminary/>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlThreadSafetyElement(), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPreliminaryElement()) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSummaryElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSeeElementAndXmlSeeAlsoElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class and the <seealso cref=""TypeName2""/> class.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class and the "), SyntaxFactory.XmlSeeAlsoElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName2"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlNewLineElement() Dim expected = "''' <summary>\r\n" & "''' This is a summary.\r\n" & "''' </summary>\r\n" & "''' \r\n" & "''' \r\n" & "''' <remarks>\r\n" & "''' \r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This is a summary."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlParamAndParamRefElement() Dim expected = "''' <summary>\r\n" & "''' <paramref name=""b""/>\r\n" & "''' </summary>\r\n" & "''' <param name=""a""></param>\r\n" & "''' <param name=""b""></param>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamRefElement("b"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("a"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("b")) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlReturnsElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <returns>\r\n" & "''' Returns a value.\r\n" & "''' </returns>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlReturnsElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Returns a value."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlRemarksElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <remarks>\r\n" & "''' Same as in class <see cref=""TypeName""/>.\r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Same as in class "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText("."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlExceptionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <exception cref=""InvalidOperationException"">This exception will be thrown if the object is in an invalid state when calling this method.</exception>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlExceptionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("InvalidOperationException")), SyntaxFactory.XmlText("This exception will be thrown if the object is in an invalid state when calling this method."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlPermissionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <permission cref=""MyPermission"">Needs MyPermission to execute.</permission>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPermissionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("MyPermission")), SyntaxFactory.XmlText("Needs MyPermission to execute."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub End Class
' Licensed to the .NET Foundation under one or more 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 Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseXmlDocComments Inherits BasicTestBase <Fact()> Public Sub ParseOneLineText() ParseAndVerify(<![CDATA[ ''' hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocText() ParseAndVerify(<![CDATA['''hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocElement() ParseAndVerify(<![CDATA['''<qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocComment() ParseAndVerify(<![CDATA['''<!-- qqqqq --> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultilineXmlDocElement() ParseAndVerify(<![CDATA[ ''' '''<qqq> '''<aaa>blah '''</aaa> '''</qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultiLineText() Dim multiline = ParseAndVerify(<![CDATA[ ''' hello doc comments! ''' hello doc comments! Module m1 End Module ]]>).GetRoot() Dim comments = multiline.GetFirstToken.LeadingTrivia Assert.Equal(4, comments.Count) Dim struct = DirectCast(comments(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.DoesNotContain(vbCr, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.DoesNotContain(vbLf, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.Equal(" hello doc comments! hello doc comments!", struct.GetInteriorXml) End Sub <Fact> Public Sub ParseOneLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ", txt) End Sub <Fact()> Public Sub ParseTwoLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim docComment1 = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.Same(docComment, docComment1) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> " & " hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>", txt) End Sub <Fact> Public Sub XmlDocCommentsSpanLines() ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq '''--> <qqq> blah </qqq> ''' hello doc comments! <!-- ''' qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub XmlDocCommentsAttrSpanLines() ParseAndVerify(<![CDATA[ ''' <qqq a '''= ''' '''" '''h ''' &lt; ''' " '''> blah </qqq> Module m1 End Module ]]>) End Sub <WorkItem(893656, "DevDiv/Personal")> <WorkItem(923711, "DevDiv/Personal")> <Fact> Public Sub TickTickTickKind() ParseAndVerify( " '''<qqq> blah </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlElementStartTag).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & "'''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & " '''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & "'''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & " '''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <WorkItem(900384, "DevDiv/Personal")> <Fact> Public Sub InvalidCastExceptionWithEvent() ParseAndVerify(<![CDATA[Class Goo ''' <summary> ''' Goo ''' </summary> Custom Event eventName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class ]]>) End Sub <WorkItem(904414, "DevDiv/Personal")> <Fact> Public Sub ParseMalformedDocComments() ParseAndVerify(<![CDATA[ Module M1 '''<doc> ''' <></> ''' </> '''</doc> '''</root> Sub Main() End Sub End Module Module M2 '''</root> '''<!--* Missing start tag and no content --> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(904903, "DevDiv/Personal")> <Fact> Public Sub ParseShortEndTag() ParseAndVerify(<![CDATA[ '''<qqq> '''<a><b></></> '''</> Module m1 End Module ]]>) End Sub <WorkItem(927580, "DevDiv/Personal")> <WorkItem(927696, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocBadNamespacePrefix() ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>) ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927781, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedEndTag() ParseAndVerify(<![CDATA[Module M1 '''<test> '''</test Sub Main() End Sub '''<doc></doc/> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927785, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedPI() ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, <errors> <error id="30622"/> </errors>) ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="30622"/> </errors>) End Sub <WorkItem(929146, "DevDiv/Personal")> <WorkItem(929147, "DevDiv/Personal")> <WorkItem(929684, "DevDiv/Personal")> <Fact> Public Sub ParseDTDInXmlDoc() ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>) ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(930282, "DevDiv/Personal")> <Fact> Public Sub ParseIncorrectCharactersInDocComment() '!!!!!!!!!!!!!! BELOW TEXT CONTAINS INVISIBLE UNICODE CHARACTERS !!!!!!!!!!!!!! ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>") ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>", VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub Bug16663() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' < 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' </> 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' <?p 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub ParseXmlNameWithLeadingSpaces() ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <WorkItem(547297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547297")> <Fact> Public Sub ParseOpenBracket() ParseAndVerify(<![CDATA[ ''' < Module M End Module ]]>) End Sub <WorkItem(697115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697115")> <Fact()> Public Sub Bug697115() ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.None), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Parse), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) End Sub <WorkItem(697269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697269")> <Fact()> Public Sub Bug697269() ParseAndVerify(<![CDATA[ '''<?a Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<?a '''b c<x/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<x><? Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> </errors>) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestDocumentationComment() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class.\r\n" & "''' </summary>\r\n" & "''' <threadsafety static=""true"" instance=""false""/>\r\n" & "''' <preliminary/>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlThreadSafetyElement(), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPreliminaryElement()) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSummaryElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSeeElementAndXmlSeeAlsoElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class and the <seealso cref=""TypeName2""/> class.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class and the "), SyntaxFactory.XmlSeeAlsoElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName2"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlNewLineElement() Dim expected = "''' <summary>\r\n" & "''' This is a summary.\r\n" & "''' </summary>\r\n" & "''' \r\n" & "''' \r\n" & "''' <remarks>\r\n" & "''' \r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This is a summary."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlParamAndParamRefElement() Dim expected = "''' <summary>\r\n" & "''' <paramref name=""b""/>\r\n" & "''' </summary>\r\n" & "''' <param name=""a""></param>\r\n" & "''' <param name=""b""></param>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamRefElement("b"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("a"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("b")) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlReturnsElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <returns>\r\n" & "''' Returns a value.\r\n" & "''' </returns>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlReturnsElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Returns a value."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlRemarksElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <remarks>\r\n" & "''' Same as in class <see cref=""TypeName""/>.\r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Same as in class "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText("."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlExceptionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <exception cref=""InvalidOperationException"">This exception will be thrown if the object is in an invalid state when calling this method.</exception>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlExceptionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("InvalidOperationException")), SyntaxFactory.XmlText("This exception will be thrown if the object is in an invalid state when calling this method."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlPermissionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <permission cref=""MyPermission"">Needs MyPermission to execute.</permission>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPermissionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("MyPermission")), SyntaxFactory.XmlText("Needs MyPermission to execute."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub End Class
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Analyzers/CSharp/Analyzers/FileHeaders/CSharpFileHeaderHelper.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 Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.FileHeaders; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FileHeaders { /// <summary> /// Helper class used for working with file headers. /// </summary> internal sealed class CSharpFileHeaderHelper : AbstractFileHeaderHelper { public static readonly CSharpFileHeaderHelper Instance = new(); private CSharpFileHeaderHelper() : base(CSharpSyntaxKinds.Instance) { } public override string CommentPrefix => "//"; protected override ReadOnlyMemory<char> GetTextContextOfComment(SyntaxTrivia commentTrivia) { if (commentTrivia.IsKind(SyntaxKind.SingleLineCommentTrivia)) { return commentTrivia.ToFullString().AsMemory()[2..]; } else if (commentTrivia.IsKind(SyntaxKind.MultiLineCommentTrivia)) { var triviaString = commentTrivia.ToFullString(); var startIndex = triviaString.IndexOf("/*", StringComparison.Ordinal) + 2; var endIndex = triviaString.LastIndexOf("*/", StringComparison.Ordinal); if (endIndex < startIndex) { // While editing, it is possible to have a multiline comment trivia that does not contain the closing '*/' yet. return triviaString.AsMemory()[startIndex..]; } return triviaString.AsMemory()[startIndex..endIndex]; } else { throw ExceptionUtilities.UnexpectedValue(commentTrivia.Kind()); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.FileHeaders; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FileHeaders { /// <summary> /// Helper class used for working with file headers. /// </summary> internal sealed class CSharpFileHeaderHelper : AbstractFileHeaderHelper { public static readonly CSharpFileHeaderHelper Instance = new(); private CSharpFileHeaderHelper() : base(CSharpSyntaxKinds.Instance) { } public override string CommentPrefix => "//"; protected override ReadOnlyMemory<char> GetTextContextOfComment(SyntaxTrivia commentTrivia) { if (commentTrivia.IsKind(SyntaxKind.SingleLineCommentTrivia)) { return commentTrivia.ToFullString().AsMemory()[2..]; } else if (commentTrivia.IsKind(SyntaxKind.MultiLineCommentTrivia)) { var triviaString = commentTrivia.ToFullString(); var startIndex = triviaString.IndexOf("/*", StringComparison.Ordinal) + 2; var endIndex = triviaString.LastIndexOf("*/", StringComparison.Ordinal); if (endIndex < startIndex) { // While editing, it is possible to have a multiline comment trivia that does not contain the closing '*/' yet. return triviaString.AsMemory()[startIndex..]; } return triviaString.AsMemory()[startIndex..endIndex]; } else { throw ExceptionUtilities.UnexpectedValue(commentTrivia.Kind()); } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpCompilation { internal readonly WellKnownMembersSignatureComparer WellKnownMemberSignatureComparer; /// <summary> /// An array of cached well known types available for use in this Compilation. /// Lazily filled by GetWellKnownType method. /// </summary> private NamedTypeSymbol?[]? _lazyWellKnownTypes; /// <summary> /// Lazy cache of well known members. /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol?[]? _lazyWellKnownTypeMembers; private bool _usesNullableAttributes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return (EmbeddableAttributes)_needsGeneratedAttributes; } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal bool GetUsesNullableAttributes() { _needsGeneratedAttributes_IsFrozen = true; return _usesNullableAttributes; } private void SetUsesNullableAttributes() { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); _usesNullableAttributes = true; } /// <summary> /// Lookup member declaration in well known type used by this Compilation. /// </summary> /// <remarks> /// If a well-known member of a generic type instantiation is needed use this method to get the corresponding generic definition and /// <see cref="MethodSymbol.AsMember"/> to construct an instantiation. /// </remarks> internal Symbol? GetWellKnownTypeMember(WellKnownMember member) { Debug.Assert(member >= 0 && member < WellKnownMember.Count); // Test hook: if a member is marked missing, then return null. if (IsMemberMissing(member)) return null; if (_lazyWellKnownTypeMembers == null || ReferenceEquals(_lazyWellKnownTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazyWellKnownTypeMembers == null) { var wellKnownTypeMembers = new Symbol[(int)WellKnownMember.Count]; for (int i = 0; i < wellKnownTypeMembers.Length; i++) { wellKnownTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers, wellKnownTypeMembers, null); } MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(member); NamedTypeSymbol type = descriptor.DeclaringTypeId <= (int)SpecialType.Count ? this.GetSpecialType((SpecialType)descriptor.DeclaringTypeId) : this.GetWellKnownType((WellKnownType)descriptor.DeclaringTypeId); Symbol? result = null; if (!type.IsErrorType()) { result = GetRuntimeMember(type, descriptor, WellKnownMemberSignatureComparer, accessWithinOpt: this.Assembly); } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazyWellKnownTypeMembers[(int)member]; } /// <summary> /// This method handles duplicate types in a few different ways: /// - for types before C# 7, the first candidate is returned with a warning /// - for types after C# 7, the type is considered missing /// - in both cases, when BinderFlags.IgnoreCorLibraryDuplicatedTypes is set, type from corlib will not count as a duplicate /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type) { Debug.Assert(type.IsValid()); bool ignoreCorLibraryDuplicatedTypes = this.Options.TopLevelBinderFlags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes); int index = (int)type - (int)WellKnownType.First; if (_lazyWellKnownTypes == null || _lazyWellKnownTypes[index] is null) { if (_lazyWellKnownTypes == null) { Interlocked.CompareExchange(ref _lazyWellKnownTypes, new NamedTypeSymbol[(int)WellKnownTypes.Count], null); } string mdName = type.GetMetadataName(); var warnings = DiagnosticBag.GetInstance(); NamedTypeSymbol? result; (AssemblySymbol, AssemblySymbol) conflicts = default; if (IsTypeMissing(type)) { result = null; } else { // well-known types introduced before CSharp7 allow lookup ambiguity and report a warning DiagnosticBag? legacyWarnings = (type <= WellKnownType.CSharp7Sentinel) ? warnings : null; result = this.Assembly.GetTypeByMetadataName( mdName, includeReferences: true, useCLSCompliantNameArityEncoding: true, isWellKnownType: true, conflicts: out conflicts, warnings: legacyWarnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); } if (result is null) { // TODO: should GetTypeByMetadataName rather return a missing symbol? MetadataTypeName emittedName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding: true); if (type.IsValueTupleType()) { CSDiagnosticInfo errorInfo; if (conflicts.Item1 is null) { Debug.Assert(conflicts.Item2 is null); errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, emittedName.FullName); } else { errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, emittedName.FullName, conflicts.Item1, conflicts.Item2); } result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type, errorInfo); } else { result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type); } } if (Interlocked.CompareExchange(ref _lazyWellKnownTypes[index], result, null) is object) { Debug.Assert( TypeSymbol.Equals(result, _lazyWellKnownTypes[index], TypeCompareKind.ConsiderEverything2) || (_lazyWellKnownTypes[index]!.IsErrorType() && result.IsErrorType()) ); } else { AdditionalCodegenWarnings.AddRange(warnings); } warnings.Free(); } return _lazyWellKnownTypes[index]!; } internal bool IsAttributeType(TypeSymbol type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Attribute, ref discardedUseSiteInfo); } internal override bool IsAttributeType(ITypeSymbol type) { return IsAttributeType(type.EnsureCSharpSymbolOrNull(nameof(type))); } internal bool IsExceptionType(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Exception, ref useSiteInfo); } internal bool IsReadOnlySpanType(TypeSymbol type) { return TypeSymbol.Equals(type.OriginalDefinition, GetWellKnownType(WellKnownType.System_ReadOnlySpan_T), TypeCompareKind.ConsiderEverything2); } internal bool IsEqualOrDerivedFromWellKnownClass(TypeSymbol type, WellKnownType wellKnownType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(wellKnownType == WellKnownType.System_Attribute || wellKnownType == WellKnownType.System_Exception); if (type.Kind != SymbolKind.NamedType || type.TypeKind != TypeKind.Class) { return false; } var wkType = GetWellKnownType(wellKnownType); return type.Equals(wkType, TypeCompareKind.ConsiderEverything) || type.IsDerivedFrom(wkType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo); } internal override bool IsSystemTypeReference(ITypeSymbolInternal type) { return TypeSymbol.Equals((TypeSymbol)type, GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything2); } internal override ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member) { return GetWellKnownTypeMember(member); } internal override ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType) { return GetWellKnownType(wellknownType); } internal static Symbol? GetRuntimeMember(NamedTypeSymbol declaringType, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { var members = declaringType.GetMembers(descriptor.Name); return GetRuntimeMember(members, descriptor, comparer, accessWithinOpt); } internal static Symbol? GetRuntimeMember(ImmutableArray<Symbol> members, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { SymbolKind targetSymbolKind; MethodKind targetMethodKind = MethodKind.Ordinary; bool isStatic = (descriptor.Flags & MemberFlags.Static) != 0; Symbol? result = null; switch (descriptor.Flags & MemberFlags.KindMask) { case MemberFlags.Constructor: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.Constructor; // static constructors are never called explicitly Debug.Assert(!isStatic); break; case MemberFlags.Method: targetSymbolKind = SymbolKind.Method; break; case MemberFlags.PropertyGet: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.PropertyGet; break; case MemberFlags.Field: targetSymbolKind = SymbolKind.Field; break; case MemberFlags.Property: targetSymbolKind = SymbolKind.Property; break; default: throw ExceptionUtilities.UnexpectedValue(descriptor.Flags); } foreach (var member in members) { if (!member.Name.Equals(descriptor.Name)) { continue; } if (member.Kind != targetSymbolKind || member.IsStatic != isStatic || !(member.DeclaredAccessibility == Accessibility.Public || (accessWithinOpt is object && Symbol.IsSymbolAccessible(member, accessWithinOpt)))) { continue; } switch (targetSymbolKind) { case SymbolKind.Method: { MethodSymbol method = (MethodSymbol)member; MethodKind methodKind = method.MethodKind; // Treat user-defined conversions and operators as ordinary methods for the purpose // of matching them here. if (methodKind == MethodKind.Conversion || methodKind == MethodKind.UserDefinedOperator) { methodKind = MethodKind.Ordinary; } if (method.Arity != descriptor.Arity || methodKind != targetMethodKind || ((descriptor.Flags & MemberFlags.Virtual) != 0) != (method.IsVirtual || method.IsOverride || method.IsAbstract)) { continue; } if (!comparer.MatchMethodSignature(method, descriptor.Signature)) { continue; } } break; case SymbolKind.Property: { PropertySymbol property = (PropertySymbol)member; if (((descriptor.Flags & MemberFlags.Virtual) != 0) != (property.IsVirtual || property.IsOverride || property.IsAbstract)) { continue; } if (!comparer.MatchPropertySignature(property, descriptor.Signature)) { continue; } } break; case SymbolKind.Field: if (!comparer.MatchFieldSignature((FieldSymbol)member, descriptor.Signature)) { continue; } break; default: throw ExceptionUtilities.UnexpectedValue(targetSymbolKind); } // ambiguity if (result is object) { result = null; break; } result = member; } return result; } /// <summary> /// Synthesizes a custom attribute. /// Returns null if the <paramref name="constructor"/> symbol is missing, /// or any of the members in <paramref name="namedArguments" /> are missing. /// The attribute is synthesized only if present. /// </summary> /// <param name="constructor"> /// Constructor of the attribute. If it doesn't exist, the attribute is not created. /// </param> /// <param name="arguments">Arguments to the attribute constructor.</param> /// <param name="namedArguments"> /// Takes a list of pairs of well-known members and constants. The constants /// will be passed to the field/property referenced by the well-known member. /// If the well-known member does not exist in the compilation then no attribute /// will be synthesized. /// </param> /// <param name="isOptionalUse"> /// Indicates if this particular attribute application should be considered optional. /// </param> internal SynthesizedAttributeData? TrySynthesizeAttribute( WellKnownMember constructor, ImmutableArray<TypedConstant> arguments = default, ImmutableArray<KeyValuePair<WellKnownMember, TypedConstant>> namedArguments = default, bool isOptionalUse = false) { UseSiteInfo<AssemblySymbol> info; var ctorSymbol = (MethodSymbol)Binder.GetWellKnownTypeMember(this, constructor, out info, isOptional: true); if ((object)ctorSymbol == null) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(isOptionalUse || WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } if (arguments.IsDefault) { arguments = ImmutableArray<TypedConstant>.Empty; } ImmutableArray<KeyValuePair<string, TypedConstant>> namedStringArguments; if (namedArguments.IsDefault) { namedStringArguments = ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty; } else { var builder = new ArrayBuilder<KeyValuePair<string, TypedConstant>>(namedArguments.Length); foreach (var arg in namedArguments) { var wellKnownMember = Binder.GetWellKnownTypeMember(this, arg.Key, out info, isOptional: true); if (wellKnownMember == null || wellKnownMember is ErrorTypeSymbol) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } else { builder.Add(new KeyValuePair<string, TypedConstant>( wellKnownMember.Name, arg.Value)); } } namedStringArguments = builder.ToImmutableAndFree(); } return new SynthesizedAttributeData(ctorSymbol, arguments, namedStringArguments); } internal SynthesizedAttributeData? TrySynthesizeAttribute( SpecialMember constructor, bool isOptionalUse = false) { var ctorSymbol = (MethodSymbol)this.GetSpecialTypeMember(constructor); if ((object)ctorSymbol == null) { Debug.Assert(isOptionalUse); return null; } return new SynthesizedAttributeData( ctorSymbol, arguments: ImmutableArray<TypedConstant>.Empty, namedArguments: ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } internal SynthesizedAttributeData? SynthesizeDecimalConstantAttribute(decimal value) { bool isNegative; byte scale; uint low, mid, high; value.GetBits(out isNegative, out scale, out low, out mid, out high); var systemByte = GetSpecialType(SpecialType.System_Byte); Debug.Assert(!systemByte.HasUseSiteError); var systemUnit32 = GetSpecialType(SpecialType.System_UInt32); Debug.Assert(!systemUnit32.HasUseSiteError); return TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, ImmutableArray.Create( new TypedConstant(systemByte, TypedConstantKind.Primitive, scale), new TypedConstant(systemByte, TypedConstantKind.Primitive, (byte)(isNegative ? 128 : 0)), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, high), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, mid), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, low) )); } internal SynthesizedAttributeData? SynthesizeDebuggerBrowsableNeverAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create(new TypedConstant( GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState), TypedConstantKind.Enum, DebuggerBrowsableState.Never))); } internal SynthesizedAttributeData? SynthesizeDebuggerStepThroughAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { Debug.Assert(!modifyCompilation || !_needsGeneratedAttributes_IsFrozen); if (CheckIfAttributeShouldBeEmbedded(attribute, diagnostics, location) && modifyCompilation) { SetNeedsGeneratedAttributes(attribute); } if ((attribute & (EmbeddableAttributes.NullableAttribute | EmbeddableAttributes.NullableContextAttribute)) != 0 && modifyCompilation) { SetUsesNullableAttributes(); } } internal void EnsureIsReadOnlyAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsByRefLikeAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsByRefLikeAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsUnmanagedAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableContextAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNativeIntegerAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute, diagnostics, location, modifyCompilation); } internal bool CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnosticsOpt, Location locationOpt) { switch (attribute) { case EmbeddableAttributes.IsReadOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); case EmbeddableAttributes.IsByRefLikeAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); case EmbeddableAttributes.IsUnmanagedAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); case EmbeddableAttributes.NullableAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags); case EmbeddableAttributes.NullableContextAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor); case EmbeddableAttributes.NullablePublicOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor); case EmbeddableAttributes.NativeIntegerAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags); default: throw ExceptionUtilities.UnexpectedValue(attribute); } } private bool CheckIfAttributeShouldBeEmbedded(BindingDiagnosticBag? diagnosticsOpt, Location? locationOpt, WellKnownType attributeType, WellKnownMember attributeCtor, WellKnownMember? secondAttributeCtor = null) { var userDefinedAttribute = GetWellKnownType(attributeType); if (userDefinedAttribute is MissingMetadataTypeSymbol) { if (Options.OutputKind == OutputKind.NetModule) { if (diagnosticsOpt != null) { var errorReported = Binder.ReportUseSite(userDefinedAttribute, diagnosticsOpt, locationOpt); Debug.Assert(errorReported); } } else { return true; } } else if (diagnosticsOpt != null) { // This should produce diagnostics if the member is missing or bad var member = Binder.GetWellKnownTypeMember(this, attributeCtor, diagnosticsOpt, locationOpt); if (member != null && secondAttributeCtor != null) { Binder.GetWellKnownTypeMember(this, secondAttributeCtor.Value, diagnosticsOpt, locationOpt); } } return false; } internal SynthesizedAttributeData? SynthesizeDebuggableAttribute() { TypeSymbol debuggableAttribute = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute); Debug.Assert((object)debuggableAttribute != null, "GetWellKnownType unexpectedly returned null"); if (debuggableAttribute is MissingMetadataTypeSymbol) { return null; } TypeSymbol debuggingModesType = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes); RoslynDebug.Assert((object)debuggingModesType != null, "GetWellKnownType unexpectedly returned null"); if (debuggingModesType is MissingMetadataTypeSymbol) { return null; } // IgnoreSymbolStoreDebuggingMode flag is checked by the CLR, it is not referred to by the debugger. // It tells the JIT that it doesn't need to load the PDB at the time it generates jitted code. // The PDB would still be used by a debugger, or even by the runtime for putting source line information // on exception stack traces. We always set this flag to avoid overhead of JIT loading the PDB. // The theoretical scenario for not setting it would be a language compiler that wants their sequence points // at specific places, but those places don't match what CLR's heuristics calculate when scanning the IL. var ignoreSymbolStoreDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints); if (ignoreSymbolStoreDebuggingMode is null || !ignoreSymbolStoreDebuggingMode.HasConstantValue) { return null; } int constantVal = ignoreSymbolStoreDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; // Since .NET 2.0 the combinations of None, Default and DisableOptimizations have the following effect: // // None JIT optimizations enabled // Default JIT optimizations enabled // DisableOptimizations JIT optimizations enabled // Default | DisableOptimizations JIT optimizations disabled if (_options.OptimizationLevel == OptimizationLevel.Debug) { var defaultDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__Default); if (defaultDebuggingMode is null || !defaultDebuggingMode.HasConstantValue) { return null; } var disableOptimizationsDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations); if (disableOptimizationsDebuggingMode is null || !disableOptimizationsDebuggingMode.HasConstantValue) { return null; } constantVal |= defaultDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; constantVal |= disableOptimizationsDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } if (_options.EnableEditAndContinue) { var enableEncDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue); if (enableEncDebuggingMode is null || !enableEncDebuggingMode.HasConstantValue) { return null; } constantVal |= enableEncDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } var typedConstantDebugMode = new TypedConstant(debuggingModesType, TypedConstantKind.Enum, constantVal); return TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes, ImmutableArray.Create(typedConstantDebugMode)); } /// <summary> /// Given a type <paramref name="type"/>, which is either dynamic type OR is a constructed type with dynamic type present in it's type argument tree, /// returns a synthesized DynamicAttribute with encoded dynamic transforms array. /// </summary> /// <remarks>This method is port of AttrBind::CompileDynamicAttr from the native C# compiler.</remarks> internal SynthesizedAttributeData? SynthesizeDynamicAttribute(TypeSymbol type, int customModifiersCount, RefKind refKindOpt = RefKind.None) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsDynamic()); if (type.IsDynamic() && refKindOpt == RefKind.None && customModifiersCount == 0) { return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor); } else { NamedTypeSymbol booleanType = GetSpecialType(SpecialType.System_Boolean); RoslynDebug.Assert((object)booleanType != null); var transformFlags = DynamicTransformsEncoder.Encode(type, refKindOpt, customModifiersCount, booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, arguments); } } internal SynthesizedAttributeData? SynthesizeTupleNamesAttribute(TypeSymbol type) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsTuple()); var stringType = GetSpecialType(SpecialType.System_String); RoslynDebug.Assert((object)stringType != null); var names = TupleNamesEncoder.Encode(type, stringType); Debug.Assert(!names.IsDefault, "should not need the attribute when no tuple names"); var stringArray = ArrayTypeSymbol.CreateSZArray(stringType.ContainingAssembly, TypeWithAnnotations.Create(stringType)); var args = ImmutableArray.Create(new TypedConstant(stringArray, names)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args); } internal SynthesizedAttributeData? SynthesizeAttributeUsageAttribute(AttributeTargets targets, bool allowMultiple, bool inherited) { var attributeTargetsType = GetWellKnownType(WellKnownType.System_AttributeTargets); var boolType = GetSpecialType(SpecialType.System_Boolean); var arguments = ImmutableArray.Create( new TypedConstant(attributeTargetsType, TypedConstantKind.Enum, targets)); var namedArguments = ImmutableArray.Create( new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, new TypedConstant(boolType, TypedConstantKind.Primitive, allowMultiple)), new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__Inherited, new TypedConstant(boolType, TypedConstantKind.Primitive, inherited))); return TrySynthesizeAttribute(WellKnownMember.System_AttributeUsageAttribute__ctor, arguments, namedArguments); } internal static class TupleNamesEncoder { public static ImmutableArray<string?> Encode(TypeSymbol type) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } return namesBuilder.ToImmutableAndFree(); } public static ImmutableArray<TypedConstant> Encode(TypeSymbol type, TypeSymbol stringType) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } var names = namesBuilder.SelectAsArray((name, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, name), stringType); namesBuilder.Free(); return names; } internal static bool TryGetNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { type.VisitType((t, builder, _ignore) => AddNames(t, builder), namesBuilder); return namesBuilder.Any(name => name != null); } private static bool AddNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { if (type.IsTupleType) { if (type.TupleElementNames.IsDefaultOrEmpty) { // If none of the tuple elements have names, put // null placeholders in. // TODO(https://github.com/dotnet/roslyn/issues/12347): // A possible optimization could be to emit an empty attribute // if all the names are missing, but that has to be true // recursively. namesBuilder.AddMany(null, type.TupleElementTypesWithAnnotations.Length); } else { namesBuilder.AddRange(type.TupleElementNames); } } // Always recur into nested types return false; } } /// <summary> /// Used to generate the dynamic attributes for the required typesymbol. /// </summary> internal static class DynamicTransformsEncoder { internal static ImmutableArray<TypedConstant> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount, TypeSymbol booleanType) { var flagsBuilder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, flagsBuilder, addCustomModifierFlags: true); Debug.Assert(flagsBuilder.Any()); Debug.Assert(flagsBuilder.Contains(true)); var result = flagsBuilder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); flagsBuilder.Free(); return result; } internal static ImmutableArray<bool> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, builder, addCustomModifierFlags: true); return builder.ToImmutableAndFree(); } internal static ImmutableArray<bool> EncodeWithoutCustomModifierFlags(TypeSymbol type, RefKind refKind) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, -1, refKind, builder, addCustomModifierFlags: false); return builder.ToImmutableAndFree(); } internal static void Encode(TypeSymbol type, int customModifiersCount, RefKind refKind, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Debug.Assert(!transformFlagsBuilder.Any()); if (refKind != RefKind.None) { // Native compiler encodes an extra transform flag, always false, for ref/out parameters. transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { // Native compiler encodes an extra transform flag, always false, for each custom modifier. HandleCustomModifiers(customModifiersCount, transformFlagsBuilder); type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: true), transformFlagsBuilder); } else { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: false), transformFlagsBuilder); } } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> transformFlagsBuilder, bool isNestedNamedType, bool addCustomModifierFlags) { // Encode transforms flag for this type and its custom modifiers (if any). switch (type.TypeKind) { case TypeKind.Dynamic: transformFlagsBuilder.Add(true); break; case TypeKind.Array: if (addCustomModifierFlags) { HandleCustomModifiers(((ArrayTypeSymbol)type).ElementTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.Pointer: if (addCustomModifierFlags) { HandleCustomModifiers(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.FunctionPointer: Debug.Assert(!isNestedNamedType); handleFunctionPointerType((FunctionPointerTypeSymbol)type, transformFlagsBuilder, addCustomModifierFlags); // Function pointer types have nested custom modifiers and refkinds in line with types, and visit all their nested types // as part of this call. // We need a different way to indicate that we should not recurse for this type, but should continue walking for other // types. https://github.com/dotnet/roslyn/issues/44160 return true; default: // Encode transforms flag for this type. // For nested named types, a single flag (false) is encoded for the entire type name, followed by flags for all of the type arguments. // For example, for type "A<T>.B<dynamic>", encoded transform flags are: // { // false, // Type "A.B" // false, // Type parameter "T" // true, // Type parameter "dynamic" // } if (!isNestedNamedType) { transformFlagsBuilder.Add(false); } break; } // Continue walking types return false; static void handleFunctionPointerType(FunctionPointerTypeSymbol funcPtr, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Func<TypeSymbol, (ArrayBuilder<bool>, bool), bool, bool> visitor = (TypeSymbol type, (ArrayBuilder<bool> builder, bool addCustomModifierFlags) param, bool isNestedNamedType) => AddFlags(type, param.builder, isNestedNamedType, param.addCustomModifierFlags); // The function pointer type itself gets a false transformFlagsBuilder.Add(false); var sig = funcPtr.Signature; handle(sig.RefKind, sig.RefCustomModifiers, sig.ReturnTypeWithAnnotations); foreach (var param in sig.Parameters) { handle(param.RefKind, param.RefCustomModifiers, param.TypeWithAnnotations); } void handle(RefKind refKind, ImmutableArray<CustomModifier> customModifiers, TypeWithAnnotations twa) { if (addCustomModifierFlags) { HandleCustomModifiers(customModifiers.Length, transformFlagsBuilder); } if (refKind != RefKind.None) { transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { HandleCustomModifiers(twa.CustomModifiers.Length, transformFlagsBuilder); } twa.Type.VisitType(visitor, (transformFlagsBuilder, addCustomModifierFlags)); } } } private static void HandleCustomModifiers(int customModifiersCount, ArrayBuilder<bool> transformFlagsBuilder) { // Native compiler encodes an extra transforms flag, always false, for each custom modifier. transformFlagsBuilder.AddMany(false, customModifiersCount); } } internal static class NativeIntegerTransformsEncoder { internal static void Encode(ArrayBuilder<bool> builder, TypeSymbol type) { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder), builder); } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> builder) { switch (type.SpecialType) { case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: builder.Add(type.IsNativeIntegerType); break; } // Continue walking types return false; } } internal class SpecialMembersSignatureComparer : SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> { // Fields public static readonly SpecialMembersSignatureComparer Instance = new SpecialMembersSignatureComparer(); // Methods protected SpecialMembersSignatureComparer() { } protected override TypeSymbol? GetMDArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (array.IsSZArray) { return null; } return array.ElementType; } protected override TypeSymbol GetFieldType(FieldSymbol field) { return field.Type; } protected override TypeSymbol GetPropertyType(PropertySymbol property) { return property.Type; } protected override TypeSymbol? GetGenericTypeArgument(TypeSymbol type, int argumentIndex) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if (named.Arity <= argumentIndex) { return null; } if ((object)named.ContainingType != null) { return null; } return named.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[argumentIndex].Type; } protected override TypeSymbol? GetGenericTypeDefinition(TypeSymbol type) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if ((object)named.ContainingType != null) { return null; } if (named.Arity == 0) { return null; } return (NamedTypeSymbol)named.OriginalDefinition; } protected override ImmutableArray<ParameterSymbol> GetParameters(MethodSymbol method) { return method.Parameters; } protected override ImmutableArray<ParameterSymbol> GetParameters(PropertySymbol property) { return property.Parameters; } protected override TypeSymbol GetParamType(ParameterSymbol parameter) { return parameter.Type; } protected override TypeSymbol? GetPointedToType(TypeSymbol type) { return type.Kind == SymbolKind.PointerType ? ((PointerTypeSymbol)type).PointedAtType : null; } protected override TypeSymbol GetReturnType(MethodSymbol method) { return method.ReturnType; } protected override TypeSymbol? GetSZArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (!array.IsSZArray) { return null; } return array.ElementType; } protected override bool IsByRefParam(ParameterSymbol parameter) { return parameter.RefKind != RefKind.None; } protected override bool IsByRefMethod(MethodSymbol method) { return method.RefKind != RefKind.None; } protected override bool IsByRefProperty(PropertySymbol property) { return property.RefKind != RefKind.None; } protected override bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.Method) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool IsGenericTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.NamedType) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool MatchArrayRank(TypeSymbol type, int countOfDimensions) { if (type.Kind != SymbolKind.ArrayType) { return false; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; return (array.Rank == countOfDimensions); } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { if ((int)type.OriginalDefinition.SpecialType == typeId) { if (type.IsDefinition) { return true; } return type.Equals(type.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return false; } } internal sealed class WellKnownMembersSignatureComparer : SpecialMembersSignatureComparer { private readonly CSharpCompilation _compilation; public WellKnownMembersSignatureComparer(CSharpCompilation compilation) { _compilation = compilation; } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { WellKnownType wellKnownId = (WellKnownType)typeId; if (wellKnownId.IsWellKnownType()) { return type.Equals(_compilation.GetWellKnownType(wellKnownId), TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return base.MatchTypeToTypeId(type, typeId); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpCompilation { internal readonly WellKnownMembersSignatureComparer WellKnownMemberSignatureComparer; /// <summary> /// An array of cached well known types available for use in this Compilation. /// Lazily filled by GetWellKnownType method. /// </summary> private NamedTypeSymbol?[]? _lazyWellKnownTypes; /// <summary> /// Lazy cache of well known members. /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol?[]? _lazyWellKnownTypeMembers; private bool _usesNullableAttributes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return (EmbeddableAttributes)_needsGeneratedAttributes; } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal bool GetUsesNullableAttributes() { _needsGeneratedAttributes_IsFrozen = true; return _usesNullableAttributes; } private void SetUsesNullableAttributes() { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); _usesNullableAttributes = true; } /// <summary> /// Lookup member declaration in well known type used by this Compilation. /// </summary> /// <remarks> /// If a well-known member of a generic type instantiation is needed use this method to get the corresponding generic definition and /// <see cref="MethodSymbol.AsMember"/> to construct an instantiation. /// </remarks> internal Symbol? GetWellKnownTypeMember(WellKnownMember member) { Debug.Assert(member >= 0 && member < WellKnownMember.Count); // Test hook: if a member is marked missing, then return null. if (IsMemberMissing(member)) return null; if (_lazyWellKnownTypeMembers == null || ReferenceEquals(_lazyWellKnownTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazyWellKnownTypeMembers == null) { var wellKnownTypeMembers = new Symbol[(int)WellKnownMember.Count]; for (int i = 0; i < wellKnownTypeMembers.Length; i++) { wellKnownTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers, wellKnownTypeMembers, null); } MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(member); NamedTypeSymbol type = descriptor.DeclaringTypeId <= (int)SpecialType.Count ? this.GetSpecialType((SpecialType)descriptor.DeclaringTypeId) : this.GetWellKnownType((WellKnownType)descriptor.DeclaringTypeId); Symbol? result = null; if (!type.IsErrorType()) { result = GetRuntimeMember(type, descriptor, WellKnownMemberSignatureComparer, accessWithinOpt: this.Assembly); } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazyWellKnownTypeMembers[(int)member]; } /// <summary> /// This method handles duplicate types in a few different ways: /// - for types before C# 7, the first candidate is returned with a warning /// - for types after C# 7, the type is considered missing /// - in both cases, when BinderFlags.IgnoreCorLibraryDuplicatedTypes is set, type from corlib will not count as a duplicate /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type) { Debug.Assert(type.IsValid()); bool ignoreCorLibraryDuplicatedTypes = this.Options.TopLevelBinderFlags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes); int index = (int)type - (int)WellKnownType.First; if (_lazyWellKnownTypes == null || _lazyWellKnownTypes[index] is null) { if (_lazyWellKnownTypes == null) { Interlocked.CompareExchange(ref _lazyWellKnownTypes, new NamedTypeSymbol[(int)WellKnownTypes.Count], null); } string mdName = type.GetMetadataName(); var warnings = DiagnosticBag.GetInstance(); NamedTypeSymbol? result; (AssemblySymbol, AssemblySymbol) conflicts = default; if (IsTypeMissing(type)) { result = null; } else { // well-known types introduced before CSharp7 allow lookup ambiguity and report a warning DiagnosticBag? legacyWarnings = (type <= WellKnownType.CSharp7Sentinel) ? warnings : null; result = this.Assembly.GetTypeByMetadataName( mdName, includeReferences: true, useCLSCompliantNameArityEncoding: true, isWellKnownType: true, conflicts: out conflicts, warnings: legacyWarnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); } if (result is null) { // TODO: should GetTypeByMetadataName rather return a missing symbol? MetadataTypeName emittedName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding: true); if (type.IsValueTupleType()) { CSDiagnosticInfo errorInfo; if (conflicts.Item1 is null) { Debug.Assert(conflicts.Item2 is null); errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, emittedName.FullName); } else { errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, emittedName.FullName, conflicts.Item1, conflicts.Item2); } result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type, errorInfo); } else { result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type); } } if (Interlocked.CompareExchange(ref _lazyWellKnownTypes[index], result, null) is object) { Debug.Assert( TypeSymbol.Equals(result, _lazyWellKnownTypes[index], TypeCompareKind.ConsiderEverything2) || (_lazyWellKnownTypes[index]!.IsErrorType() && result.IsErrorType()) ); } else { AdditionalCodegenWarnings.AddRange(warnings); } warnings.Free(); } return _lazyWellKnownTypes[index]!; } internal bool IsAttributeType(TypeSymbol type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Attribute, ref discardedUseSiteInfo); } internal override bool IsAttributeType(ITypeSymbol type) { return IsAttributeType(type.EnsureCSharpSymbolOrNull(nameof(type))); } internal bool IsExceptionType(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Exception, ref useSiteInfo); } internal bool IsReadOnlySpanType(TypeSymbol type) { return TypeSymbol.Equals(type.OriginalDefinition, GetWellKnownType(WellKnownType.System_ReadOnlySpan_T), TypeCompareKind.ConsiderEverything2); } internal bool IsEqualOrDerivedFromWellKnownClass(TypeSymbol type, WellKnownType wellKnownType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(wellKnownType == WellKnownType.System_Attribute || wellKnownType == WellKnownType.System_Exception); if (type.Kind != SymbolKind.NamedType || type.TypeKind != TypeKind.Class) { return false; } var wkType = GetWellKnownType(wellKnownType); return type.Equals(wkType, TypeCompareKind.ConsiderEverything) || type.IsDerivedFrom(wkType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo); } internal override bool IsSystemTypeReference(ITypeSymbolInternal type) { return TypeSymbol.Equals((TypeSymbol)type, GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything2); } internal override ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member) { return GetWellKnownTypeMember(member); } internal override ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType) { return GetWellKnownType(wellknownType); } internal static Symbol? GetRuntimeMember(NamedTypeSymbol declaringType, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { var members = declaringType.GetMembers(descriptor.Name); return GetRuntimeMember(members, descriptor, comparer, accessWithinOpt); } internal static Symbol? GetRuntimeMember(ImmutableArray<Symbol> members, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { SymbolKind targetSymbolKind; MethodKind targetMethodKind = MethodKind.Ordinary; bool isStatic = (descriptor.Flags & MemberFlags.Static) != 0; Symbol? result = null; switch (descriptor.Flags & MemberFlags.KindMask) { case MemberFlags.Constructor: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.Constructor; // static constructors are never called explicitly Debug.Assert(!isStatic); break; case MemberFlags.Method: targetSymbolKind = SymbolKind.Method; break; case MemberFlags.PropertyGet: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.PropertyGet; break; case MemberFlags.Field: targetSymbolKind = SymbolKind.Field; break; case MemberFlags.Property: targetSymbolKind = SymbolKind.Property; break; default: throw ExceptionUtilities.UnexpectedValue(descriptor.Flags); } foreach (var member in members) { if (!member.Name.Equals(descriptor.Name)) { continue; } if (member.Kind != targetSymbolKind || member.IsStatic != isStatic || !(member.DeclaredAccessibility == Accessibility.Public || (accessWithinOpt is object && Symbol.IsSymbolAccessible(member, accessWithinOpt)))) { continue; } switch (targetSymbolKind) { case SymbolKind.Method: { MethodSymbol method = (MethodSymbol)member; MethodKind methodKind = method.MethodKind; // Treat user-defined conversions and operators as ordinary methods for the purpose // of matching them here. if (methodKind == MethodKind.Conversion || methodKind == MethodKind.UserDefinedOperator) { methodKind = MethodKind.Ordinary; } if (method.Arity != descriptor.Arity || methodKind != targetMethodKind || ((descriptor.Flags & MemberFlags.Virtual) != 0) != (method.IsVirtual || method.IsOverride || method.IsAbstract)) { continue; } if (!comparer.MatchMethodSignature(method, descriptor.Signature)) { continue; } } break; case SymbolKind.Property: { PropertySymbol property = (PropertySymbol)member; if (((descriptor.Flags & MemberFlags.Virtual) != 0) != (property.IsVirtual || property.IsOverride || property.IsAbstract)) { continue; } if (!comparer.MatchPropertySignature(property, descriptor.Signature)) { continue; } } break; case SymbolKind.Field: if (!comparer.MatchFieldSignature((FieldSymbol)member, descriptor.Signature)) { continue; } break; default: throw ExceptionUtilities.UnexpectedValue(targetSymbolKind); } // ambiguity if (result is object) { result = null; break; } result = member; } return result; } /// <summary> /// Synthesizes a custom attribute. /// Returns null if the <paramref name="constructor"/> symbol is missing, /// or any of the members in <paramref name="namedArguments" /> are missing. /// The attribute is synthesized only if present. /// </summary> /// <param name="constructor"> /// Constructor of the attribute. If it doesn't exist, the attribute is not created. /// </param> /// <param name="arguments">Arguments to the attribute constructor.</param> /// <param name="namedArguments"> /// Takes a list of pairs of well-known members and constants. The constants /// will be passed to the field/property referenced by the well-known member. /// If the well-known member does not exist in the compilation then no attribute /// will be synthesized. /// </param> /// <param name="isOptionalUse"> /// Indicates if this particular attribute application should be considered optional. /// </param> internal SynthesizedAttributeData? TrySynthesizeAttribute( WellKnownMember constructor, ImmutableArray<TypedConstant> arguments = default, ImmutableArray<KeyValuePair<WellKnownMember, TypedConstant>> namedArguments = default, bool isOptionalUse = false) { UseSiteInfo<AssemblySymbol> info; var ctorSymbol = (MethodSymbol)Binder.GetWellKnownTypeMember(this, constructor, out info, isOptional: true); if ((object)ctorSymbol == null) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(isOptionalUse || WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } if (arguments.IsDefault) { arguments = ImmutableArray<TypedConstant>.Empty; } ImmutableArray<KeyValuePair<string, TypedConstant>> namedStringArguments; if (namedArguments.IsDefault) { namedStringArguments = ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty; } else { var builder = new ArrayBuilder<KeyValuePair<string, TypedConstant>>(namedArguments.Length); foreach (var arg in namedArguments) { var wellKnownMember = Binder.GetWellKnownTypeMember(this, arg.Key, out info, isOptional: true); if (wellKnownMember == null || wellKnownMember is ErrorTypeSymbol) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } else { builder.Add(new KeyValuePair<string, TypedConstant>( wellKnownMember.Name, arg.Value)); } } namedStringArguments = builder.ToImmutableAndFree(); } return new SynthesizedAttributeData(ctorSymbol, arguments, namedStringArguments); } internal SynthesizedAttributeData? TrySynthesizeAttribute( SpecialMember constructor, bool isOptionalUse = false) { var ctorSymbol = (MethodSymbol)this.GetSpecialTypeMember(constructor); if ((object)ctorSymbol == null) { Debug.Assert(isOptionalUse); return null; } return new SynthesizedAttributeData( ctorSymbol, arguments: ImmutableArray<TypedConstant>.Empty, namedArguments: ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } internal SynthesizedAttributeData? SynthesizeDecimalConstantAttribute(decimal value) { bool isNegative; byte scale; uint low, mid, high; value.GetBits(out isNegative, out scale, out low, out mid, out high); var systemByte = GetSpecialType(SpecialType.System_Byte); Debug.Assert(!systemByte.HasUseSiteError); var systemUnit32 = GetSpecialType(SpecialType.System_UInt32); Debug.Assert(!systemUnit32.HasUseSiteError); return TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, ImmutableArray.Create( new TypedConstant(systemByte, TypedConstantKind.Primitive, scale), new TypedConstant(systemByte, TypedConstantKind.Primitive, (byte)(isNegative ? 128 : 0)), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, high), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, mid), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, low) )); } internal SynthesizedAttributeData? SynthesizeDebuggerBrowsableNeverAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create(new TypedConstant( GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState), TypedConstantKind.Enum, DebuggerBrowsableState.Never))); } internal SynthesizedAttributeData? SynthesizeDebuggerStepThroughAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { Debug.Assert(!modifyCompilation || !_needsGeneratedAttributes_IsFrozen); if (CheckIfAttributeShouldBeEmbedded(attribute, diagnostics, location) && modifyCompilation) { SetNeedsGeneratedAttributes(attribute); } if ((attribute & (EmbeddableAttributes.NullableAttribute | EmbeddableAttributes.NullableContextAttribute)) != 0 && modifyCompilation) { SetUsesNullableAttributes(); } } internal void EnsureIsReadOnlyAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsByRefLikeAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsByRefLikeAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsUnmanagedAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableContextAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNativeIntegerAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute, diagnostics, location, modifyCompilation); } internal bool CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnosticsOpt, Location locationOpt) { switch (attribute) { case EmbeddableAttributes.IsReadOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); case EmbeddableAttributes.IsByRefLikeAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); case EmbeddableAttributes.IsUnmanagedAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); case EmbeddableAttributes.NullableAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags); case EmbeddableAttributes.NullableContextAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor); case EmbeddableAttributes.NullablePublicOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor); case EmbeddableAttributes.NativeIntegerAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags); default: throw ExceptionUtilities.UnexpectedValue(attribute); } } private bool CheckIfAttributeShouldBeEmbedded(BindingDiagnosticBag? diagnosticsOpt, Location? locationOpt, WellKnownType attributeType, WellKnownMember attributeCtor, WellKnownMember? secondAttributeCtor = null) { var userDefinedAttribute = GetWellKnownType(attributeType); if (userDefinedAttribute is MissingMetadataTypeSymbol) { if (Options.OutputKind == OutputKind.NetModule) { if (diagnosticsOpt != null) { var errorReported = Binder.ReportUseSite(userDefinedAttribute, diagnosticsOpt, locationOpt); Debug.Assert(errorReported); } } else { return true; } } else if (diagnosticsOpt != null) { // This should produce diagnostics if the member is missing or bad var member = Binder.GetWellKnownTypeMember(this, attributeCtor, diagnosticsOpt, locationOpt); if (member != null && secondAttributeCtor != null) { Binder.GetWellKnownTypeMember(this, secondAttributeCtor.Value, diagnosticsOpt, locationOpt); } } return false; } internal SynthesizedAttributeData? SynthesizeDebuggableAttribute() { TypeSymbol debuggableAttribute = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute); Debug.Assert((object)debuggableAttribute != null, "GetWellKnownType unexpectedly returned null"); if (debuggableAttribute is MissingMetadataTypeSymbol) { return null; } TypeSymbol debuggingModesType = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes); RoslynDebug.Assert((object)debuggingModesType != null, "GetWellKnownType unexpectedly returned null"); if (debuggingModesType is MissingMetadataTypeSymbol) { return null; } // IgnoreSymbolStoreDebuggingMode flag is checked by the CLR, it is not referred to by the debugger. // It tells the JIT that it doesn't need to load the PDB at the time it generates jitted code. // The PDB would still be used by a debugger, or even by the runtime for putting source line information // on exception stack traces. We always set this flag to avoid overhead of JIT loading the PDB. // The theoretical scenario for not setting it would be a language compiler that wants their sequence points // at specific places, but those places don't match what CLR's heuristics calculate when scanning the IL. var ignoreSymbolStoreDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints); if (ignoreSymbolStoreDebuggingMode is null || !ignoreSymbolStoreDebuggingMode.HasConstantValue) { return null; } int constantVal = ignoreSymbolStoreDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; // Since .NET 2.0 the combinations of None, Default and DisableOptimizations have the following effect: // // None JIT optimizations enabled // Default JIT optimizations enabled // DisableOptimizations JIT optimizations enabled // Default | DisableOptimizations JIT optimizations disabled if (_options.OptimizationLevel == OptimizationLevel.Debug) { var defaultDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__Default); if (defaultDebuggingMode is null || !defaultDebuggingMode.HasConstantValue) { return null; } var disableOptimizationsDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations); if (disableOptimizationsDebuggingMode is null || !disableOptimizationsDebuggingMode.HasConstantValue) { return null; } constantVal |= defaultDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; constantVal |= disableOptimizationsDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } if (_options.EnableEditAndContinue) { var enableEncDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue); if (enableEncDebuggingMode is null || !enableEncDebuggingMode.HasConstantValue) { return null; } constantVal |= enableEncDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } var typedConstantDebugMode = new TypedConstant(debuggingModesType, TypedConstantKind.Enum, constantVal); return TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes, ImmutableArray.Create(typedConstantDebugMode)); } /// <summary> /// Given a type <paramref name="type"/>, which is either dynamic type OR is a constructed type with dynamic type present in it's type argument tree, /// returns a synthesized DynamicAttribute with encoded dynamic transforms array. /// </summary> /// <remarks>This method is port of AttrBind::CompileDynamicAttr from the native C# compiler.</remarks> internal SynthesizedAttributeData? SynthesizeDynamicAttribute(TypeSymbol type, int customModifiersCount, RefKind refKindOpt = RefKind.None) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsDynamic()); if (type.IsDynamic() && refKindOpt == RefKind.None && customModifiersCount == 0) { return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor); } else { NamedTypeSymbol booleanType = GetSpecialType(SpecialType.System_Boolean); RoslynDebug.Assert((object)booleanType != null); var transformFlags = DynamicTransformsEncoder.Encode(type, refKindOpt, customModifiersCount, booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, arguments); } } internal SynthesizedAttributeData? SynthesizeTupleNamesAttribute(TypeSymbol type) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsTuple()); var stringType = GetSpecialType(SpecialType.System_String); RoslynDebug.Assert((object)stringType != null); var names = TupleNamesEncoder.Encode(type, stringType); Debug.Assert(!names.IsDefault, "should not need the attribute when no tuple names"); var stringArray = ArrayTypeSymbol.CreateSZArray(stringType.ContainingAssembly, TypeWithAnnotations.Create(stringType)); var args = ImmutableArray.Create(new TypedConstant(stringArray, names)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args); } internal SynthesizedAttributeData? SynthesizeAttributeUsageAttribute(AttributeTargets targets, bool allowMultiple, bool inherited) { var attributeTargetsType = GetWellKnownType(WellKnownType.System_AttributeTargets); var boolType = GetSpecialType(SpecialType.System_Boolean); var arguments = ImmutableArray.Create( new TypedConstant(attributeTargetsType, TypedConstantKind.Enum, targets)); var namedArguments = ImmutableArray.Create( new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, new TypedConstant(boolType, TypedConstantKind.Primitive, allowMultiple)), new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__Inherited, new TypedConstant(boolType, TypedConstantKind.Primitive, inherited))); return TrySynthesizeAttribute(WellKnownMember.System_AttributeUsageAttribute__ctor, arguments, namedArguments); } internal static class TupleNamesEncoder { public static ImmutableArray<string?> Encode(TypeSymbol type) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } return namesBuilder.ToImmutableAndFree(); } public static ImmutableArray<TypedConstant> Encode(TypeSymbol type, TypeSymbol stringType) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } var names = namesBuilder.SelectAsArray((name, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, name), stringType); namesBuilder.Free(); return names; } internal static bool TryGetNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { type.VisitType((t, builder, _ignore) => AddNames(t, builder), namesBuilder); return namesBuilder.Any(name => name != null); } private static bool AddNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { if (type.IsTupleType) { if (type.TupleElementNames.IsDefaultOrEmpty) { // If none of the tuple elements have names, put // null placeholders in. // TODO(https://github.com/dotnet/roslyn/issues/12347): // A possible optimization could be to emit an empty attribute // if all the names are missing, but that has to be true // recursively. namesBuilder.AddMany(null, type.TupleElementTypesWithAnnotations.Length); } else { namesBuilder.AddRange(type.TupleElementNames); } } // Always recur into nested types return false; } } /// <summary> /// Used to generate the dynamic attributes for the required typesymbol. /// </summary> internal static class DynamicTransformsEncoder { internal static ImmutableArray<TypedConstant> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount, TypeSymbol booleanType) { var flagsBuilder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, flagsBuilder, addCustomModifierFlags: true); Debug.Assert(flagsBuilder.Any()); Debug.Assert(flagsBuilder.Contains(true)); var result = flagsBuilder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); flagsBuilder.Free(); return result; } internal static ImmutableArray<bool> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, builder, addCustomModifierFlags: true); return builder.ToImmutableAndFree(); } internal static ImmutableArray<bool> EncodeWithoutCustomModifierFlags(TypeSymbol type, RefKind refKind) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, -1, refKind, builder, addCustomModifierFlags: false); return builder.ToImmutableAndFree(); } internal static void Encode(TypeSymbol type, int customModifiersCount, RefKind refKind, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Debug.Assert(!transformFlagsBuilder.Any()); if (refKind != RefKind.None) { // Native compiler encodes an extra transform flag, always false, for ref/out parameters. transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { // Native compiler encodes an extra transform flag, always false, for each custom modifier. HandleCustomModifiers(customModifiersCount, transformFlagsBuilder); type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: true), transformFlagsBuilder); } else { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: false), transformFlagsBuilder); } } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> transformFlagsBuilder, bool isNestedNamedType, bool addCustomModifierFlags) { // Encode transforms flag for this type and its custom modifiers (if any). switch (type.TypeKind) { case TypeKind.Dynamic: transformFlagsBuilder.Add(true); break; case TypeKind.Array: if (addCustomModifierFlags) { HandleCustomModifiers(((ArrayTypeSymbol)type).ElementTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.Pointer: if (addCustomModifierFlags) { HandleCustomModifiers(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.FunctionPointer: Debug.Assert(!isNestedNamedType); handleFunctionPointerType((FunctionPointerTypeSymbol)type, transformFlagsBuilder, addCustomModifierFlags); // Function pointer types have nested custom modifiers and refkinds in line with types, and visit all their nested types // as part of this call. // We need a different way to indicate that we should not recurse for this type, but should continue walking for other // types. https://github.com/dotnet/roslyn/issues/44160 return true; default: // Encode transforms flag for this type. // For nested named types, a single flag (false) is encoded for the entire type name, followed by flags for all of the type arguments. // For example, for type "A<T>.B<dynamic>", encoded transform flags are: // { // false, // Type "A.B" // false, // Type parameter "T" // true, // Type parameter "dynamic" // } if (!isNestedNamedType) { transformFlagsBuilder.Add(false); } break; } // Continue walking types return false; static void handleFunctionPointerType(FunctionPointerTypeSymbol funcPtr, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Func<TypeSymbol, (ArrayBuilder<bool>, bool), bool, bool> visitor = (TypeSymbol type, (ArrayBuilder<bool> builder, bool addCustomModifierFlags) param, bool isNestedNamedType) => AddFlags(type, param.builder, isNestedNamedType, param.addCustomModifierFlags); // The function pointer type itself gets a false transformFlagsBuilder.Add(false); var sig = funcPtr.Signature; handle(sig.RefKind, sig.RefCustomModifiers, sig.ReturnTypeWithAnnotations); foreach (var param in sig.Parameters) { handle(param.RefKind, param.RefCustomModifiers, param.TypeWithAnnotations); } void handle(RefKind refKind, ImmutableArray<CustomModifier> customModifiers, TypeWithAnnotations twa) { if (addCustomModifierFlags) { HandleCustomModifiers(customModifiers.Length, transformFlagsBuilder); } if (refKind != RefKind.None) { transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { HandleCustomModifiers(twa.CustomModifiers.Length, transformFlagsBuilder); } twa.Type.VisitType(visitor, (transformFlagsBuilder, addCustomModifierFlags)); } } } private static void HandleCustomModifiers(int customModifiersCount, ArrayBuilder<bool> transformFlagsBuilder) { // Native compiler encodes an extra transforms flag, always false, for each custom modifier. transformFlagsBuilder.AddMany(false, customModifiersCount); } } internal static class NativeIntegerTransformsEncoder { internal static void Encode(ArrayBuilder<bool> builder, TypeSymbol type) { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder), builder); } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> builder) { switch (type.SpecialType) { case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: builder.Add(type.IsNativeIntegerType); break; } // Continue walking types return false; } } internal class SpecialMembersSignatureComparer : SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> { // Fields public static readonly SpecialMembersSignatureComparer Instance = new SpecialMembersSignatureComparer(); // Methods protected SpecialMembersSignatureComparer() { } protected override TypeSymbol? GetMDArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (array.IsSZArray) { return null; } return array.ElementType; } protected override TypeSymbol GetFieldType(FieldSymbol field) { return field.Type; } protected override TypeSymbol GetPropertyType(PropertySymbol property) { return property.Type; } protected override TypeSymbol? GetGenericTypeArgument(TypeSymbol type, int argumentIndex) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if (named.Arity <= argumentIndex) { return null; } if ((object)named.ContainingType != null) { return null; } return named.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[argumentIndex].Type; } protected override TypeSymbol? GetGenericTypeDefinition(TypeSymbol type) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if ((object)named.ContainingType != null) { return null; } if (named.Arity == 0) { return null; } return (NamedTypeSymbol)named.OriginalDefinition; } protected override ImmutableArray<ParameterSymbol> GetParameters(MethodSymbol method) { return method.Parameters; } protected override ImmutableArray<ParameterSymbol> GetParameters(PropertySymbol property) { return property.Parameters; } protected override TypeSymbol GetParamType(ParameterSymbol parameter) { return parameter.Type; } protected override TypeSymbol? GetPointedToType(TypeSymbol type) { return type.Kind == SymbolKind.PointerType ? ((PointerTypeSymbol)type).PointedAtType : null; } protected override TypeSymbol GetReturnType(MethodSymbol method) { return method.ReturnType; } protected override TypeSymbol? GetSZArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (!array.IsSZArray) { return null; } return array.ElementType; } protected override bool IsByRefParam(ParameterSymbol parameter) { return parameter.RefKind != RefKind.None; } protected override bool IsByRefMethod(MethodSymbol method) { return method.RefKind != RefKind.None; } protected override bool IsByRefProperty(PropertySymbol property) { return property.RefKind != RefKind.None; } protected override bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.Method) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool IsGenericTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.NamedType) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool MatchArrayRank(TypeSymbol type, int countOfDimensions) { if (type.Kind != SymbolKind.ArrayType) { return false; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; return (array.Rank == countOfDimensions); } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { if ((int)type.OriginalDefinition.SpecialType == typeId) { if (type.IsDefinition) { return true; } return type.Equals(type.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return false; } } internal sealed class WellKnownMembersSignatureComparer : SpecialMembersSignatureComparer { private readonly CSharpCompilation _compilation; public WellKnownMembersSignatureComparer(CSharpCompilation compilation) { _compilation = compilation; } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { WellKnownType wellKnownId = (WellKnownType)typeId; if (wellKnownId.IsWellKnownType()) { return type.Equals(_compilation.GetWellKnownType(wellKnownId), TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return base.MatchTypeToTypeId(type, typeId); } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Workspaces/Core/Portable/Workspace/WorkspaceRegistration.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { public sealed class WorkspaceRegistration { private readonly object _gate = new(); internal WorkspaceRegistration() { } public Workspace? Workspace { get; private set; } public event EventHandler? WorkspaceChanged; internal void SetWorkspaceAndRaiseEvents(Workspace? workspace) { SetWorkspace(workspace); RaiseEvents(); } internal void SetWorkspace(Workspace? workspace) => Workspace = workspace; internal void RaiseEvents() { lock (_gate) { // this is a workaround for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/744145 // for preview 2. // // it is a workaround since we are calling event handler under a lock to make sure // we don't raise event concurrently // // we have this issue to track proper fix for preview 3 or later // https://github.com/dotnet/roslyn/issues/32551 // // issue we are working around is the fact this event can happen concurrently // if RegisteryText happens and then UnregisterText happens in perfect timing, // RegisterText got slightly delayed since it is async event, and UnregisterText happens // at the same time since it is a synchronous event, and they my happens in 2 different threads, // cause this event to be raised concurrently. // that can cause some listener to mess up its internal state like the issue linked above WorkspaceChanged?.Invoke(this, EventArgs.Empty); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { public sealed class WorkspaceRegistration { private readonly object _gate = new(); internal WorkspaceRegistration() { } public Workspace? Workspace { get; private set; } public event EventHandler? WorkspaceChanged; internal void SetWorkspaceAndRaiseEvents(Workspace? workspace) { SetWorkspace(workspace); RaiseEvents(); } internal void SetWorkspace(Workspace? workspace) => Workspace = workspace; internal void RaiseEvents() { lock (_gate) { // this is a workaround for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/744145 // for preview 2. // // it is a workaround since we are calling event handler under a lock to make sure // we don't raise event concurrently // // we have this issue to track proper fix for preview 3 or later // https://github.com/dotnet/roslyn/issues/32551 // // issue we are working around is the fact this event can happen concurrently // if RegisteryText happens and then UnregisterText happens in perfect timing, // RegisterText got slightly delayed since it is async event, and UnregisterText happens // at the same time since it is a synchronous event, and they my happens in 2 different threads, // cause this event to be raised concurrently. // that can cause some listener to mess up its internal state like the issue linked above WorkspaceChanged?.Invoke(this, EventArgs.Empty); } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/Core.Cocoa/Utilities/NavigateToLinkService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using AppKit; using Foundation; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditorFeatures.Cocoa { [ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)] [Shared] internal sealed class NavigateToLinkService : INavigateToLinkService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigateToLinkService() { } public Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { return SpecializedTasks.False; } if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) { return SpecializedTasks.False; } NSWorkspace.SharedWorkspace.OpenUrl(new NSUrl(uri.AbsoluteUri)); return SpecializedTasks.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.Composition; using System.Threading; using System.Threading.Tasks; using AppKit; using Foundation; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditorFeatures.Cocoa { [ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)] [Shared] internal sealed class NavigateToLinkService : INavigateToLinkService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigateToLinkService() { } public Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { return SpecializedTasks.False; } if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) { return SpecializedTasks.False; } NSWorkspace.SharedWorkspace.OpenUrl(new NSUrl(uri.AbsoluteUri)); return SpecializedTasks.True; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_Property1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:G$$oo|} { get { return 1; } } static void Main(string[] args) { int temp = Program.[|Goo|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_Property2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:Goo|} { get { return 1; } } static void Main(string[] args) { int temp = Program.[|Go$$o|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyCascadeThroughInterface1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { int {|Definition:$$P|} { get; } } class C : I { public int {|Definition:P|} { get; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyCascadeThroughInterface2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { int {|Definition:P|} { get; } } class C : I { public int {|Definition:$$P|} { get; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:$$Area|} { get; } } class C1 : I1 { public int {|Definition:Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:Area|} { get; } } class C1 : I1 { public int {|Definition:$$Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int Definition:Area { get; } } class C1 : I1 { public int Definition:Area { get { return 1; } } } class C2 : C1 { public int {|Definition:$$Area|} { get { return base.Area; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:Area|} { get; } } class C1 : I1 { public int {|Definition:Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|$$Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_ExplicitProperty1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public interface DD { int {|Definition:$$Prop|} { get; set; } } public class A : DD { int DD.{|Definition:Prop|} { get { return 1; } set { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_ExplicitProperty2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public interface DD { int {|Definition:Prop|} { get; set; } } public class A : DD { int DD.{|Definition:$$Prop|} { get { return 1; } set { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface1_Api(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:$$Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPI(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface1_Feature(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:$$Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int {|Definition:$$Name|} { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T Name { get; set; } int I2.{|Definition:Name|} { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface3_Api(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:$$Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPI(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface3_FEature(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:$$Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int {|Definition:Name|} { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T Name { get; set; } int I2.{|Definition:$$Name|} { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface5(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:$$Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_PropertyFunctionValue1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Module Program ReadOnly Property {|Definition:$$X|} As Integer ' Rename X to Y Get [|X|] = 1 End Get End Property End Module]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_PropertyFunctionValue2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Module Program ReadOnly Property {|Definition:X|} As Integer ' Rename X to Y Get [|$$X|] = 1 End Get End Property End Module]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { $$[|{|Definition:P|}|] = 4 }; var b = new { P = "asdf" }; var c = new { [|P|] = 4 }; var d = new { P = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { [|P|] = 4 }; var b = new { P = "asdf" }; var c = new { $$[|{|Definition:P|}|] = 4 }; var d = new { P = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { P = 4 }; var b = new { $$[|{|Definition:P|}|] = "asdf" }; var c = new { P = 4 }; var d = new { [|P|] = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { P = 4 }; var b = new { [|P|] = "asdf" }; var c = new { P = 4 }; var d = new { $$[|{|Definition:P|}|] = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.at = New With {.s = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key {|Definition:a1|}} Dim hello = query.First() Console.WriteLine(hello.$$[|a1|].at.s) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.[|{|Definition:at|}|] = New With {.s = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key a1} Dim hello = query.First() Console.WriteLine(hello.a1.$$[|at|].s) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.at = New With {.[|{|Definition:s|}|] = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key a1} Dim hello = query.First() Console.WriteLine(hello.a1.at.$$[|s|]) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenPropertyAndField1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property {|Definition:$$X|}() Sub Goo() Console.WriteLine([|_X|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenPropertyAndField2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property {|Definition:X|}() Sub Goo() Console.WriteLine([|$$_X|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:$$X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:get_X|}(int y) { return base.[|get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:$$get_X|}(int y) { return base.[|get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:get_X|}(int y) { return base.[|$$get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_DefaultProperties(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Strict On Public Interface IA Default Property Goo(ByVal x As Integer) As Integer End Interface Public Interface IC Inherits IA Default Overloads Property {|Definition:$$Goo|}(ByVal x As Long) As String ' Rename Goo to Bar End Interface Class M Sub F(x As IC) Dim y = x[||](1L) Dim y2 = x(1) End Sub End Class </Document> <Document> Class M2 Sub F(x As IC) Dim y = x[||](1L) Dim y2 = x(1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_DefaultProperties2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Strict On Public Interface IA Default Property {|Definition:$$Goo|}(ByVal x As Integer) As Integer End Interface Public Interface IC Inherits IA Default Overloads Property Goo(ByVal x As Long) As String ' Rename Goo to Bar End Interface Class M Sub F(x As IC) Dim y = x(1L) Dim y2 = x[||](1) End Sub End Class </Document> <Document> Class M2 Sub F(x As IC) Dim y = x(1L) Dim y2 = x[||](1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharpProperty_Cref(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IC { /// &lt;see cref="[|Prop|]"/&gt; int {|Definition:$$Prop|} { get; set; } } </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestProperty_ValueUsageInfo(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:G$$oo|} { get { return 1; } set { } } static void Main(string[] args) { Console.WriteLine(Program.{|ValueUsageInfo.Read:[|Goo|]|}); Program.{|ValueUsageInfo.Write:[|Goo|]|} = 0; Program.{|ValueUsageInfo.ReadWrite:[|Goo|]|} += 1; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPropertyReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~P:N.C.[|P|]")] namespace N { class C { public int {|Definition:$$P|} { get; set; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyUseInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace ConsoleApplication22 { class C { static public int {|Definition:G$$oo|} { get { return 1; } } } } </Document> <DocumentFromSourceGenerator> using System; namespace ConsoleApplication22 { class Program { static void Main(string[] args) { int temp = C.[|Goo|]; } } } </DocumentFromSourceGenerator> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyInInterface(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P$$2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P2|} { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P2|} { get; set; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaFeature1(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P$$2|} { get; set; } } class C2_2 : I2 { static int I2.P2 { get; set; } } </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaFeature2(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int P2 { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P$$2|} { get; set; } } </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaAPI1(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P2|} { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P$$2|} { get; set; } } </Document> </Project> </Workspace> Await TestAPI(input, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaAPI2(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P$$2|} { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P2|} { get; set; } } </Document> </Project> </Workspace> Await TestAPI(input, host) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_Property1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:G$$oo|} { get { return 1; } } static void Main(string[] args) { int temp = Program.[|Goo|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_Property2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:Goo|} { get { return 1; } } static void Main(string[] args) { int temp = Program.[|Go$$o|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyCascadeThroughInterface1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { int {|Definition:$$P|} { get; } } class C : I { public int {|Definition:P|} { get; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyCascadeThroughInterface2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { int {|Definition:P|} { get; } } class C : I { public int {|Definition:$$P|} { get; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:$$Area|} { get; } } class C1 : I1 { public int {|Definition:Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:Area|} { get; } } class C1 : I1 { public int {|Definition:$$Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int Definition:Area { get; } } class C1 : I1 { public int Definition:Area { get { return 1; } } } class C2 : C1 { public int {|Definition:$$Area|} { get { return base.Area; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyThroughBase4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I1 { int {|Definition:Area|} { get; } } class C1 : I1 { public int {|Definition:Area|} { get { return 1; } } } class C2 : C1 { public int Area { get { return base.[|$$Area|]; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_ExplicitProperty1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public interface DD { int {|Definition:$$Prop|} { get; set; } } public class A : DD { int DD.{|Definition:Prop|} { get { return 1; } set { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_ExplicitProperty2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public interface DD { int {|Definition:Prop|} { get; set; } } public class A : DD { int DD.{|Definition:$$Prop|} { get { return 1; } set { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface1_Api(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:$$Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPI(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface1_Feature(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:$$Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int {|Definition:$$Name|} { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T Name { get; set; } int I2.{|Definition:Name|} { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface3_Api(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:$$Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPI(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface3_FEature(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:$$Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T Name { get; set; } } interface I2 { int {|Definition:Name|} { get; set; } } interface I3<T> : I2 { new T Name { get; set; } } public class M<T> : I1<T>, I3<T> { public T Name { get; set; } int I2.{|Definition:$$Name|} { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyFromGenericInterface5(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; interface I1<T> { T {|Definition:Name|} { get; set; } } interface I2 { int Name { get; set; } } interface I3<T> : I2 { new T {|Definition:Name|} { get; set; } } public class M<T> : I1<T>, I3<T> { public T {|Definition:$$Name|} { get; set; } int I2.Name { get; set; } } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_PropertyFunctionValue1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Module Program ReadOnly Property {|Definition:$$X|} As Integer ' Rename X to Y Get [|X|] = 1 End Get End Property End Module]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_PropertyFunctionValue2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Module Program ReadOnly Property {|Definition:X|} As Integer ' Rename X to Y Get [|$$X|] = 1 End Get End Property End Module]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { $$[|{|Definition:P|}|] = 4 }; var b = new { P = "asdf" }; var c = new { [|P|] = 4 }; var d = new { P = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { [|P|] = 4 }; var b = new { P = "asdf" }; var c = new { $$[|{|Definition:P|}|] = 4 }; var d = new { P = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { P = 4 }; var b = new { $$[|{|Definition:P|}|] = "asdf" }; var c = new { P = 4 }; var d = new { [|P|] = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AnonymousTypeProperties4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = new { P = 4 }; var b = new { [|P|] = "asdf" }; var c = new { P = 4 }; var d = new { $$[|{|Definition:P|}|] = "asdf" }; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.at = New With {.s = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key {|Definition:a1|}} Dim hello = query.First() Console.WriteLine(hello.$$[|a1|].at.s) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.[|{|Definition:at|}|] = New With {.s = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key a1} Dim hello = query.First() Console.WriteLine(hello.a1.$$[|at|].s) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim a1 = New With {Key.at = New With {.[|{|Definition:s|}|] = "hello"}} Dim query = From at In (From s In "1" Select s) Select New With {Key a1} Dim hello = query.First() Console.WriteLine(hello.a1.at.$$[|s|]) End Sub End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenPropertyAndField1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property {|Definition:$$X|}() Sub Goo() Console.WriteLine([|_X|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenPropertyAndField2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property {|Definition:X|}() Sub Goo() Console.WriteLine([|$$_X|]) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:$$X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:get_X|}(int y) { return base.[|get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:$$get_X|}(int y) { return base.[|get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer {|Definition:Get|} Return 0 End Get End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> class B : A { public override int {|Definition:get_X|}(int y) { return base.[|$$get_X|](y); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_DefaultProperties(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Strict On Public Interface IA Default Property Goo(ByVal x As Integer) As Integer End Interface Public Interface IC Inherits IA Default Overloads Property {|Definition:$$Goo|}(ByVal x As Long) As String ' Rename Goo to Bar End Interface Class M Sub F(x As IC) Dim y = x[||](1L) Dim y2 = x(1) End Sub End Class </Document> <Document> Class M2 Sub F(x As IC) Dim y = x[||](1L) Dim y2 = x(1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestBasic_DefaultProperties2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Strict On Public Interface IA Default Property {|Definition:$$Goo|}(ByVal x As Integer) As Integer End Interface Public Interface IC Inherits IA Default Overloads Property Goo(ByVal x As Long) As String ' Rename Goo to Bar End Interface Class M Sub F(x As IC) Dim y = x(1L) Dim y2 = x[||](1) End Sub End Class </Document> <Document> Class M2 Sub F(x As IC) Dim y = x(1L) Dim y2 = x[||](1) End Sub End Class </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharpProperty_Cref(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface IC { /// &lt;see cref="[|Prop|]"/&gt; int {|Definition:$$Prop|} { get; set; } } </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestProperty_ValueUsageInfo(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; namespace ConsoleApplication22 { class Program { static public int {|Definition:G$$oo|} { get { return 1; } set { } } static void Main(string[] args) { Console.WriteLine(Program.{|ValueUsageInfo.Read:[|Goo|]|}); Program.{|ValueUsageInfo.Write:[|Goo|]|} = 0; Program.{|ValueUsageInfo.ReadWrite:[|Goo|]|} += 1; } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPropertyReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~P:N.C.[|P|]")] namespace N { class C { public int {|Definition:$$P|} { get; set; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_PropertyUseInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace ConsoleApplication22 { class C { static public int {|Definition:G$$oo|} { get { return 1; } } } } </Document> <DocumentFromSourceGenerator> using System; namespace ConsoleApplication22 { class Program { static void Main(string[] args) { int temp = C.[|Goo|]; } } } </DocumentFromSourceGenerator> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyInInterface(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P$$2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P2|} { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P2|} { get; set; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaFeature1(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P$$2|} { get; set; } } class C2_2 : I2 { static int I2.P2 { get; set; } } </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaFeature2(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int P2 { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P$$2|} { get; set; } } </Document> </Project> </Workspace> Await TestStreamingFeature(input, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaAPI1(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P2|} { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P$$2|} { get; set; } } </Document> </Project> </Workspace> Await TestAPI(input, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCSharp_AbstractStaticPropertyViaAPI2(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I2 { abstract static int {|Definition:P2|} { get; set; } } class C2_1 : I2 { public static int {|Definition:P$$2|} { get; set; } } class C2_2 : I2 { static int I2.{|Definition:P2|} { get; set; } } </Document> </Project> </Workspace> Await TestAPI(input, host) End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Test/Semantic/Semantics/AnonymousTypesTests.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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AnonymousTypesTests Inherits BasicTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldsReferences() Dim source = <![CDATA[ Module ModuleA Sub Test1() Dim v1 As Object = New With {.a = 1, .b = .a, .c = .b + .a}'BIND:"New With {.a = 1, .b = .a, .c = .b + .a}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>) (Syntax: 'New With {. ... = .b + .a}') Initializers(3): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '.b = .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '.a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '.c = .b + .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.c As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '.b + .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '.b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '.a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeErrorInFieldReference() Dim source = <![CDATA[ Module ModuleA Sub Test1() Dim v1 As Object = New With {.a = sss, .b = .a}'BIND:"New With {.a = sss, .b = .a}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?, b As ?>, IsInvalid) (Syntax: 'New With {. ... s, .b = .a}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = sss') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?, b As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?, b As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... s, .b = .a}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'sss') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?) (Syntax: '.b = .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?, b As ?>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?, b As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... s, .b = .a}') Right: IPropertyReferenceOperation: Property <anonymous type: a As ?, b As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: '.a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?, b As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... s, .b = .a}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'sss' is not declared. It may be inaccessible due to its protection level. Dim v1 As Object = New With {.a = sss, .b = .a}'BIND:"New With {.a = sss, .b = .a}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldOfRestrictedType() Dim source = <![CDATA[ Module ModuleA Sub Test1(tr As System.TypedReference)'BIND:"Sub Test1(tr As System.TypedReference)" Dim v1 As Object = New With {.a = tr} Dim v2 As Object = New With {.a = {{tr}}} End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (4 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: 'Sub Test1(t ... End Sub') Locals: Local_1: v1 As System.Object Local_2: v2 As System.Object IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim v1 As O ... h {.a = tr}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'v1 As Objec ... h {.a = tr}') Declarators: IVariableDeclaratorOperation (Symbol: v1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'v1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New With {.a = tr}') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New With {.a = tr}') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.TypedReference>, IsInvalid) (Syntax: 'New With {.a = tr}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.TypedReference, IsInvalid) (Syntax: '.a = tr') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.TypedReference>.a As System.TypedReference (OperationKind.PropertyReference, Type: System.TypedReference) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.TypedReference>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = tr}') Right: IParameterReferenceOperation: tr (OperationKind.ParameterReference, Type: System.TypedReference, IsInvalid) (Syntax: 'tr') IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim v2 As O ... a = {{tr}}}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'v2 As Objec ... a = {{tr}}}') Declarators: IVariableDeclaratorOperation (Symbol: v2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'v2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New With {.a = {{tr}}}') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New With {.a = {{tr}}}') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.TypedReference(,)>, IsInvalid) (Syntax: 'New With {.a = {{tr}}}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.TypedReference(,), IsInvalid) (Syntax: '.a = {{tr}}') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.TypedReference(,)>.a As System.TypedReference(,) (OperationKind.PropertyReference, Type: System.TypedReference(,)) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.TypedReference(,)>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = {{tr}}}') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.TypedReference(,), IsInvalid) (Syntax: '{{tr}}') Dimension Sizes(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '{{tr}}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '{{tr}}') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid, IsImplicit) (Syntax: '{{tr}}') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{tr}') Element Values(1): IParameterReferenceOperation: tr (OperationKind.ParameterReference, Type: System.TypedReference, IsInvalid) (Syntax: 'tr') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v1 As Object = New With {.a = tr} ~~ BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v2 As Object = New With {.a = {{tr}}} ~~~~~~ BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v2 As Object = New With {.a = {{tr}}} ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeReferenceToOuterTypeField() Dim source = <![CDATA[ Module ModuleA Sub Test1() Dim c = New With {.a = 1, .b = New With {.c = .a}}'BIND:"New With {.a = 1, .b = New With {.c = .a}}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>, IsInvalid) (Syntax: 'New With {. ... {.c = .a}}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... {.c = .a}}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: c As ?>, IsInvalid) (Syntax: '.b = New With {.c = .a}') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>.b As <anonymous type: c As ?> (OperationKind.PropertyReference, Type: <anonymous type: c As ?>) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... {.c = .a}}') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: c As ?>, IsInvalid) (Syntax: 'New With {.c = .a}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.c = .a') Left: IPropertyReferenceOperation: Property <anonymous type: c As ?>.c As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.c = .a}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'a' is not a member of '<anonymous type>'; it does not exist in the current context. Dim c = New With {.a = 1, .b = New With {.c = .a}}'BIND:"New With {.a = 1, .b = New With {.c = .a}}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldReferenceOutOfOrder01() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With {.b = .c, .c = .b}'BIND:"New With {.b = .c, .c = .b}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: b As ?, c As ?>, IsInvalid) (Syntax: 'New With {. ... c, .c = .b}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.b = .c') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As ?>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... c, .c = .b}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.c') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?) (Syntax: '.c = .b') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As ?>.c As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... c, .c = .b}') Right: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As ?>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: '.b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... c, .c = .b}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36559: Anonymous type member property 'c' cannot be used to infer the type of another member property because the type of 'c' is not yet established. Dim v1 As Object = New With {.b = .c, .c = .b}'BIND:"New With {.b = .c, .c = .b}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldReferenceOutOfOrder02() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With {.b = .c, .c = 1}'BIND:"New With {.b = .c, .c = 1}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: b As ?, c As System.Int32>, IsInvalid) (Syntax: 'New With {. ... .c, .c = 1}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.b = .c') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As System.Int32>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... .c, .c = 1}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.c') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.c = 1') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As System.Int32>.c As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... .c, .c = 1}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36559: Anonymous type member property 'c' cannot be used to infer the type of another member property because the type of 'c' is not yet established. Dim v1 As Object = New With {.b = .c, .c = 1}'BIND:"New With {.b = .c, .c = 1}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithInstanceMethod() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim b = New With {.a = .ToString()}'BIND:"New With {.a = .ToString()}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {. ... ToString()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .ToString()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... ToString()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ToString') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'ToString' is not a member of '<anonymous type>'; it does not exist in the current context. Dim b = New With {.a = .ToString()}'BIND:"New With {.a = .ToString()}" ~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithSharedMethod() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim b = New With {.a = .ReferenceEquals(Nothing, Nothing)}'BIND:"New With {.a = .ReferenceEquals(Nothing, Nothing)}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {. ... , Nothing)}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .Refer ... g, Nothing)') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... , Nothing)}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ReferenceE ... g, Nothing)') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ReferenceEquals') Children(0) ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'ReferenceEquals' is not a member of '<anonymous type>'; it does not exist in the current context. Dim b = New With {.a = .ReferenceEquals(Nothing, Nothing)}'BIND:"New With {.a = .ReferenceEquals(Nothing, Nothing)}" ~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithExtensionMethod() Dim source = <![CDATA[ Imports System.Runtime.CompilerServices Module ModuleA Sub Main() Dim a = New With {.a = .EM()}'BIND:"New With {.a = .EM()}" End Sub <Extension()> Public Function EM(o As Object) As String Return "!" End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {.a = .EM()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .EM()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = .EM()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.EM()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.EM') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'EM' is not a member of '<anonymous type>'; it does not exist in the current context. Dim a = New With {.a = .EM()}'BIND:"New With {.a = .EM()}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithConstructorCall() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a = New With {.a = .New()}'BIND:"New With {.a = .New()}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {.a = .New()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .New()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = .New()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.New()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.New') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'New' is not a member of '<anonymous type>'; it does not exist in the current context. Dim a = New With {.a = .New()}'BIND:"New With {.a = .New()}" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldOfVoidType() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a = New With {.a = SubName()}'BIND:"New With {.a = SubName()}" End Sub Public Sub SubName() End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {. ... SubName()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = SubName()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... SubName()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'SubName()') Children(1): IInvocationOperation (Sub ModuleA.SubName()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'SubName()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30491: Expression does not produce a value. Dim a = New With {.a = SubName()}'BIND:"New With {.a = SubName()}" ~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameWithGeneric() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a = New With {.a = 1, .b = .a(Of Integer)}'BIND:"New With {.a = 1, .b = .a(Of Integer)}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid) (Syntax: 'New With {. ... f Integer)}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... f Integer)}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '.b = .a(Of Integer)') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... f Integer)}') Right: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: '.a(Of Integer)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... f Integer)}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC32045: 'Public Property a As T0' has no type parameters and so cannot have type arguments. Dim a = New With {.a = 1, .b = .a(Of Integer)}'BIND:"New With {.a = 1, .b = .a(Of Integer)}" ~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldWithSyntaxError() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {.a = .}'BIND:"New With {.a = .}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {.a = .}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = .}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30203: Identifier expected. Dim b = New With {.a = .}'BIND:"New With {.a = .}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldWithNothingLiteral() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {.a = Nothing}'BIND:"New With {.a = Nothing}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Object>) (Syntax: 'New With {.a = Nothing}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, Constant: null) (Syntax: '.a = Nothing') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Object>.a As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Object>, IsImplicit) (Syntax: 'New With {.a = Nothing}') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromGeneric01() Dim source = <![CDATA[ Friend Module AM Sub Main() Dim at = New With {New A().F(Of Integer)}'BIND:"New With {New A().F(Of Integer)}" End Sub Class A Public Function F(Of T)() As T Return Nothing End Function End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Int32>, IsInvalid) (Syntax: 'New With {N ... f Integer)}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'New A().F(Of Integer)') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Int32>.$0 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'New A().F(Of Integer)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {N ... f Integer)}') Right: IInvocationOperation ( Function AM.A.F(Of System.Int32)() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'New A().F(Of Integer)') Instance Receiver: IObjectCreationOperation (Constructor: Sub AM.A..ctor()) (OperationKind.ObjectCreation, Type: AM.A, IsInvalid) (Syntax: 'New A()') Arguments(0) Initializer: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36556: Anonymous type member name can be inferred only from a simple or qualified name with no arguments. Dim at = New With {New A().F(Of Integer)}'BIND:"New With {New A().F(Of Integer)}" ~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml01() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {<some-name></some-name>}'BIND:"New With {<some-name></some-name>}" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Xml.Linq.XElement>, IsInvalid) (Syntax: 'New With {< ... some-name>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Xml.Linq.XElement, IsInvalid, IsImplicit) (Syntax: '<some-name></some-name>') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Xml.Linq.XElement>.$0 As System.Xml.Linq.XElement (OperationKind.PropertyReference, Type: System.Xml.Linq.XElement, IsInvalid, IsImplicit) (Syntax: '<some-name></some-name>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Xml.Linq.XElement>, IsInvalid, IsImplicit) (Syntax: 'New With {< ... some-name>}') Right: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '<some-name></some-name>') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36556: Anonymous type member name can be inferred only from a simple or qualified name with no arguments. Dim b = New With {<some-name></some-name>}'BIND:"New With {<some-name></some-name>}" ~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml02() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {<some-name></some-name>.@aa}'BIND:"New With {<some-name></some-name>.@aa}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: aa As System.String>) (Syntax: 'New With {< ... -name>.@aa}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: '<some-name> ... e-name>.@aa') Left: IPropertyReferenceOperation: Property <anonymous type: aa As System.String>.aa As System.String (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: '<some-name> ... e-name>.@aa') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: aa As System.String>, IsImplicit) (Syntax: 'New With {< ... -name>.@aa}') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '<some-name> ... e-name>.@aa') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml03() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {<some-name name="a"></some-name>.@<a-a>}'BIND:"New With {<some-name name="a"></some-name>.@<a-a>}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.String>, IsInvalid) (Syntax: 'New With {< ... me>.@<a-a>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid, IsImplicit) (Syntax: '<some-name ... ame>.@<a-a>') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.String>.$0 As System.String (OperationKind.PropertyReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: '<some-name ... ame>.@<a-a>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {< ... me>.@<a-a>}') Right: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '<some-name ... ame>.@<a-a>') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36613: Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier. Dim b = New With {<some-name name="a"></some-name>.@<a-a>}'BIND:"New With {<some-name name="a"></some-name>.@<a-a>}" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(544370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544370")> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml04() Dim source = <![CDATA[ Module ModuleA Sub Main()'BIND:"Sub Main()" Dim err = New With {<a/>.<_>} Dim ok = New With {<a/>.<__>} End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (4 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: 'Sub Main()' ... End Sub') Locals: Local_1: err As <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)> Local_2: ok As <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)> IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim err = N ... {<a/>.<_>}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'err = New W ... {<a/>.<_>}') Declarators: IVariableDeclaratorOperation (Symbol: err As <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'err') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New With {<a/>.<_>}') IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>, IsInvalid) (Syntax: 'New With {<a/>.<_>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsInvalid, IsImplicit) (Syntax: '<a/>.<_>') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>.$0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsInvalid, IsImplicit) (Syntax: '<a/>.<_>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>, IsInvalid, IsImplicit) (Syntax: 'New With {<a/>.<_>}') Right: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '<a/>.<_>') IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim ok = Ne ... {<a/>.<__>}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ok = New Wi ... {<a/>.<__>}') Declarators: IVariableDeclaratorOperation (Symbol: ok As <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ok') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New With {<a/>.<__>}') IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>) (Syntax: 'New With {<a/>.<__>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsImplicit) (Syntax: '<a/>.<__>') Left: IPropertyReferenceOperation: Property <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>.__ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsImplicit) (Syntax: '<a/>.<__>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>, IsImplicit) (Syntax: 'New With {<a/>.<__>}') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '<a/>.<__>') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36613: Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier. Dim err = New With {<a/>.<_>} ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression01() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a As Integer = 0 Dim b = New With {a * 2}'BIND:"New With {a * 2}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Int32>, IsInvalid) (Syntax: 'New With {a * 2}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a * 2') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Int32>.$0 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a * 2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {a * 2}') Right: IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: 'a * 2') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36556: Anonymous type member name can be inferred only from a simple or qualified name with no arguments. Dim b = New With {a * 2}'BIND:"New With {a * 2}" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression02() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a As Integer = 0 Dim b = New With {.a = 1, a}'BIND:"New With {.a = 1, a}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, a As System.Int32>, IsInvalid) (Syntax: 'New With {.a = 1, a}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, a As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, a As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = 1, a}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, a As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, a As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = 1, a}') Right: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36547: Anonymous type member or property 'a' is already declared. Dim b = New With {.a = 1, a}'BIND:"New With {.a = 1, a}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression03() Dim source = <![CDATA[ Module ModuleA Structure S Public Property FLD As Integer End Structure Sub Main() Dim a As S = New S() Dim b = New With {a.FLD, a.FLD()}'BIND:"New With {a.FLD, a.FLD()}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: FLD As System.Int32, FLD As System.Int32>, IsInvalid) (Syntax: 'New With {a ... D, a.FLD()}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a.FLD') Left: IPropertyReferenceOperation: Property <anonymous type: FLD As System.Int32, FLD As System.Int32>.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a.FLD') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: FLD As System.Int32, FLD As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {a ... D, a.FLD()}') Right: IPropertyReferenceOperation: Property ModuleA.S.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a.FLD') Instance Receiver: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: ModuleA.S) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a.FLD()') Left: IPropertyReferenceOperation: Property <anonymous type: FLD As System.Int32, FLD As System.Int32>.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a.FLD()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: FLD As System.Int32, FLD As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {a ... D, a.FLD()}') Right: IPropertyReferenceOperation: Property ModuleA.S.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'a.FLD()') Instance Receiver: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: ModuleA.S, IsInvalid) (Syntax: 'a') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36547: Anonymous type member or property 'FLD' is already declared. Dim b = New With {a.FLD, a.FLD()}'BIND:"New With {a.FLD, a.FLD()}" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression04() Dim source = <![CDATA[ Imports System.Collections.Generic Module ModuleA Sub Main() Dim a As New Dictionary(Of String, Integer) Dim b = New With {.x = 1, a!x}'BIND:"New With {.x = 1, a!x}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: x As System.Int32, x As System.Int32>, IsInvalid) (Syntax: 'New With {.x = 1, a!x}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.x = 1') Left: IPropertyReferenceOperation: Property <anonymous type: x As System.Int32, x As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: x As System.Int32, x As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.x = 1, a!x}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a!x') Left: IPropertyReferenceOperation: Property <anonymous type: x As System.Int32, x As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a!x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: x As System.Int32, x As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.x = 1, a!x}') Right: IPropertyReferenceOperation: Property System.Collections.Generic.Dictionary(Of System.String, System.Int32).Item(key As System.String) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'a!x') Instance Receiver: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'a') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "x", IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36547: Anonymous type member or property 'x' is already declared. Dim b = New With {.x = 1, a!x}'BIND:"New With {.x = 1, a!x}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithAddressOf() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {Key .a = AddressOf S})'BIND:"New With {Key .a = AddressOf S}" End Sub Sub S() End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As ?>, IsInvalid) (Syntax: 'New With {K ... ddressOf S}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Key .a = AddressOf S') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {K ... ddressOf S}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'AddressOf S') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf S') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'S') Children(1): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'S') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30491: Expression does not produce a value. Console.WriteLine(New With {Key .a = AddressOf S})'BIND:"New With {Key .a = AddressOf S}" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate01() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .x = "--value--", Key .a = DirectCast(Function() As String Return .x.ToString() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, Constant: "--value--") (Syntax: 'Key .x = "--value--"') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.String, Key a As System.String>.x As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "--value--") (Syntax: '"--value--"') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.String, Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .x.ToString()') ReturnedValue: IInvocationOperation (virtual Function System.String.ToString() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: '.x.ToString()') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.String, Key a As System.String>.x As System.String (OperationKind.PropertyReference, Type: System.String, IsInvalid) (Syntax: '.x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Arguments(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36549: Anonymous type property 'x' cannot be used in the definition of a lambda expression within the same initialization list. Return .x.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate02() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .a = DirectCast(Function() As String Return .a.ToString() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .a.ToString()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '.a.ToString()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '.a.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a') Children(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36559: Anonymous type member property 'a' cannot be used to infer the type of another member property because the type of 'a' is not yet established. Return .a.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate03() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .a = DirectCast(Function() As String Return .x.ToString() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .x.ToString()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '.x.ToString()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x') Children(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'x' is not a member of '<anonymous type>'; it does not exist in the current context. Return .x.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate04() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .a = DirectCast(Function() As String Return DirectCast(Function() As String Return .x.ToString() End Function, Func(Of String)).Invoke() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return Dire ... )).Invoke()') ReturnedValue: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .x.ToString()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '.x.ToString()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x') Children(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'x' is not a member of '<anonymous type>'; it does not exist in the current context. Return .x.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(542940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542940")> <Fact> Public Sub LambdaReturningAnonymousType() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim x1 As Object = Function() New With {.Default = "Test"}'BIND:"New With {.Default = "Test"}" System.Console.WriteLine(x1) End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Default As System.String>) (Syntax: 'New With {. ... t = "Test"}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, Constant: "Test") (Syntax: '.Default = "Test"') Left: IPropertyReferenceOperation: Property <anonymous type: Default As System.String>.Default As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'Default') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Default As System.String>, IsImplicit) (Syntax: 'New With {. ... t = "Test"}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Test") (Syntax: '"Test"') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeCreation_MixedInitializers() Dim source = <![CDATA[ Module Program Sub M(a As Integer, o As Object) o = New With { a, .b = 1 }'BIND:"New With { a, .b = 1 }" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As System.Int32>) (Syntax: 'New With { a, .b = 1 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsImplicit) (Syntax: 'New With { a, .b = 1 }') Right: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.b = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsImplicit) (Syntax: 'New With { a, .b = 1 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <WorkItem(543286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543286")> <Fact> Public Sub AnonymousTypeInALambdaInGenericMethod1() Dim compilationDef = <compilation name="AnonymousTypeInALambdaInGenericMethod1"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing return Function() Return new With {x2} End Function End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="{ x2 = 0 }") End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeInALambdaInGenericMethod1_OperationTree() Dim source = <![CDATA[ Imports System Module S1 Public Function Foo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing Return Function() Return New With {x2}'BIND:"New With {x2}" End Function End Function Sub Main() Console.WriteLine(Foo(Of Integer)()()) End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: x2 As T>) (Syntax: 'New With {x2}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: T, IsImplicit) (Syntax: 'x2') Left: IPropertyReferenceOperation: Property <anonymous type: x2 As T>.x2 As T (OperationKind.PropertyReference, Type: T, IsImplicit) (Syntax: 'x2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: x2 As T>, IsImplicit) (Syntax: 'New With {x2}') Right: ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: T) (Syntax: 'x2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <WorkItem(543286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543286")> <Fact> Public Sub AnonymousTypeInALambdaInGenericMethod2() Dim compilationDef = <compilation name="AnonymousTypeInALambdaInGenericMethod2"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing Dim x3 = Function() Dim result = new With {x2} Return result End Function return x3 End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="{ x2 = 0 }") End Sub <Fact()> Public Sub AnonymousTypeInALambdaInGenericMethod3() Dim compilationDef = <compilation name="AnonymousTypeInALambdaInGenericMethod3"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing Dim x3 = Function() Dim result = new With {x2} Dim tmp = result.x2 ' Property getter should be also rewritten Return result End Function return x3 End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="{ x2 = 0 }") End Sub <WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")> <Fact()> Public Sub AssociatedAnonymousDelegate_Valid() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module S1 Public Sub Goo() Dim sss = Sub(x) Console.WriteLine() 'BIND2:"x" sss(x:=1)'BIND1:"sss(x:=1)" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node2 As ParameterSyntax = CompilationUtils.FindBindingText(Of ParameterSyntax)(compilation, "a.vb", 2) Dim symbol2 = model.GetDeclaredSymbol(node2) Assert.Equal(SymbolKind.Parameter, symbol2.Kind) Assert.Equal("x As Object", symbol2.ToDisplayString()) Dim lambda2 = DirectCast(symbol2.ContainingSymbol, MethodSymbol) Assert.Equal(MethodKind.LambdaMethod, lambda2.MethodKind) Assert.Equal("Private Shared Sub (x As Object)", symbol2.ContainingSymbol.ToDisplayString()) Dim associatedDelegate = lambda2.AssociatedAnonymousDelegate Assert.NotNull(associatedDelegate) Assert.True(associatedDelegate.IsDelegateType) Assert.True(associatedDelegate.IsAnonymousType) Assert.Equal("Sub <generated method>(x As Object)", associatedDelegate.ToDisplayString) Assert.Same(associatedDelegate, DirectCast(lambda2, IMethodSymbol).AssociatedAnonymousDelegate) Dim node As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim info = model.GetSymbolInfo(node) Assert.Equal("Public Overridable Sub Invoke(x As Object)", info.Symbol.ToDisplayString()) Assert.Equal("Sub <generated method>(x As Object)", info.Symbol.ContainingSymbol.ToDisplayString()) Assert.Same(associatedDelegate, info.Symbol.ContainingSymbol) End Sub <WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")> <Fact()> Public Sub AssociatedAnonymousDelegate_Action_SameSignature() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module S1 Public Sub Goo() Dim sss As Action(Of Object) = Sub(x) Console.WriteLine() 'BIND2:"x" sss(obj:=1)'BIND1:"sss(obj:=1)" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node2 As ParameterSyntax = CompilationUtils.FindBindingText(Of ParameterSyntax)(compilation, "a.vb", 2) Dim symbol2 = model.GetDeclaredSymbol(node2) Assert.Equal(SymbolKind.Parameter, symbol2.Kind) Assert.Equal("x As Object", symbol2.ToDisplayString()) Dim lambda2 = DirectCast(symbol2.ContainingSymbol, MethodSymbol) Assert.Equal(MethodKind.LambdaMethod, lambda2.MethodKind) Assert.Equal("Private Shared Sub (x As Object)", symbol2.ContainingSymbol.ToDisplayString()) Dim associatedDelegate = lambda2.AssociatedAnonymousDelegate 'Assert.Null(associatedDelegate) Assert.True(associatedDelegate.IsDelegateType) Assert.True(associatedDelegate.IsAnonymousType) Assert.Equal("Sub <generated method>(x As Object)", associatedDelegate.ToDisplayString) Assert.Same(associatedDelegate, DirectCast(lambda2, IMethodSymbol).AssociatedAnonymousDelegate) Dim node As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim info = model.GetSymbolInfo(node) Assert.Equal("Public Overridable Overloads Sub Invoke(obj As Object)", info.Symbol.ToDisplayString()) Assert.Equal("System.Action(Of Object)", info.Symbol.ContainingSymbol.ToDisplayString()) Assert.NotSame(associatedDelegate, info.Symbol.ContainingSymbol) End Sub <WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")> <Fact()> Public Sub AssociatedAnonymousDelegate_Action_DifferentSignature() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module S1 Public Sub Goo() Dim sss As Action = Sub(x) Console.WriteLine() 'BIND2:"x" sss()'BIND1:"sss()" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node2 As ParameterSyntax = CompilationUtils.FindBindingText(Of ParameterSyntax)(compilation, "a.vb", 2) Dim symbol2 = model.GetDeclaredSymbol(node2) Assert.Equal(SymbolKind.Parameter, symbol2.Kind) Assert.Equal("x As Object", symbol2.ToDisplayString()) Dim lambda2 = DirectCast(symbol2.ContainingSymbol, MethodSymbol) Assert.Equal(MethodKind.LambdaMethod, lambda2.MethodKind) Assert.Equal("Private Shared Sub (x As Object)", symbol2.ContainingSymbol.ToDisplayString()) Dim associatedDelegate = lambda2.AssociatedAnonymousDelegate Assert.Null(associatedDelegate) Assert.Same(associatedDelegate, DirectCast(lambda2, IMethodSymbol).AssociatedAnonymousDelegate) Dim node As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim info = model.GetSymbolInfo(node) Assert.Equal("Public Overridable Overloads Sub Invoke()", info.Symbol.ToDisplayString()) Assert.Equal("System.Action", info.Symbol.ContainingSymbol.ToDisplayString()) 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AnonymousTypesTests Inherits BasicTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldsReferences() Dim source = <![CDATA[ Module ModuleA Sub Test1() Dim v1 As Object = New With {.a = 1, .b = .a, .c = .b + .a}'BIND:"New With {.a = 1, .b = .a, .c = .b + .a}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>) (Syntax: 'New With {. ... = .b + .a}') Initializers(3): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '.b = .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '.a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '.c = .b + .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.c As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '.b + .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '.b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') Right: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '.a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32, c As System.Int32>, IsImplicit) (Syntax: 'New With {. ... = .b + .a}') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeErrorInFieldReference() Dim source = <![CDATA[ Module ModuleA Sub Test1() Dim v1 As Object = New With {.a = sss, .b = .a}'BIND:"New With {.a = sss, .b = .a}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?, b As ?>, IsInvalid) (Syntax: 'New With {. ... s, .b = .a}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = sss') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?, b As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?, b As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... s, .b = .a}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'sss') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?) (Syntax: '.b = .a') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?, b As ?>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?, b As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... s, .b = .a}') Right: IPropertyReferenceOperation: Property <anonymous type: a As ?, b As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: '.a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?, b As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... s, .b = .a}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'sss' is not declared. It may be inaccessible due to its protection level. Dim v1 As Object = New With {.a = sss, .b = .a}'BIND:"New With {.a = sss, .b = .a}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldOfRestrictedType() Dim source = <![CDATA[ Module ModuleA Sub Test1(tr As System.TypedReference)'BIND:"Sub Test1(tr As System.TypedReference)" Dim v1 As Object = New With {.a = tr} Dim v2 As Object = New With {.a = {{tr}}} End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (4 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: 'Sub Test1(t ... End Sub') Locals: Local_1: v1 As System.Object Local_2: v2 As System.Object IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim v1 As O ... h {.a = tr}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'v1 As Objec ... h {.a = tr}') Declarators: IVariableDeclaratorOperation (Symbol: v1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'v1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New With {.a = tr}') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New With {.a = tr}') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.TypedReference>, IsInvalid) (Syntax: 'New With {.a = tr}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.TypedReference, IsInvalid) (Syntax: '.a = tr') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.TypedReference>.a As System.TypedReference (OperationKind.PropertyReference, Type: System.TypedReference) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.TypedReference>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = tr}') Right: IParameterReferenceOperation: tr (OperationKind.ParameterReference, Type: System.TypedReference, IsInvalid) (Syntax: 'tr') IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim v2 As O ... a = {{tr}}}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'v2 As Objec ... a = {{tr}}}') Declarators: IVariableDeclaratorOperation (Symbol: v2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'v2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New With {.a = {{tr}}}') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New With {.a = {{tr}}}') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.TypedReference(,)>, IsInvalid) (Syntax: 'New With {.a = {{tr}}}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.TypedReference(,), IsInvalid) (Syntax: '.a = {{tr}}') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.TypedReference(,)>.a As System.TypedReference(,) (OperationKind.PropertyReference, Type: System.TypedReference(,)) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.TypedReference(,)>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = {{tr}}}') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.TypedReference(,), IsInvalid) (Syntax: '{{tr}}') Dimension Sizes(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '{{tr}}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '{{tr}}') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid, IsImplicit) (Syntax: '{{tr}}') Element Values(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{tr}') Element Values(1): IParameterReferenceOperation: tr (OperationKind.ParameterReference, Type: System.TypedReference, IsInvalid) (Syntax: 'tr') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v1 As Object = New With {.a = tr} ~~ BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v2 As Object = New With {.a = {{tr}}} ~~~~~~ BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v2 As Object = New With {.a = {{tr}}} ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeReferenceToOuterTypeField() Dim source = <![CDATA[ Module ModuleA Sub Test1() Dim c = New With {.a = 1, .b = New With {.c = .a}}'BIND:"New With {.a = 1, .b = New With {.c = .a}}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>, IsInvalid) (Syntax: 'New With {. ... {.c = .a}}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... {.c = .a}}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: c As ?>, IsInvalid) (Syntax: '.b = New With {.c = .a}') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>.b As <anonymous type: c As ?> (OperationKind.PropertyReference, Type: <anonymous type: c As ?>) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As <anonymous type: c As ?>>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... {.c = .a}}') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: c As ?>, IsInvalid) (Syntax: 'New With {.c = .a}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.c = .a') Left: IPropertyReferenceOperation: Property <anonymous type: c As ?>.c As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.c = .a}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'a' is not a member of '<anonymous type>'; it does not exist in the current context. Dim c = New With {.a = 1, .b = New With {.c = .a}}'BIND:"New With {.a = 1, .b = New With {.c = .a}}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldReferenceOutOfOrder01() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With {.b = .c, .c = .b}'BIND:"New With {.b = .c, .c = .b}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: b As ?, c As ?>, IsInvalid) (Syntax: 'New With {. ... c, .c = .b}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.b = .c') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As ?>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... c, .c = .b}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.c') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?) (Syntax: '.c = .b') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As ?>.c As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... c, .c = .b}') Right: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As ?>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: '.b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... c, .c = .b}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36559: Anonymous type member property 'c' cannot be used to infer the type of another member property because the type of 'c' is not yet established. Dim v1 As Object = New With {.b = .c, .c = .b}'BIND:"New With {.b = .c, .c = .b}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldReferenceOutOfOrder02() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With {.b = .c, .c = 1}'BIND:"New With {.b = .c, .c = 1}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: b As ?, c As System.Int32>, IsInvalid) (Syntax: 'New With {. ... .c, .c = 1}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.b = .c') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As System.Int32>.b As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... .c, .c = 1}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.c') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.c = 1') Left: IPropertyReferenceOperation: Property <anonymous type: b As ?, c As System.Int32>.c As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: b As ?, c As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... .c, .c = 1}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36559: Anonymous type member property 'c' cannot be used to infer the type of another member property because the type of 'c' is not yet established. Dim v1 As Object = New With {.b = .c, .c = 1}'BIND:"New With {.b = .c, .c = 1}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithInstanceMethod() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim b = New With {.a = .ToString()}'BIND:"New With {.a = .ToString()}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {. ... ToString()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .ToString()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... ToString()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ToString') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'ToString' is not a member of '<anonymous type>'; it does not exist in the current context. Dim b = New With {.a = .ToString()}'BIND:"New With {.a = .ToString()}" ~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithSharedMethod() Dim source = <![CDATA[ Module ModuleA Sub Test1(x As Integer) Dim b = New With {.a = .ReferenceEquals(Nothing, Nothing)}'BIND:"New With {.a = .ReferenceEquals(Nothing, Nothing)}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {. ... , Nothing)}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .Refer ... g, Nothing)') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... , Nothing)}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ReferenceE ... g, Nothing)') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.ReferenceEquals') Children(0) ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'ReferenceEquals' is not a member of '<anonymous type>'; it does not exist in the current context. Dim b = New With {.a = .ReferenceEquals(Nothing, Nothing)}'BIND:"New With {.a = .ReferenceEquals(Nothing, Nothing)}" ~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithExtensionMethod() Dim source = <![CDATA[ Imports System.Runtime.CompilerServices Module ModuleA Sub Main() Dim a = New With {.a = .EM()}'BIND:"New With {.a = .EM()}" End Sub <Extension()> Public Function EM(o As Object) As String Return "!" End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {.a = .EM()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .EM()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = .EM()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.EM()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.EM') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'EM' is not a member of '<anonymous type>'; it does not exist in the current context. Dim a = New With {.a = .EM()}'BIND:"New With {.a = .EM()}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithConstructorCall() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a = New With {.a = .New()}'BIND:"New With {.a = .New()}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {.a = .New()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .New()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = .New()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.New()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.New') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'New' is not a member of '<anonymous type>'; it does not exist in the current context. Dim a = New With {.a = .New()}'BIND:"New With {.a = .New()}" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldOfVoidType() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a = New With {.a = SubName()}'BIND:"New With {.a = SubName()}" End Sub Public Sub SubName() End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {. ... SubName()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = SubName()') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... SubName()}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'SubName()') Children(1): IInvocationOperation (Sub ModuleA.SubName()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'SubName()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30491: Expression does not produce a value. Dim a = New With {.a = SubName()}'BIND:"New With {.a = SubName()}" ~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameWithGeneric() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a = New With {.a = 1, .b = .a(Of Integer)}'BIND:"New With {.a = 1, .b = .a(Of Integer)}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid) (Syntax: 'New With {. ... f Integer)}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... f Integer)}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: '.b = .a(Of Integer)') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... f Integer)}') Right: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: '.a(Of Integer)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {. ... f Integer)}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC32045: 'Public Property a As T0' has no type parameters and so cannot have type arguments. Dim a = New With {.a = 1, .b = .a(Of Integer)}'BIND:"New With {.a = 1, .b = .a(Of Integer)}" ~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldWithSyntaxError() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {.a = .}'BIND:"New With {.a = .}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As ?>, IsInvalid) (Syntax: 'New With {.a = .}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '.a = .') Left: IPropertyReferenceOperation: Property <anonymous type: a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = .}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30203: Identifier expected. Dim b = New With {.a = .}'BIND:"New With {.a = .}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldWithNothingLiteral() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {.a = Nothing}'BIND:"New With {.a = Nothing}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Object>) (Syntax: 'New With {.a = Nothing}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, Constant: null) (Syntax: '.a = Nothing') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Object>.a As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Object>, IsImplicit) (Syntax: 'New With {.a = Nothing}') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromGeneric01() Dim source = <![CDATA[ Friend Module AM Sub Main() Dim at = New With {New A().F(Of Integer)}'BIND:"New With {New A().F(Of Integer)}" End Sub Class A Public Function F(Of T)() As T Return Nothing End Function End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Int32>, IsInvalid) (Syntax: 'New With {N ... f Integer)}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'New A().F(Of Integer)') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Int32>.$0 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'New A().F(Of Integer)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {N ... f Integer)}') Right: IInvocationOperation ( Function AM.A.F(Of System.Int32)() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'New A().F(Of Integer)') Instance Receiver: IObjectCreationOperation (Constructor: Sub AM.A..ctor()) (OperationKind.ObjectCreation, Type: AM.A, IsInvalid) (Syntax: 'New A()') Arguments(0) Initializer: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36556: Anonymous type member name can be inferred only from a simple or qualified name with no arguments. Dim at = New With {New A().F(Of Integer)}'BIND:"New With {New A().F(Of Integer)}" ~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml01() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {<some-name></some-name>}'BIND:"New With {<some-name></some-name>}" End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Xml.Linq.XElement>, IsInvalid) (Syntax: 'New With {< ... some-name>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Xml.Linq.XElement, IsInvalid, IsImplicit) (Syntax: '<some-name></some-name>') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Xml.Linq.XElement>.$0 As System.Xml.Linq.XElement (OperationKind.PropertyReference, Type: System.Xml.Linq.XElement, IsInvalid, IsImplicit) (Syntax: '<some-name></some-name>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Xml.Linq.XElement>, IsInvalid, IsImplicit) (Syntax: 'New With {< ... some-name>}') Right: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '<some-name></some-name>') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36556: Anonymous type member name can be inferred only from a simple or qualified name with no arguments. Dim b = New With {<some-name></some-name>}'BIND:"New With {<some-name></some-name>}" ~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml02() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {<some-name></some-name>.@aa}'BIND:"New With {<some-name></some-name>.@aa}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: aa As System.String>) (Syntax: 'New With {< ... -name>.@aa}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: '<some-name> ... e-name>.@aa') Left: IPropertyReferenceOperation: Property <anonymous type: aa As System.String>.aa As System.String (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: '<some-name> ... e-name>.@aa') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: aa As System.String>, IsImplicit) (Syntax: 'New With {< ... -name>.@aa}') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '<some-name> ... e-name>.@aa') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml03() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim b = New With {<some-name name="a"></some-name>.@<a-a>}'BIND:"New With {<some-name name="a"></some-name>.@<a-a>}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.String>, IsInvalid) (Syntax: 'New With {< ... me>.@<a-a>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid, IsImplicit) (Syntax: '<some-name ... ame>.@<a-a>') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.String>.$0 As System.String (OperationKind.PropertyReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: '<some-name ... ame>.@<a-a>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {< ... me>.@<a-a>}') Right: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '<some-name ... ame>.@<a-a>') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36613: Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier. Dim b = New With {<some-name name="a"></some-name>.@<a-a>}'BIND:"New With {<some-name name="a"></some-name>.@<a-a>}" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(544370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544370")> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromXml04() Dim source = <![CDATA[ Module ModuleA Sub Main()'BIND:"Sub Main()" Dim err = New With {<a/>.<_>} Dim ok = New With {<a/>.<__>} End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (4 statements, 2 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: 'Sub Main()' ... End Sub') Locals: Local_1: err As <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)> Local_2: ok As <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)> IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim err = N ... {<a/>.<_>}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'err = New W ... {<a/>.<_>}') Declarators: IVariableDeclaratorOperation (Symbol: err As <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'err') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New With {<a/>.<_>}') IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>, IsInvalid) (Syntax: 'New With {<a/>.<_>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsInvalid, IsImplicit) (Syntax: '<a/>.<_>') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>.$0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsInvalid, IsImplicit) (Syntax: '<a/>.<_>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>, IsInvalid, IsImplicit) (Syntax: 'New With {<a/>.<_>}') Right: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: '<a/>.<_>') IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim ok = Ne ... {<a/>.<__>}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ok = New Wi ... {<a/>.<__>}') Declarators: IVariableDeclaratorOperation (Symbol: ok As <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ok') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New With {<a/>.<__>}') IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>) (Syntax: 'New With {<a/>.<__>}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsImplicit) (Syntax: '<a/>.<__>') Left: IPropertyReferenceOperation: Property <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>.__ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), IsImplicit) (Syntax: '<a/>.<__>') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: __ As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)>, IsImplicit) (Syntax: 'New With {<a/>.<__>}') Right: IOperation: (OperationKind.None, Type: null) (Syntax: '<a/>.<__>') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36613: Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier. Dim err = New With {<a/>.<_>} ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics, references:=XmlReferences) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression01() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a As Integer = 0 Dim b = New With {a * 2}'BIND:"New With {a * 2}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: $0 As System.Int32>, IsInvalid) (Syntax: 'New With {a * 2}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a * 2') Left: IPropertyReferenceOperation: Property <anonymous type: $0 As System.Int32>.$0 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a * 2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: $0 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {a * 2}') Right: IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: 'a * 2') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36556: Anonymous type member name can be inferred only from a simple or qualified name with no arguments. Dim b = New With {a * 2}'BIND:"New With {a * 2}" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression02() Dim source = <![CDATA[ Module ModuleA Sub Main() Dim a As Integer = 0 Dim b = New With {.a = 1, a}'BIND:"New With {.a = 1, a}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, a As System.Int32>, IsInvalid) (Syntax: 'New With {.a = 1, a}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.a = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, a As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, a As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = 1, a}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, a As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, a As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.a = 1, a}') Right: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36547: Anonymous type member or property 'a' is already declared. Dim b = New With {.a = 1, a}'BIND:"New With {.a = 1, a}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression03() Dim source = <![CDATA[ Module ModuleA Structure S Public Property FLD As Integer End Structure Sub Main() Dim a As S = New S() Dim b = New With {a.FLD, a.FLD()}'BIND:"New With {a.FLD, a.FLD()}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: FLD As System.Int32, FLD As System.Int32>, IsInvalid) (Syntax: 'New With {a ... D, a.FLD()}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a.FLD') Left: IPropertyReferenceOperation: Property <anonymous type: FLD As System.Int32, FLD As System.Int32>.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a.FLD') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: FLD As System.Int32, FLD As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {a ... D, a.FLD()}') Right: IPropertyReferenceOperation: Property ModuleA.S.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a.FLD') Instance Receiver: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: ModuleA.S) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a.FLD()') Left: IPropertyReferenceOperation: Property <anonymous type: FLD As System.Int32, FLD As System.Int32>.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a.FLD()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: FLD As System.Int32, FLD As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {a ... D, a.FLD()}') Right: IPropertyReferenceOperation: Property ModuleA.S.FLD As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'a.FLD()') Instance Receiver: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: ModuleA.S, IsInvalid) (Syntax: 'a') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36547: Anonymous type member or property 'FLD' is already declared. Dim b = New With {a.FLD, a.FLD()}'BIND:"New With {a.FLD, a.FLD()}" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldNameInferenceFromExpression04() Dim source = <![CDATA[ Imports System.Collections.Generic Module ModuleA Sub Main() Dim a As New Dictionary(Of String, Integer) Dim b = New With {.x = 1, a!x}'BIND:"New With {.x = 1, a!x}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: x As System.Int32, x As System.Int32>, IsInvalid) (Syntax: 'New With {.x = 1, a!x}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.x = 1') Left: IPropertyReferenceOperation: Property <anonymous type: x As System.Int32, x As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: x As System.Int32, x As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.x = 1, a!x}') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a!x') Left: IPropertyReferenceOperation: Property <anonymous type: x As System.Int32, x As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a!x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: x As System.Int32, x As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'New With {.x = 1, a!x}') Right: IPropertyReferenceOperation: Property System.Collections.Generic.Dictionary(Of System.String, System.Int32).Item(key As System.String) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'a!x') Instance Receiver: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'a') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "x", IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36547: Anonymous type member or property 'x' is already declared. Dim b = New With {.x = 1, a!x}'BIND:"New With {.x = 1, a!x}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithAddressOf() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {Key .a = AddressOf S})'BIND:"New With {Key .a = AddressOf S}" End Sub Sub S() End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As ?>, IsInvalid) (Syntax: 'New With {K ... ddressOf S}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Key .a = AddressOf S') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As ?>.a As ? (OperationKind.PropertyReference, Type: ?) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As ?>, IsInvalid, IsImplicit) (Syntax: 'New With {K ... ddressOf S}') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'AddressOf S') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf S') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'S') Children(1): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'S') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30491: Expression does not produce a value. Console.WriteLine(New With {Key .a = AddressOf S})'BIND:"New With {Key .a = AddressOf S}" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate01() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .x = "--value--", Key .a = DirectCast(Function() As String Return .x.ToString() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, Constant: "--value--") (Syntax: 'Key .x = "--value--"') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.String, Key a As System.String>.x As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "--value--") (Syntax: '"--value--"') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.String, Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .x.ToString()') ReturnedValue: IInvocationOperation (virtual Function System.String.ToString() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: '.x.ToString()') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.String, Key a As System.String>.x As System.String (OperationKind.PropertyReference, Type: System.String, IsInvalid) (Syntax: '.x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.String, Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Arguments(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36549: Anonymous type property 'x' cannot be used in the definition of a lambda expression within the same initialization list. Return .x.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate02() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .a = DirectCast(Function() As String Return .a.ToString() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .a.ToString()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '.a.ToString()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '.a.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.a') Children(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36559: Anonymous type member property 'a' cannot be used to infer the type of another member property because the type of 'a' is not yet established. Return .a.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate03() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .a = DirectCast(Function() As String Return .x.ToString() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .x.ToString()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '.x.ToString()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x') Children(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'x' is not a member of '<anonymous type>'; it does not exist in the current context. Return .x.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeFieldInitializedWithDelegate04() Dim source = <![CDATA[ Imports System Module Program Sub Main(args As String()) Console.WriteLine(New With {'BIND:"New With {" Key .a = DirectCast(Function() As String Return DirectCast(Function() As String Return .x.ToString() End Function, Func(Of String)).Invoke() End Function, Func(Of String)).Invoke()}) End Sub End Module]]>.Value ' The IOperation tree for this test seems to have an unexpected ILocalReferenceExpression within IAnonymousFunctionExpression. ' See https://github.com/dotnet/roslyn/issues/20357. Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key a As System.String>, IsInvalid) (Syntax: 'New With {' ... ).Invoke()}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: 'Key .a = Di ... )).Invoke()') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key a As System.String>.a As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key a As System.String>, IsInvalid, IsImplicit) (Syntax: 'New With {' ... ).Invoke()}') Right: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return Dire ... )).Invoke()') ReturnedValue: IInvocationOperation (virtual Function System.Func(Of System.String).Invoke() As System.String) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'DirectCast( ... )).Invoke()') Instance Receiver: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))') Target: IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nd Function') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nd Function') Locals: Local_1: <anonymous local> As System.String IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'Return .x.ToString()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '.x.ToString()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x.ToString') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '.x') Children(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Function') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Function') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'End Function') Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36557: 'x' is not a member of '<anonymous type>'; it does not exist in the current context. Return .x.ToString() ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(542940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542940")> <Fact> Public Sub LambdaReturningAnonymousType() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim x1 As Object = Function() New With {.Default = "Test"}'BIND:"New With {.Default = "Test"}" System.Console.WriteLine(x1) End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Default As System.String>) (Syntax: 'New With {. ... t = "Test"}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, Constant: "Test") (Syntax: '.Default = "Test"') Left: IPropertyReferenceOperation: Property <anonymous type: Default As System.String>.Default As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'Default') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Default As System.String>, IsImplicit) (Syntax: 'New With {. ... t = "Test"}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Test") (Syntax: '"Test"') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeCreation_MixedInitializers() Dim source = <![CDATA[ Module Program Sub M(a As Integer, o As Object) o = New With { a, .b = 1 }'BIND:"New With { a, .b = 1 }" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: a As System.Int32, b As System.Int32>) (Syntax: 'New With { a, .b = 1 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.a As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsImplicit) (Syntax: 'New With { a, .b = 1 }') Right: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 1) (Syntax: '.b = 1') Left: IPropertyReferenceOperation: Property <anonymous type: a As System.Int32, b As System.Int32>.b As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: a As System.Int32, b As System.Int32>, IsImplicit) (Syntax: 'New With { a, .b = 1 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <WorkItem(543286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543286")> <Fact> Public Sub AnonymousTypeInALambdaInGenericMethod1() Dim compilationDef = <compilation name="AnonymousTypeInALambdaInGenericMethod1"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing return Function() Return new With {x2} End Function End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="{ x2 = 0 }") End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub AnonymousTypeInALambdaInGenericMethod1_OperationTree() Dim source = <![CDATA[ Imports System Module S1 Public Function Foo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing Return Function() Return New With {x2}'BIND:"New With {x2}" End Function End Function Sub Main() Console.WriteLine(Foo(Of Integer)()()) End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: x2 As T>) (Syntax: 'New With {x2}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: T, IsImplicit) (Syntax: 'x2') Left: IPropertyReferenceOperation: Property <anonymous type: x2 As T>.x2 As T (OperationKind.PropertyReference, Type: T, IsImplicit) (Syntax: 'x2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: x2 As T>, IsImplicit) (Syntax: 'New With {x2}') Right: ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: T) (Syntax: 'x2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <WorkItem(543286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543286")> <Fact> Public Sub AnonymousTypeInALambdaInGenericMethod2() Dim compilationDef = <compilation name="AnonymousTypeInALambdaInGenericMethod2"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing Dim x3 = Function() Dim result = new With {x2} Return result End Function return x3 End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="{ x2 = 0 }") End Sub <Fact()> Public Sub AnonymousTypeInALambdaInGenericMethod3() Dim compilationDef = <compilation name="AnonymousTypeInALambdaInGenericMethod3"> <file name="a.vb"> Imports System Module S1 Public Function Goo(Of T)() As System.Func(Of Object) Dim x2 As T = Nothing Dim x3 = Function() Dim result = new With {x2} Dim tmp = result.x2 ' Property getter should be also rewritten Return result End Function return x3 End Function Sub Main() Console.WriteLine(Goo(Of Integer)()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="{ x2 = 0 }") End Sub <WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")> <Fact()> Public Sub AssociatedAnonymousDelegate_Valid() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module S1 Public Sub Goo() Dim sss = Sub(x) Console.WriteLine() 'BIND2:"x" sss(x:=1)'BIND1:"sss(x:=1)" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node2 As ParameterSyntax = CompilationUtils.FindBindingText(Of ParameterSyntax)(compilation, "a.vb", 2) Dim symbol2 = model.GetDeclaredSymbol(node2) Assert.Equal(SymbolKind.Parameter, symbol2.Kind) Assert.Equal("x As Object", symbol2.ToDisplayString()) Dim lambda2 = DirectCast(symbol2.ContainingSymbol, MethodSymbol) Assert.Equal(MethodKind.LambdaMethod, lambda2.MethodKind) Assert.Equal("Private Shared Sub (x As Object)", symbol2.ContainingSymbol.ToDisplayString()) Dim associatedDelegate = lambda2.AssociatedAnonymousDelegate Assert.NotNull(associatedDelegate) Assert.True(associatedDelegate.IsDelegateType) Assert.True(associatedDelegate.IsAnonymousType) Assert.Equal("Sub <generated method>(x As Object)", associatedDelegate.ToDisplayString) Assert.Same(associatedDelegate, DirectCast(lambda2, IMethodSymbol).AssociatedAnonymousDelegate) Dim node As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim info = model.GetSymbolInfo(node) Assert.Equal("Public Overridable Sub Invoke(x As Object)", info.Symbol.ToDisplayString()) Assert.Equal("Sub <generated method>(x As Object)", info.Symbol.ContainingSymbol.ToDisplayString()) Assert.Same(associatedDelegate, info.Symbol.ContainingSymbol) End Sub <WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")> <Fact()> Public Sub AssociatedAnonymousDelegate_Action_SameSignature() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module S1 Public Sub Goo() Dim sss As Action(Of Object) = Sub(x) Console.WriteLine() 'BIND2:"x" sss(obj:=1)'BIND1:"sss(obj:=1)" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node2 As ParameterSyntax = CompilationUtils.FindBindingText(Of ParameterSyntax)(compilation, "a.vb", 2) Dim symbol2 = model.GetDeclaredSymbol(node2) Assert.Equal(SymbolKind.Parameter, symbol2.Kind) Assert.Equal("x As Object", symbol2.ToDisplayString()) Dim lambda2 = DirectCast(symbol2.ContainingSymbol, MethodSymbol) Assert.Equal(MethodKind.LambdaMethod, lambda2.MethodKind) Assert.Equal("Private Shared Sub (x As Object)", symbol2.ContainingSymbol.ToDisplayString()) Dim associatedDelegate = lambda2.AssociatedAnonymousDelegate 'Assert.Null(associatedDelegate) Assert.True(associatedDelegate.IsDelegateType) Assert.True(associatedDelegate.IsAnonymousType) Assert.Equal("Sub <generated method>(x As Object)", associatedDelegate.ToDisplayString) Assert.Same(associatedDelegate, DirectCast(lambda2, IMethodSymbol).AssociatedAnonymousDelegate) Dim node As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim info = model.GetSymbolInfo(node) Assert.Equal("Public Overridable Overloads Sub Invoke(obj As Object)", info.Symbol.ToDisplayString()) Assert.Equal("System.Action(Of Object)", info.Symbol.ContainingSymbol.ToDisplayString()) Assert.NotSame(associatedDelegate, info.Symbol.ContainingSymbol) End Sub <WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")> <Fact()> Public Sub AssociatedAnonymousDelegate_Action_DifferentSignature() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module S1 Public Sub Goo() Dim sss As Action = Sub(x) Console.WriteLine() 'BIND2:"x" sss()'BIND1:"sss()" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node2 As ParameterSyntax = CompilationUtils.FindBindingText(Of ParameterSyntax)(compilation, "a.vb", 2) Dim symbol2 = model.GetDeclaredSymbol(node2) Assert.Equal(SymbolKind.Parameter, symbol2.Kind) Assert.Equal("x As Object", symbol2.ToDisplayString()) Dim lambda2 = DirectCast(symbol2.ContainingSymbol, MethodSymbol) Assert.Equal(MethodKind.LambdaMethod, lambda2.MethodKind) Assert.Equal("Private Shared Sub (x As Object)", symbol2.ContainingSymbol.ToDisplayString()) Dim associatedDelegate = lambda2.AssociatedAnonymousDelegate Assert.Null(associatedDelegate) Assert.Same(associatedDelegate, DirectCast(lambda2, IMethodSymbol).AssociatedAnonymousDelegate) Dim node As InvocationExpressionSyntax = CompilationUtils.FindBindingText(Of InvocationExpressionSyntax)(compilation, "a.vb", 1) Dim info = model.GetSymbolInfo(node) Assert.Equal("Public Overridable Overloads Sub Invoke()", info.Symbol.ToDisplayString()) Assert.Equal("System.Action", info.Symbol.ContainingSymbol.ToDisplayString()) End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Dependencies/Collections/ImmutableSegmentedList`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. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Collections.Internal; namespace Microsoft.CodeAnalysis.Collections { /// <summary> /// Represents a segmented list that is immutable; meaning it cannot be changed once it is created. /// </summary> /// <remarks> /// <para>There are different scenarios best for <see cref="ImmutableSegmentedList{T}"/> and others /// best for <see cref="ImmutableList{T}"/>.</para> /// /// <para>The following table summarizes the performance characteristics of /// <see cref="ImmutableSegmentedList{T}"/>:</para> /// /// <list type="table"> /// <item> /// <description>Operation</description> /// <description><see cref="ImmutableSegmentedList{T}"/> Complexity</description> /// <description><see cref="ImmutableList{T}"/> Complexity</description> /// <description>Comments</description> /// </item> /// <item> /// <description>Item</description> /// <description>O(1)</description> /// <description>O(log n)</description> /// <description>Directly index into the underlying segmented list</description> /// </item> /// <item> /// <description>Add()</description> /// <description>Currently O(n), but could be O(1) with a relatively large constant</description> /// <description>O(log n)</description> /// <description>Currently requires creating a new segmented list, but could be modified to only clone the segments with changes</description> /// </item> /// <item> /// <description>Insert()</description> /// <description>O(n)</description> /// <description>O(log n)</description> /// <description>Requires creating a new segmented list and cloning all impacted segments</description> /// </item> /// </list> /// /// <para>This type is backed by segmented arrays to avoid using the Large Object Heap without impacting algorithmic /// complexity.</para> /// </remarks> /// <typeparam name="T">The type of the value in the list.</typeparam> /// <devremarks> /// <para>This type has a documented contract of being exactly one reference-type field in size. Our own /// <see cref="RoslynImmutableInterlocked"/> class depends on it, as well as others externally.</para> /// /// <para><strong>IMPORTANT NOTICE FOR MAINTAINERS AND REVIEWERS:</strong></para> /// /// <para>This type should be thread-safe. As a struct, it cannot protect its own fields from being changed from one /// thread while its members are executing on other threads because structs can change <em>in place</em> simply by /// reassigning the field containing this struct. Therefore it is extremely important that <strong>⚠⚠ Every member /// should only dereference <c>this</c> ONCE ⚠⚠</strong>. If a member needs to reference the /// <see cref="_list"/> field, that counts as a dereference of <c>this</c>. Calling other instance members /// (properties or methods) also counts as dereferencing <c>this</c>. Any member that needs to use <c>this</c> more /// than once must instead assign <c>this</c> to a local variable and use that for the rest of the code instead. /// This effectively copies the one field in the struct to a local variable so that it is insulated from other /// threads.</para> /// </devremarks> internal readonly partial struct ImmutableSegmentedList<T> : IImmutableList<T>, IReadOnlyList<T>, IList<T>, IList, IEquatable<ImmutableSegmentedList<T>> { /// <inheritdoc cref="ImmutableList{T}.Empty"/> public static readonly ImmutableSegmentedList<T> Empty = new(new SegmentedList<T>()); private readonly SegmentedList<T> _list; private ImmutableSegmentedList(SegmentedList<T> list) => _list = list; public int Count => _list.Count; public bool IsDefault => _list == null; /// <inheritdoc cref="ImmutableList{T}.IsEmpty"/> public bool IsEmpty => _list.Count == 0; bool ICollection<T>.IsReadOnly => true; bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; bool ICollection.IsSynchronized => true; object ICollection.SyncRoot => _list; public T this[int index] => _list[index]; T IList<T>.this[int index] { get => _list[index]; set => throw new NotSupportedException(); } object? IList.this[int index] { get => _list[index]; set => throw new NotSupportedException(); } public static bool operator ==(ImmutableSegmentedList<T> left, ImmutableSegmentedList<T> right) => left.Equals(right); public static bool operator !=(ImmutableSegmentedList<T> left, ImmutableSegmentedList<T> right) => !left.Equals(right); public static bool operator ==(ImmutableSegmentedList<T>? left, ImmutableSegmentedList<T>? right) => left.GetValueOrDefault().Equals(right.GetValueOrDefault()); public static bool operator !=(ImmutableSegmentedList<T>? left, ImmutableSegmentedList<T>? right) => !left.GetValueOrDefault().Equals(right.GetValueOrDefault()); /// <inheritdoc cref="ImmutableList{T}.ItemRef(int)"/> public ref readonly T ItemRef(int index) { var self = this; // Following trick can reduce the number of range comparison operations by one if (unchecked((uint)index) >= (uint)self.Count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return ref self._list._items[index]; } /// <inheritdoc cref="ImmutableList{T}.Add(T)"/> public ImmutableSegmentedList<T> Add(T value) { var self = this; if (self.IsEmpty) { var list = new SegmentedList<T> { value }; return new ImmutableSegmentedList<T>(list); } else { // TODO: Optimize this to share all segments except for the last one // TODO: Only resize the last page the minimum amount necessary var builder = self.ToValueBuilder(); builder.Add(value); return builder.ToImmutable(); } } /// <inheritdoc cref="ImmutableList{T}.AddRange(IEnumerable{T})"/> public ImmutableSegmentedList<T> AddRange(IEnumerable<T> items) { var self = this; if (items is ICollection<T> { Count: 0 }) { return self; } else if (self.IsEmpty) { if (items is ImmutableSegmentedList<T> immutableList) return immutableList; else if (items is ImmutableSegmentedList<T>.Builder builder) return builder.ToImmutable(); var list = new SegmentedList<T>(items); return new ImmutableSegmentedList<T>(list); } else { // TODO: Optimize this to share all segments except for the last one var builder = self.ToValueBuilder(); builder.AddRange(items); return builder.ToImmutable(); } } /// <inheritdoc cref="ImmutableList{T}.BinarySearch(T)"/> public int BinarySearch(T item) => _list.BinarySearch(item); /// <inheritdoc cref="ImmutableList{T}.BinarySearch(T, IComparer{T}?)"/> public int BinarySearch(T item, IComparer<T>? comparer) => _list.BinarySearch(item, comparer); /// <inheritdoc cref="ImmutableList{T}.BinarySearch(int, int, T, IComparer{T}?)"/> public int BinarySearch(int index, int count, T item, IComparer<T>? comparer) => _list.BinarySearch(index, count, item, comparer); /// <inheritdoc cref="ImmutableList{T}.Clear()"/> public ImmutableSegmentedList<T> Clear() => Empty; public bool Contains(T value) => _list.Contains(value); /// <inheritdoc cref="ImmutableList{T}.ConvertAll{TOutput}(Func{T, TOutput})"/> public ImmutableSegmentedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter) => new ImmutableSegmentedList<TOutput>(_list.ConvertAll(converter)); /// <inheritdoc cref="ImmutableList{T}.CopyTo(T[])"/> public void CopyTo(T[] array) => _list.CopyTo(array); public void CopyTo(T[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex); /// <inheritdoc cref="ImmutableList{T}.CopyTo(int, T[], int, int)"/> public void CopyTo(int index, T[] array, int arrayIndex, int count) => _list.CopyTo(index, array, arrayIndex, count); /// <inheritdoc cref="ImmutableList{T}.Exists(Predicate{T})"/> public bool Exists(Predicate<T> match) => _list.Exists(match); /// <inheritdoc cref="ImmutableList{T}.Find(Predicate{T})"/> public T? Find(Predicate<T> match) => _list.Find(match); /// <inheritdoc cref="ImmutableList{T}.FindAll(Predicate{T})"/> public ImmutableSegmentedList<T> FindAll(Predicate<T> match) => new ImmutableSegmentedList<T>(_list.FindAll(match)); /// <inheritdoc cref="ImmutableList{T}.FindIndex(Predicate{T})"/> public int FindIndex(Predicate<T> match) => _list.FindIndex(match); /// <inheritdoc cref="ImmutableList{T}.FindIndex(int, Predicate{T})"/> public int FindIndex(int startIndex, Predicate<T> match) => _list.FindIndex(startIndex, match); /// <inheritdoc cref="ImmutableList{T}.FindIndex(int, int, Predicate{T})"/> public int FindIndex(int startIndex, int count, Predicate<T> match) => _list.FindIndex(startIndex, count, match); /// <inheritdoc cref="ImmutableList{T}.FindLast(Predicate{T})"/> public T? FindLast(Predicate<T> match) => _list.FindLast(match); /// <inheritdoc cref="ImmutableList{T}.FindLastIndex(Predicate{T})"/> public int FindLastIndex(Predicate<T> match) => _list.FindLastIndex(match); /// <inheritdoc cref="ImmutableList{T}.FindLastIndex(int, Predicate{T})"/> public int FindLastIndex(int startIndex, Predicate<T> match) { var self = this; if (startIndex == 0 && self.IsEmpty) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return self._list.FindLastIndex(startIndex, match); } /// <inheritdoc cref="ImmutableList{T}.FindLastIndex(int, int, Predicate{T})"/> public int FindLastIndex(int startIndex, int count, Predicate<T> match) { var self = this; if (count == 0 && startIndex == 0 && self.IsEmpty) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return self._list.FindLastIndex(startIndex, count, match); } /// <inheritdoc cref="ImmutableList{T}.ForEach(Action{T})"/> public void ForEach(Action<T> action) => _list.ForEach(action); /// <inheritdoc cref="ImmutableList{T}.GetEnumerator()"/> public Enumerator GetEnumerator() => new(_list); /// <inheritdoc cref="ImmutableList{T}.GetRange(int, int)"/> public ImmutableSegmentedList<T> GetRange(int index, int count) { var self = this; if (index == 0 && count == self.Count) return self; return new ImmutableSegmentedList<T>(self._list.GetRange(index, count)); } public int IndexOf(T value) => _list.IndexOf(value); public int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) => _list.IndexOf(item, index, count, equalityComparer); /// <inheritdoc cref="ImmutableList{T}.Insert(int, T)"/> public ImmutableSegmentedList<T> Insert(int index, T item) { var self = this; if (index == self.Count) return self.Add(item); // TODO: Optimize this to share all segments prior to index // TODO: Only resize the last page the minimum amount necessary var builder = self.ToValueBuilder(); builder.Insert(index, item); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.InsertRange(int, IEnumerable{T})"/> public ImmutableSegmentedList<T> InsertRange(int index, IEnumerable<T> items) { var self = this; if (index == self.Count) return self.AddRange(items); // TODO: Optimize this to share all segments prior to index // TODO: Only resize the last page the minimum amount necessary var builder = self.ToValueBuilder(); builder.InsertRange(index, items); return builder.ToImmutable(); } public int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) { var self = this; if (index < 0) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); if (count < 0 || count > self.Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); if (index - count + 1 < 0) throw new ArgumentException(); if (count == 0 && index == 0 && self.IsEmpty) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return self._list.LastIndexOf(item, index, count, equalityComparer); } /// <inheritdoc cref="ImmutableList{T}.Remove(T)"/> public ImmutableSegmentedList<T> Remove(T value) { var self = this; var index = self.IndexOf(value); if (index < 0) return self; return self.RemoveAt(index); } /// <inheritdoc cref="ImmutableList{T}.Remove(T, IEqualityComparer{T}?)"/> public ImmutableSegmentedList<T> Remove(T value, IEqualityComparer<T>? equalityComparer) { var self = this; var index = self.IndexOf(value, 0, Count, equalityComparer); if (index < 0) return self; return self.RemoveAt(index); } /// <inheritdoc cref="ImmutableList{T}.RemoveAll(Predicate{T})"/> public ImmutableSegmentedList<T> RemoveAll(Predicate<T> match) { // TODO: Optimize this to avoid allocations if no items are removed // TODO: Optimize this to share pages prior to the first removed item var builder = ToValueBuilder(); builder.RemoveAll(match); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveAt(int)"/> public ImmutableSegmentedList<T> RemoveAt(int index) { // TODO: Optimize this to share pages prior to the removed item var builder = ToValueBuilder(); builder.RemoveAt(index); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveRange(IEnumerable{T})"/> public ImmutableSegmentedList<T> RemoveRange(IEnumerable<T> items) { if (items is null) throw new ArgumentNullException(nameof(items)); var self = this; if (self.IsEmpty) return self; var builder = ToValueBuilder(); foreach (var item in items) { var index = builder.IndexOf(item); if (index < 0) continue; builder.RemoveAt(index); } return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveRange(IEnumerable{T}, IEqualityComparer{T}?)"/> public ImmutableSegmentedList<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { if (items is null) throw new ArgumentNullException(nameof(items)); var self = this; if (self.IsEmpty) return self; var builder = ToValueBuilder(); foreach (var item in items) { var index = builder.IndexOf(item, 0, builder.Count, equalityComparer); if (index < 0) continue; builder.RemoveAt(index); } return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveRange(int, int)"/> public ImmutableSegmentedList<T> RemoveRange(int index, int count) { var self = this; if (count == 0 && index >= 0 && index <= self.Count) { return self; } // TODO: Optimize this to share pages prior to the first removed item var builder = self.ToValueBuilder(); builder.RemoveRange(index, count); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Replace(T, T)"/> public ImmutableSegmentedList<T> Replace(T oldValue, T newValue) { var self = this; var index = self.IndexOf(oldValue); if (index < 0) { throw new ArgumentException(SR.CannotFindOldValue, nameof(oldValue)); } return self.SetItem(index, newValue); } /// <inheritdoc cref="ImmutableList{T}.Replace(T, T, IEqualityComparer{T}?)"/> public ImmutableSegmentedList<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { var self = this; var index = self.IndexOf(oldValue, equalityComparer); if (index < 0) { throw new ArgumentException(SR.CannotFindOldValue, nameof(oldValue)); } return self.SetItem(index, newValue); } /// <inheritdoc cref="ImmutableList{T}.Reverse()"/> public ImmutableSegmentedList<T> Reverse() { var self = this; if (self.Count < 2) return self; var builder = self.ToValueBuilder(); builder.Reverse(); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Reverse(int, int)"/> public ImmutableSegmentedList<T> Reverse(int index, int count) { var builder = ToValueBuilder(); builder.Reverse(index, count); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.SetItem(int, T)"/> public ImmutableSegmentedList<T> SetItem(int index, T value) { // TODO: Optimize this to share all pages except the one with 'index' var builder = ToValueBuilder(); builder[index] = value; return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort()"/> public ImmutableSegmentedList<T> Sort() { var self = this; if (self.Count < 2) return self; // TODO: Optimize this to avoid allocations if the list is already sorted var builder = self.ToValueBuilder(); builder.Sort(); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort(IComparer{T}?)"/> public ImmutableSegmentedList<T> Sort(IComparer<T>? comparer) { var self = this; if (self.Count < 2) return self; // TODO: Optimize this to avoid allocations if the list is already sorted var builder = self.ToValueBuilder(); builder.Sort(comparer); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort(Comparison{T})"/> public ImmutableSegmentedList<T> Sort(Comparison<T> comparison) { if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } var self = this; if (self.Count < 2) return self; // TODO: Optimize this to avoid allocations if the list is already sorted var builder = self.ToValueBuilder(); builder.Sort(comparison); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort(int, int, IComparer{T}?)"/> public ImmutableSegmentedList<T> Sort(int index, int count, IComparer<T>? comparer) { // TODO: Optimize this to avoid allocations if the list is already sorted var builder = ToValueBuilder(); builder.Sort(index, count, comparer); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.ToBuilder()"/> public Builder ToBuilder() => new Builder(this); private ValueBuilder ToValueBuilder() => new ValueBuilder(this); public override int GetHashCode() => _list?.GetHashCode() ?? 0; public override bool Equals(object? obj) { return obj is ImmutableSegmentedList<T> other && Equals(other); } public bool Equals(ImmutableSegmentedList<T> other) => _list == other._list; /// <inheritdoc cref="ImmutableList{T}.TrueForAll(Predicate{T})"/> public bool TrueForAll(Predicate<T> match) => _list.TrueForAll(match); IImmutableList<T> IImmutableList<T>.Clear() => Clear(); IImmutableList<T> IImmutableList<T>.Add(T value) => Add(value); IImmutableList<T> IImmutableList<T>.AddRange(IEnumerable<T> items) => AddRange(items); IImmutableList<T> IImmutableList<T>.Insert(int index, T element) => Insert(index, element); IImmutableList<T> IImmutableList<T>.InsertRange(int index, IEnumerable<T> items) => InsertRange(index, items); IImmutableList<T> IImmutableList<T>.Remove(T value, IEqualityComparer<T>? equalityComparer) => Remove(value, equalityComparer); IImmutableList<T> IImmutableList<T>.RemoveAll(Predicate<T> match) => RemoveAll(match); IImmutableList<T> IImmutableList<T>.RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) => RemoveRange(items, equalityComparer); IImmutableList<T> IImmutableList<T>.RemoveRange(int index, int count) => RemoveRange(index, count); IImmutableList<T> IImmutableList<T>.RemoveAt(int index) => RemoveAt(index); IImmutableList<T> IImmutableList<T>.SetItem(int index, T value) => SetItem(index, value); IImmutableList<T> IImmutableList<T>.Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) => Replace(oldValue, newValue, equalityComparer); IEnumerator<T> IEnumerable<T>.GetEnumerator() => IsEmpty ? Enumerable.Empty<T>().GetEnumerator() : GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator(); void IList<T>.Insert(int index, T item) => throw new NotSupportedException(); void IList<T>.RemoveAt(int index) => throw new NotSupportedException(); void ICollection<T>.Add(T item) => throw new NotSupportedException(); void ICollection<T>.Clear() => throw new NotSupportedException(); bool ICollection<T>.Remove(T item) => throw new NotSupportedException(); int IList.Add(object? value) => throw new NotSupportedException(); void IList.Clear() => throw new NotSupportedException(); bool IList.Contains(object? value) { IList backingList = _list; return backingList.Contains(value); } int IList.IndexOf(object? value) { IList backingList = _list; return backingList.IndexOf(value); } void IList.Insert(int index, object? value) => throw new NotSupportedException(); void IList.Remove(object? value) => throw new NotSupportedException(); void IList.RemoveAt(int index) => throw new NotSupportedException(); void ICollection.CopyTo(Array array, int index) { IList backingList = _list; backingList.CopyTo(array, index); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Collections.Internal; namespace Microsoft.CodeAnalysis.Collections { /// <summary> /// Represents a segmented list that is immutable; meaning it cannot be changed once it is created. /// </summary> /// <remarks> /// <para>There are different scenarios best for <see cref="ImmutableSegmentedList{T}"/> and others /// best for <see cref="ImmutableList{T}"/>.</para> /// /// <para>The following table summarizes the performance characteristics of /// <see cref="ImmutableSegmentedList{T}"/>:</para> /// /// <list type="table"> /// <item> /// <description>Operation</description> /// <description><see cref="ImmutableSegmentedList{T}"/> Complexity</description> /// <description><see cref="ImmutableList{T}"/> Complexity</description> /// <description>Comments</description> /// </item> /// <item> /// <description>Item</description> /// <description>O(1)</description> /// <description>O(log n)</description> /// <description>Directly index into the underlying segmented list</description> /// </item> /// <item> /// <description>Add()</description> /// <description>Currently O(n), but could be O(1) with a relatively large constant</description> /// <description>O(log n)</description> /// <description>Currently requires creating a new segmented list, but could be modified to only clone the segments with changes</description> /// </item> /// <item> /// <description>Insert()</description> /// <description>O(n)</description> /// <description>O(log n)</description> /// <description>Requires creating a new segmented list and cloning all impacted segments</description> /// </item> /// </list> /// /// <para>This type is backed by segmented arrays to avoid using the Large Object Heap without impacting algorithmic /// complexity.</para> /// </remarks> /// <typeparam name="T">The type of the value in the list.</typeparam> /// <devremarks> /// <para>This type has a documented contract of being exactly one reference-type field in size. Our own /// <see cref="RoslynImmutableInterlocked"/> class depends on it, as well as others externally.</para> /// /// <para><strong>IMPORTANT NOTICE FOR MAINTAINERS AND REVIEWERS:</strong></para> /// /// <para>This type should be thread-safe. As a struct, it cannot protect its own fields from being changed from one /// thread while its members are executing on other threads because structs can change <em>in place</em> simply by /// reassigning the field containing this struct. Therefore it is extremely important that <strong>⚠⚠ Every member /// should only dereference <c>this</c> ONCE ⚠⚠</strong>. If a member needs to reference the /// <see cref="_list"/> field, that counts as a dereference of <c>this</c>. Calling other instance members /// (properties or methods) also counts as dereferencing <c>this</c>. Any member that needs to use <c>this</c> more /// than once must instead assign <c>this</c> to a local variable and use that for the rest of the code instead. /// This effectively copies the one field in the struct to a local variable so that it is insulated from other /// threads.</para> /// </devremarks> internal readonly partial struct ImmutableSegmentedList<T> : IImmutableList<T>, IReadOnlyList<T>, IList<T>, IList, IEquatable<ImmutableSegmentedList<T>> { /// <inheritdoc cref="ImmutableList{T}.Empty"/> public static readonly ImmutableSegmentedList<T> Empty = new(new SegmentedList<T>()); private readonly SegmentedList<T> _list; private ImmutableSegmentedList(SegmentedList<T> list) => _list = list; public int Count => _list.Count; public bool IsDefault => _list == null; /// <inheritdoc cref="ImmutableList{T}.IsEmpty"/> public bool IsEmpty => _list.Count == 0; bool ICollection<T>.IsReadOnly => true; bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; bool ICollection.IsSynchronized => true; object ICollection.SyncRoot => _list; public T this[int index] => _list[index]; T IList<T>.this[int index] { get => _list[index]; set => throw new NotSupportedException(); } object? IList.this[int index] { get => _list[index]; set => throw new NotSupportedException(); } public static bool operator ==(ImmutableSegmentedList<T> left, ImmutableSegmentedList<T> right) => left.Equals(right); public static bool operator !=(ImmutableSegmentedList<T> left, ImmutableSegmentedList<T> right) => !left.Equals(right); public static bool operator ==(ImmutableSegmentedList<T>? left, ImmutableSegmentedList<T>? right) => left.GetValueOrDefault().Equals(right.GetValueOrDefault()); public static bool operator !=(ImmutableSegmentedList<T>? left, ImmutableSegmentedList<T>? right) => !left.GetValueOrDefault().Equals(right.GetValueOrDefault()); /// <inheritdoc cref="ImmutableList{T}.ItemRef(int)"/> public ref readonly T ItemRef(int index) { var self = this; // Following trick can reduce the number of range comparison operations by one if (unchecked((uint)index) >= (uint)self.Count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return ref self._list._items[index]; } /// <inheritdoc cref="ImmutableList{T}.Add(T)"/> public ImmutableSegmentedList<T> Add(T value) { var self = this; if (self.IsEmpty) { var list = new SegmentedList<T> { value }; return new ImmutableSegmentedList<T>(list); } else { // TODO: Optimize this to share all segments except for the last one // TODO: Only resize the last page the minimum amount necessary var builder = self.ToValueBuilder(); builder.Add(value); return builder.ToImmutable(); } } /// <inheritdoc cref="ImmutableList{T}.AddRange(IEnumerable{T})"/> public ImmutableSegmentedList<T> AddRange(IEnumerable<T> items) { var self = this; if (items is ICollection<T> { Count: 0 }) { return self; } else if (self.IsEmpty) { if (items is ImmutableSegmentedList<T> immutableList) return immutableList; else if (items is ImmutableSegmentedList<T>.Builder builder) return builder.ToImmutable(); var list = new SegmentedList<T>(items); return new ImmutableSegmentedList<T>(list); } else { // TODO: Optimize this to share all segments except for the last one var builder = self.ToValueBuilder(); builder.AddRange(items); return builder.ToImmutable(); } } /// <inheritdoc cref="ImmutableList{T}.BinarySearch(T)"/> public int BinarySearch(T item) => _list.BinarySearch(item); /// <inheritdoc cref="ImmutableList{T}.BinarySearch(T, IComparer{T}?)"/> public int BinarySearch(T item, IComparer<T>? comparer) => _list.BinarySearch(item, comparer); /// <inheritdoc cref="ImmutableList{T}.BinarySearch(int, int, T, IComparer{T}?)"/> public int BinarySearch(int index, int count, T item, IComparer<T>? comparer) => _list.BinarySearch(index, count, item, comparer); /// <inheritdoc cref="ImmutableList{T}.Clear()"/> public ImmutableSegmentedList<T> Clear() => Empty; public bool Contains(T value) => _list.Contains(value); /// <inheritdoc cref="ImmutableList{T}.ConvertAll{TOutput}(Func{T, TOutput})"/> public ImmutableSegmentedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter) => new ImmutableSegmentedList<TOutput>(_list.ConvertAll(converter)); /// <inheritdoc cref="ImmutableList{T}.CopyTo(T[])"/> public void CopyTo(T[] array) => _list.CopyTo(array); public void CopyTo(T[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex); /// <inheritdoc cref="ImmutableList{T}.CopyTo(int, T[], int, int)"/> public void CopyTo(int index, T[] array, int arrayIndex, int count) => _list.CopyTo(index, array, arrayIndex, count); /// <inheritdoc cref="ImmutableList{T}.Exists(Predicate{T})"/> public bool Exists(Predicate<T> match) => _list.Exists(match); /// <inheritdoc cref="ImmutableList{T}.Find(Predicate{T})"/> public T? Find(Predicate<T> match) => _list.Find(match); /// <inheritdoc cref="ImmutableList{T}.FindAll(Predicate{T})"/> public ImmutableSegmentedList<T> FindAll(Predicate<T> match) => new ImmutableSegmentedList<T>(_list.FindAll(match)); /// <inheritdoc cref="ImmutableList{T}.FindIndex(Predicate{T})"/> public int FindIndex(Predicate<T> match) => _list.FindIndex(match); /// <inheritdoc cref="ImmutableList{T}.FindIndex(int, Predicate{T})"/> public int FindIndex(int startIndex, Predicate<T> match) => _list.FindIndex(startIndex, match); /// <inheritdoc cref="ImmutableList{T}.FindIndex(int, int, Predicate{T})"/> public int FindIndex(int startIndex, int count, Predicate<T> match) => _list.FindIndex(startIndex, count, match); /// <inheritdoc cref="ImmutableList{T}.FindLast(Predicate{T})"/> public T? FindLast(Predicate<T> match) => _list.FindLast(match); /// <inheritdoc cref="ImmutableList{T}.FindLastIndex(Predicate{T})"/> public int FindLastIndex(Predicate<T> match) => _list.FindLastIndex(match); /// <inheritdoc cref="ImmutableList{T}.FindLastIndex(int, Predicate{T})"/> public int FindLastIndex(int startIndex, Predicate<T> match) { var self = this; if (startIndex == 0 && self.IsEmpty) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return self._list.FindLastIndex(startIndex, match); } /// <inheritdoc cref="ImmutableList{T}.FindLastIndex(int, int, Predicate{T})"/> public int FindLastIndex(int startIndex, int count, Predicate<T> match) { var self = this; if (count == 0 && startIndex == 0 && self.IsEmpty) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return self._list.FindLastIndex(startIndex, count, match); } /// <inheritdoc cref="ImmutableList{T}.ForEach(Action{T})"/> public void ForEach(Action<T> action) => _list.ForEach(action); /// <inheritdoc cref="ImmutableList{T}.GetEnumerator()"/> public Enumerator GetEnumerator() => new(_list); /// <inheritdoc cref="ImmutableList{T}.GetRange(int, int)"/> public ImmutableSegmentedList<T> GetRange(int index, int count) { var self = this; if (index == 0 && count == self.Count) return self; return new ImmutableSegmentedList<T>(self._list.GetRange(index, count)); } public int IndexOf(T value) => _list.IndexOf(value); public int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) => _list.IndexOf(item, index, count, equalityComparer); /// <inheritdoc cref="ImmutableList{T}.Insert(int, T)"/> public ImmutableSegmentedList<T> Insert(int index, T item) { var self = this; if (index == self.Count) return self.Add(item); // TODO: Optimize this to share all segments prior to index // TODO: Only resize the last page the minimum amount necessary var builder = self.ToValueBuilder(); builder.Insert(index, item); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.InsertRange(int, IEnumerable{T})"/> public ImmutableSegmentedList<T> InsertRange(int index, IEnumerable<T> items) { var self = this; if (index == self.Count) return self.AddRange(items); // TODO: Optimize this to share all segments prior to index // TODO: Only resize the last page the minimum amount necessary var builder = self.ToValueBuilder(); builder.InsertRange(index, items); return builder.ToImmutable(); } public int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) { var self = this; if (index < 0) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); if (count < 0 || count > self.Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); if (index - count + 1 < 0) throw new ArgumentException(); if (count == 0 && index == 0 && self.IsEmpty) { // SegmentedList<T> doesn't allow starting at index 0 for an empty list, but IImmutableList<T> does. // Handle it explicitly to avoid an exception. return -1; } return self._list.LastIndexOf(item, index, count, equalityComparer); } /// <inheritdoc cref="ImmutableList{T}.Remove(T)"/> public ImmutableSegmentedList<T> Remove(T value) { var self = this; var index = self.IndexOf(value); if (index < 0) return self; return self.RemoveAt(index); } /// <inheritdoc cref="ImmutableList{T}.Remove(T, IEqualityComparer{T}?)"/> public ImmutableSegmentedList<T> Remove(T value, IEqualityComparer<T>? equalityComparer) { var self = this; var index = self.IndexOf(value, 0, Count, equalityComparer); if (index < 0) return self; return self.RemoveAt(index); } /// <inheritdoc cref="ImmutableList{T}.RemoveAll(Predicate{T})"/> public ImmutableSegmentedList<T> RemoveAll(Predicate<T> match) { // TODO: Optimize this to avoid allocations if no items are removed // TODO: Optimize this to share pages prior to the first removed item var builder = ToValueBuilder(); builder.RemoveAll(match); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveAt(int)"/> public ImmutableSegmentedList<T> RemoveAt(int index) { // TODO: Optimize this to share pages prior to the removed item var builder = ToValueBuilder(); builder.RemoveAt(index); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveRange(IEnumerable{T})"/> public ImmutableSegmentedList<T> RemoveRange(IEnumerable<T> items) { if (items is null) throw new ArgumentNullException(nameof(items)); var self = this; if (self.IsEmpty) return self; var builder = ToValueBuilder(); foreach (var item in items) { var index = builder.IndexOf(item); if (index < 0) continue; builder.RemoveAt(index); } return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveRange(IEnumerable{T}, IEqualityComparer{T}?)"/> public ImmutableSegmentedList<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { if (items is null) throw new ArgumentNullException(nameof(items)); var self = this; if (self.IsEmpty) return self; var builder = ToValueBuilder(); foreach (var item in items) { var index = builder.IndexOf(item, 0, builder.Count, equalityComparer); if (index < 0) continue; builder.RemoveAt(index); } return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.RemoveRange(int, int)"/> public ImmutableSegmentedList<T> RemoveRange(int index, int count) { var self = this; if (count == 0 && index >= 0 && index <= self.Count) { return self; } // TODO: Optimize this to share pages prior to the first removed item var builder = self.ToValueBuilder(); builder.RemoveRange(index, count); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Replace(T, T)"/> public ImmutableSegmentedList<T> Replace(T oldValue, T newValue) { var self = this; var index = self.IndexOf(oldValue); if (index < 0) { throw new ArgumentException(SR.CannotFindOldValue, nameof(oldValue)); } return self.SetItem(index, newValue); } /// <inheritdoc cref="ImmutableList{T}.Replace(T, T, IEqualityComparer{T}?)"/> public ImmutableSegmentedList<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { var self = this; var index = self.IndexOf(oldValue, equalityComparer); if (index < 0) { throw new ArgumentException(SR.CannotFindOldValue, nameof(oldValue)); } return self.SetItem(index, newValue); } /// <inheritdoc cref="ImmutableList{T}.Reverse()"/> public ImmutableSegmentedList<T> Reverse() { var self = this; if (self.Count < 2) return self; var builder = self.ToValueBuilder(); builder.Reverse(); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Reverse(int, int)"/> public ImmutableSegmentedList<T> Reverse(int index, int count) { var builder = ToValueBuilder(); builder.Reverse(index, count); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.SetItem(int, T)"/> public ImmutableSegmentedList<T> SetItem(int index, T value) { // TODO: Optimize this to share all pages except the one with 'index' var builder = ToValueBuilder(); builder[index] = value; return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort()"/> public ImmutableSegmentedList<T> Sort() { var self = this; if (self.Count < 2) return self; // TODO: Optimize this to avoid allocations if the list is already sorted var builder = self.ToValueBuilder(); builder.Sort(); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort(IComparer{T}?)"/> public ImmutableSegmentedList<T> Sort(IComparer<T>? comparer) { var self = this; if (self.Count < 2) return self; // TODO: Optimize this to avoid allocations if the list is already sorted var builder = self.ToValueBuilder(); builder.Sort(comparer); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort(Comparison{T})"/> public ImmutableSegmentedList<T> Sort(Comparison<T> comparison) { if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } var self = this; if (self.Count < 2) return self; // TODO: Optimize this to avoid allocations if the list is already sorted var builder = self.ToValueBuilder(); builder.Sort(comparison); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.Sort(int, int, IComparer{T}?)"/> public ImmutableSegmentedList<T> Sort(int index, int count, IComparer<T>? comparer) { // TODO: Optimize this to avoid allocations if the list is already sorted var builder = ToValueBuilder(); builder.Sort(index, count, comparer); return builder.ToImmutable(); } /// <inheritdoc cref="ImmutableList{T}.ToBuilder()"/> public Builder ToBuilder() => new Builder(this); private ValueBuilder ToValueBuilder() => new ValueBuilder(this); public override int GetHashCode() => _list?.GetHashCode() ?? 0; public override bool Equals(object? obj) { return obj is ImmutableSegmentedList<T> other && Equals(other); } public bool Equals(ImmutableSegmentedList<T> other) => _list == other._list; /// <inheritdoc cref="ImmutableList{T}.TrueForAll(Predicate{T})"/> public bool TrueForAll(Predicate<T> match) => _list.TrueForAll(match); IImmutableList<T> IImmutableList<T>.Clear() => Clear(); IImmutableList<T> IImmutableList<T>.Add(T value) => Add(value); IImmutableList<T> IImmutableList<T>.AddRange(IEnumerable<T> items) => AddRange(items); IImmutableList<T> IImmutableList<T>.Insert(int index, T element) => Insert(index, element); IImmutableList<T> IImmutableList<T>.InsertRange(int index, IEnumerable<T> items) => InsertRange(index, items); IImmutableList<T> IImmutableList<T>.Remove(T value, IEqualityComparer<T>? equalityComparer) => Remove(value, equalityComparer); IImmutableList<T> IImmutableList<T>.RemoveAll(Predicate<T> match) => RemoveAll(match); IImmutableList<T> IImmutableList<T>.RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) => RemoveRange(items, equalityComparer); IImmutableList<T> IImmutableList<T>.RemoveRange(int index, int count) => RemoveRange(index, count); IImmutableList<T> IImmutableList<T>.RemoveAt(int index) => RemoveAt(index); IImmutableList<T> IImmutableList<T>.SetItem(int index, T value) => SetItem(index, value); IImmutableList<T> IImmutableList<T>.Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) => Replace(oldValue, newValue, equalityComparer); IEnumerator<T> IEnumerable<T>.GetEnumerator() => IsEmpty ? Enumerable.Empty<T>().GetEnumerator() : GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator(); void IList<T>.Insert(int index, T item) => throw new NotSupportedException(); void IList<T>.RemoveAt(int index) => throw new NotSupportedException(); void ICollection<T>.Add(T item) => throw new NotSupportedException(); void ICollection<T>.Clear() => throw new NotSupportedException(); bool ICollection<T>.Remove(T item) => throw new NotSupportedException(); int IList.Add(object? value) => throw new NotSupportedException(); void IList.Clear() => throw new NotSupportedException(); bool IList.Contains(object? value) { IList backingList = _list; return backingList.Contains(value); } int IList.IndexOf(object? value) { IList backingList = _list; return backingList.IndexOf(value); } void IList.Insert(int index, object? value) => throw new NotSupportedException(); void IList.Remove(object? value) => throw new NotSupportedException(); void IList.RemoveAt(int index) => throw new NotSupportedException(); void ICollection.CopyTo(Array array, int index) { IList backingList = _list; backingList.CopyTo(array, index); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Portable/BoundTree/Statement.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.Operations; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundNode : IBoundNodeWithIOperationChildren { ImmutableArray<BoundNode?> IBoundNodeWithIOperationChildren.Children => this.Children; /// <summary> /// Override this property to return the child bound nodes if the IOperation API corresponding to this bound node is not yet designed or implemented. /// </summary> /// <remarks>Note that any of the child bound nodes may be null.</remarks> protected virtual ImmutableArray<BoundNode?> Children => ImmutableArray<BoundNode?>.Empty; } internal partial class BoundBadStatement : IBoundInvalidNode { protected override ImmutableArray<BoundNode?> Children => this.ChildBoundNodes!; ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => this.ChildBoundNodes; } partial class BoundFixedStatement { protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Declarations, this.Body); } partial class BoundPointerIndirectionOperator { protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand); } }
// Licensed to the .NET Foundation under one or more 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.Operations; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundNode : IBoundNodeWithIOperationChildren { ImmutableArray<BoundNode?> IBoundNodeWithIOperationChildren.Children => this.Children; /// <summary> /// Override this property to return the child bound nodes if the IOperation API corresponding to this bound node is not yet designed or implemented. /// </summary> /// <remarks>Note that any of the child bound nodes may be null.</remarks> protected virtual ImmutableArray<BoundNode?> Children => ImmutableArray<BoundNode?>.Empty; } internal partial class BoundBadStatement : IBoundInvalidNode { protected override ImmutableArray<BoundNode?> Children => this.ChildBoundNodes!; ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => this.ChildBoundNodes; } partial class BoundFixedStatement { protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Declarations, this.Body); } partial class BoundPointerIndirectionOperator { protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand); } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Tools/ExternalAccess/Razor/RazorDocumentPropertiesServiceWrapper.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 Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal sealed class RazorDocumentPropertiesServiceWrapper : DocumentPropertiesService { public RazorDocumentPropertiesServiceWrapper(IRazorDocumentPropertiesService razorDocumentPropertiesService) { DiagnosticsLspClientName = razorDocumentPropertiesService.DiagnosticsLspClientName; } /// <summary> /// The LSP client name that should get the diagnostics produced by this document; any other source /// will not show these diagnostics. For example, razor uses this to exclude diagnostics from the error list /// so that they can handle the final display. /// If null, the diagnostics do not have this special handling. /// </summary> public override string? DiagnosticsLspClientName { get; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal sealed class RazorDocumentPropertiesServiceWrapper : DocumentPropertiesService { public RazorDocumentPropertiesServiceWrapper(IRazorDocumentPropertiesService razorDocumentPropertiesService) { DiagnosticsLspClientName = razorDocumentPropertiesService.DiagnosticsLspClientName; } /// <summary> /// The LSP client name that should get the diagnostics produced by this document; any other source /// will not show these diagnostics. For example, razor uses this to exclude diagnostics from the error list /// so that they can handle the final display. /// If null, the diagnostics do not have this special handling. /// </summary> public override string? DiagnosticsLspClientName { get; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/Test/UnusedReferences/UnusedReferencesRemoverTests.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnusedReferences; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.UnusedReferences { public class UnusedReferencesRemoverTests { private static readonly string[] Empty = Array.Empty<string>(); private const string UsedAssemblyName = "Used.dll"; private const string UsedAssemblyPath = $"/libs/{UsedAssemblyName}"; private const string UnusedAssemblyName = "Unused.dll"; private const string UnusedAssemblyPath = $"/libs/{UnusedAssemblyName}"; [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_DirectlyUsedAssemblyReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var usedReference = AssemblyReference(UsedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, usedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_DirectlyUsedPackageReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var usedReference = PackageReference(UsedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, usedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_DirectlyUsedProjectReferences_AreNotReturned() { var usedProjects = new[] { UsedAssemblyName }; var usedReference = ProjectReference(UsedAssemblyName); var unusedReferences = GetUnusedReferences(usedCompilationAssemblies: Empty, usedProjects, usedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_UnusedReferences_AreReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var unusedReference = PackageReference(UnusedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, unusedReference); Assert.Contains(unusedReference, unusedReferences); Assert.Single(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_TransitivelyUsedPackageReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var transitivelyUsedReference = PackageReference(UnusedAssemblyName, PackageReference(UsedAssemblyPath)); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, transitivelyUsedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_TransitivelyUsedProjectReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var transitivelyUsedReference = ProjectReference(UnusedAssemblyName, PackageReference(UsedAssemblyPath)); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, transitivelyUsedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_WhenUsedAssemblyIsAvilableDirectlyAndTransitively_DirectReferencesAreReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var transitivelyUsedReference = ProjectReference(UnusedAssemblyPath, PackageReference(UsedAssemblyPath)); var directlyUsedReference = PackageReference(UsedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, transitivelyUsedReference, directlyUsedReference); Assert.Contains(transitivelyUsedReference, unusedReferences); Assert.Single(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_ReferencesThatDoNotContributeToCompilation_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var analyzerReference = new ReferenceInfo( ReferenceType.Package, itemSpecification: "Analyzer", treatAsUsed: false, compilationAssemblies: ImmutableArray<string>.Empty, dependencies: ImmutableArray<ReferenceInfo>.Empty); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, analyzerReference); Assert.Empty(unusedReferences); } [Theory, Trait(Traits.Feature, Traits.Features.UnusedReferences)] [InlineData(UpdateAction.None, false)] [InlineData(UpdateAction.None, true)] [InlineData(UpdateAction.TreatAsUnused, false)] [InlineData(UpdateAction.TreatAsUsed, true)] internal async Task ApplyReferenceUpdates_NoChangeUpdates_AreNotApplied(UpdateAction action, bool treatAsUsed) { var noChangeUpdate = new ReferenceUpdate(action, PackageReference(UnusedAssemblyPath, treatAsUsed)); var appliedUpdates = await ApplyReferenceUpdatesAsync(noChangeUpdate); Assert.Empty(appliedUpdates); } [Theory, Trait(Traits.Feature, Traits.Features.UnusedReferences)] [InlineData(UpdateAction.Remove, false)] [InlineData(UpdateAction.Remove, true)] [InlineData(UpdateAction.TreatAsUnused, true)] [InlineData(UpdateAction.TreatAsUsed, false)] internal async Task ApplyReferenceUpdates_ChangeUpdates_AreApplied(UpdateAction action, bool treatAsUsed) { var changeUpdate = new ReferenceUpdate(action, PackageReference(UnusedAssemblyPath, treatAsUsed)); var appliedUpdates = await ApplyReferenceUpdatesAsync(changeUpdate); Assert.Contains(changeUpdate, appliedUpdates); Assert.Single(appliedUpdates); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public async Task ApplyReferenceUpdates_MixOfChangeAndNoChangeUpdates_ChangesAreApplied() { var noChangeUpdate = new ReferenceUpdate(UpdateAction.None, PackageReference(UsedAssemblyPath)); var changeUpdate = new ReferenceUpdate(UpdateAction.Remove, PackageReference(UnusedAssemblyPath)); var appliedUpdates = await ApplyReferenceUpdatesAsync(noChangeUpdate, changeUpdate); Assert.Contains(changeUpdate, appliedUpdates); Assert.Single(appliedUpdates); } private static ImmutableArray<ReferenceInfo> GetUnusedReferences(string[] usedCompilationAssemblies, string[] usedProjectAssemblyNames, params ReferenceInfo[] references) => UnusedReferencesRemover.GetUnusedReferences(new(usedCompilationAssemblies), new(usedProjectAssemblyNames), references.ToImmutableArray()); private static async Task<ImmutableArray<ReferenceUpdate>> ApplyReferenceUpdatesAsync(params ReferenceUpdate[] referenceUpdates) { var referenceCleanupService = new TestReferenceCleanupService(); await UnusedReferencesRemover.ApplyReferenceUpdatesAsync( referenceCleanupService, string.Empty, referenceUpdates.ToImmutableArray(), CancellationToken.None).ConfigureAwait(false); return referenceCleanupService.AppliedUpdates.ToImmutableArray(); } private static ReferenceInfo ProjectReference(string assemblyPath, params ReferenceInfo[] dependencies) => ProjectReference(assemblyPath, treatAsUsed: false, dependencies); private static ReferenceInfo ProjectReference(string assemblyPath, bool treatAsUsed, params ReferenceInfo[] dependencies) => new(ReferenceType.Project, itemSpecification: Path.GetFileName(assemblyPath), treatAsUsed, compilationAssemblies: ImmutableArray.Create(assemblyPath), dependencies.ToImmutableArray()); private static ReferenceInfo PackageReference(string assemblyPath, params ReferenceInfo[] dependencies) => PackageReference(assemblyPath, treatAsUsed: false, dependencies); private static ReferenceInfo PackageReference(string assemblyPath, bool treatAsUsed, params ReferenceInfo[] dependencies) => new(ReferenceType.Package, itemSpecification: Path.GetFileName(assemblyPath), treatAsUsed, compilationAssemblies: ImmutableArray.Create(assemblyPath), dependencies.ToImmutableArray()); private static ReferenceInfo AssemblyReference(string assemblyPath) => AssemblyReference(assemblyPath, treatAsUsed: false); private static ReferenceInfo AssemblyReference(string assemblyPath, bool treatAsUsed) => new(ReferenceType.Assembly, itemSpecification: Path.GetFileName(assemblyPath), treatAsUsed, compilationAssemblies: ImmutableArray.Create(assemblyPath), dependencies: ImmutableArray<ReferenceInfo>.Empty); private class TestReferenceCleanupService : IReferenceCleanupService { private readonly List<ReferenceUpdate> _appliedUpdates = new(); public IReadOnlyList<ReferenceUpdate> AppliedUpdates => _appliedUpdates; public Task<ImmutableArray<ReferenceInfo>> GetProjectReferencesAsync(string projectPath, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public Task<bool> TryUpdateReferenceAsync(string projectPath, ReferenceUpdate referenceUpdate, CancellationToken cancellationToken) { _appliedUpdates.Add(referenceUpdate); return Task.FromResult(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.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnusedReferences; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.UnusedReferences { public class UnusedReferencesRemoverTests { private static readonly string[] Empty = Array.Empty<string>(); private const string UsedAssemblyName = "Used.dll"; private const string UsedAssemblyPath = $"/libs/{UsedAssemblyName}"; private const string UnusedAssemblyName = "Unused.dll"; private const string UnusedAssemblyPath = $"/libs/{UnusedAssemblyName}"; [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_DirectlyUsedAssemblyReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var usedReference = AssemblyReference(UsedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, usedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_DirectlyUsedPackageReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var usedReference = PackageReference(UsedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, usedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_DirectlyUsedProjectReferences_AreNotReturned() { var usedProjects = new[] { UsedAssemblyName }; var usedReference = ProjectReference(UsedAssemblyName); var unusedReferences = GetUnusedReferences(usedCompilationAssemblies: Empty, usedProjects, usedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_UnusedReferences_AreReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var unusedReference = PackageReference(UnusedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, unusedReference); Assert.Contains(unusedReference, unusedReferences); Assert.Single(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_TransitivelyUsedPackageReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var transitivelyUsedReference = PackageReference(UnusedAssemblyName, PackageReference(UsedAssemblyPath)); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, transitivelyUsedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_TransitivelyUsedProjectReferences_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var transitivelyUsedReference = ProjectReference(UnusedAssemblyName, PackageReference(UsedAssemblyPath)); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, transitivelyUsedReference); Assert.Empty(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_WhenUsedAssemblyIsAvilableDirectlyAndTransitively_DirectReferencesAreReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var transitivelyUsedReference = ProjectReference(UnusedAssemblyPath, PackageReference(UsedAssemblyPath)); var directlyUsedReference = PackageReference(UsedAssemblyPath); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, transitivelyUsedReference, directlyUsedReference); Assert.Contains(transitivelyUsedReference, unusedReferences); Assert.Single(unusedReferences); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public void GetUnusedReferences_ReferencesThatDoNotContributeToCompilation_AreNotReturned() { var usedAssemblies = new[] { UsedAssemblyPath }; var analyzerReference = new ReferenceInfo( ReferenceType.Package, itemSpecification: "Analyzer", treatAsUsed: false, compilationAssemblies: ImmutableArray<string>.Empty, dependencies: ImmutableArray<ReferenceInfo>.Empty); var unusedReferences = GetUnusedReferences(usedAssemblies, usedProjectAssemblyNames: Empty, analyzerReference); Assert.Empty(unusedReferences); } [Theory, Trait(Traits.Feature, Traits.Features.UnusedReferences)] [InlineData(UpdateAction.None, false)] [InlineData(UpdateAction.None, true)] [InlineData(UpdateAction.TreatAsUnused, false)] [InlineData(UpdateAction.TreatAsUsed, true)] internal async Task ApplyReferenceUpdates_NoChangeUpdates_AreNotApplied(UpdateAction action, bool treatAsUsed) { var noChangeUpdate = new ReferenceUpdate(action, PackageReference(UnusedAssemblyPath, treatAsUsed)); var appliedUpdates = await ApplyReferenceUpdatesAsync(noChangeUpdate); Assert.Empty(appliedUpdates); } [Theory, Trait(Traits.Feature, Traits.Features.UnusedReferences)] [InlineData(UpdateAction.Remove, false)] [InlineData(UpdateAction.Remove, true)] [InlineData(UpdateAction.TreatAsUnused, true)] [InlineData(UpdateAction.TreatAsUsed, false)] internal async Task ApplyReferenceUpdates_ChangeUpdates_AreApplied(UpdateAction action, bool treatAsUsed) { var changeUpdate = new ReferenceUpdate(action, PackageReference(UnusedAssemblyPath, treatAsUsed)); var appliedUpdates = await ApplyReferenceUpdatesAsync(changeUpdate); Assert.Contains(changeUpdate, appliedUpdates); Assert.Single(appliedUpdates); } [Fact, Trait(Traits.Feature, Traits.Features.UnusedReferences)] public async Task ApplyReferenceUpdates_MixOfChangeAndNoChangeUpdates_ChangesAreApplied() { var noChangeUpdate = new ReferenceUpdate(UpdateAction.None, PackageReference(UsedAssemblyPath)); var changeUpdate = new ReferenceUpdate(UpdateAction.Remove, PackageReference(UnusedAssemblyPath)); var appliedUpdates = await ApplyReferenceUpdatesAsync(noChangeUpdate, changeUpdate); Assert.Contains(changeUpdate, appliedUpdates); Assert.Single(appliedUpdates); } private static ImmutableArray<ReferenceInfo> GetUnusedReferences(string[] usedCompilationAssemblies, string[] usedProjectAssemblyNames, params ReferenceInfo[] references) => UnusedReferencesRemover.GetUnusedReferences(new(usedCompilationAssemblies), new(usedProjectAssemblyNames), references.ToImmutableArray()); private static async Task<ImmutableArray<ReferenceUpdate>> ApplyReferenceUpdatesAsync(params ReferenceUpdate[] referenceUpdates) { var referenceCleanupService = new TestReferenceCleanupService(); await UnusedReferencesRemover.ApplyReferenceUpdatesAsync( referenceCleanupService, string.Empty, referenceUpdates.ToImmutableArray(), CancellationToken.None).ConfigureAwait(false); return referenceCleanupService.AppliedUpdates.ToImmutableArray(); } private static ReferenceInfo ProjectReference(string assemblyPath, params ReferenceInfo[] dependencies) => ProjectReference(assemblyPath, treatAsUsed: false, dependencies); private static ReferenceInfo ProjectReference(string assemblyPath, bool treatAsUsed, params ReferenceInfo[] dependencies) => new(ReferenceType.Project, itemSpecification: Path.GetFileName(assemblyPath), treatAsUsed, compilationAssemblies: ImmutableArray.Create(assemblyPath), dependencies.ToImmutableArray()); private static ReferenceInfo PackageReference(string assemblyPath, params ReferenceInfo[] dependencies) => PackageReference(assemblyPath, treatAsUsed: false, dependencies); private static ReferenceInfo PackageReference(string assemblyPath, bool treatAsUsed, params ReferenceInfo[] dependencies) => new(ReferenceType.Package, itemSpecification: Path.GetFileName(assemblyPath), treatAsUsed, compilationAssemblies: ImmutableArray.Create(assemblyPath), dependencies.ToImmutableArray()); private static ReferenceInfo AssemblyReference(string assemblyPath) => AssemblyReference(assemblyPath, treatAsUsed: false); private static ReferenceInfo AssemblyReference(string assemblyPath, bool treatAsUsed) => new(ReferenceType.Assembly, itemSpecification: Path.GetFileName(assemblyPath), treatAsUsed, compilationAssemblies: ImmutableArray.Create(assemblyPath), dependencies: ImmutableArray<ReferenceInfo>.Empty); private class TestReferenceCleanupService : IReferenceCleanupService { private readonly List<ReferenceUpdate> _appliedUpdates = new(); public IReadOnlyList<ReferenceUpdate> AppliedUpdates => _appliedUpdates; public Task<ImmutableArray<ReferenceInfo>> GetProjectReferencesAsync(string projectPath, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public Task<bool> TryUpdateReferenceAsync(string projectPath, ReferenceUpdate referenceUpdate, CancellationToken cancellationToken) { _appliedUpdates.Add(referenceUpdate); return Task.FromResult(true); } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviderOrderTests.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.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion <UseExportProvider> Public Class CompletionProviderOrderTests ''' <summary> ''' Verifies the exact order of all built-in completion providers. ''' </summary> <Fact> Public Sub TestCompletionProviderOrder() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim actualOrder = orderedVisualBasicCompletionProviders.Select(Function(x) x.Value.GetType()).ToArray() Dim expectedOrder = { GetType(FirstBuiltInCompletionProvider), GetType(KeywordCompletionProvider), GetType(AwaitCompletionProvider), GetType(SymbolCompletionProvider), GetType(PreprocessorCompletionProvider), GetType(ObjectInitializerCompletionProvider), GetType(ObjectCreationCompletionProvider), GetType(EnumCompletionProvider), GetType(NamedParameterCompletionProvider), GetType(VisualBasicSuggestionModeCompletionProvider), GetType(ImplementsClauseCompletionProvider), GetType(HandlesClauseCompletionProvider), GetType(PartialTypeCompletionProvider), GetType(CrefCompletionProvider), GetType(CompletionListTagCompletionProvider), GetType(OverrideCompletionProvider), GetType(XmlDocCommentCompletionProvider), GetType(InternalsVisibleToCompletionProvider), GetType(EmbeddedLanguageCompletionProvider), GetType(TypeImportCompletionProvider), GetType(ExtensionMethodImportCompletionProvider), GetType(LastBuiltInCompletionProvider) } AssertEx.EqualOrDiff( String.Join(Environment.NewLine, expectedOrder.Select(Function(x) x.FullName)), String.Join(Environment.NewLine, actualOrder.Select(Function(x) x.FullName))) End Sub ''' <summary> ''' Verifies that the order of built-in completion providers is deterministic. ''' </summary> <Fact> Public Sub TestCompletionProviderOrderMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) For i = 0 To orderedVisualBasicCompletionProviders.Count - 1 If i = 0 Then Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped) Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped) Continue For ElseIf i = orderedVisualBasicCompletionProviders.Count - 1 Then Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped) If Not orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped.Contains(orderedVisualBasicCompletionProviders(i - 1).Metadata.Name) Then ' Make sure the last built-in provider comes before the marker Assert.Contains(orderedVisualBasicCompletionProviders(i).Metadata.Name, orderedVisualBasicCompletionProviders(i - 1).Metadata.BeforeTyped) End If Continue For End If If orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped.Any() Then Assert.Equal(orderedVisualBasicCompletionProviders.Last().Metadata.Name, Assert.Single(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped)) End If Dim after = Assert.Single(orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped) Assert.Equal(orderedVisualBasicCompletionProviders(i - 1).Metadata.Name, after) Next End Sub <Fact> Public Sub TestCompletionProviderFirstNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim firstCompletionProvider = orderedVisualBasicCompletionProviders.First() Assert.Equal("FirstBuiltInCompletionProvider", firstCompletionProvider.Metadata.Name) End Sub <Fact> Public Sub TestCompletionProviderLastNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim lastCompletionProvider = orderedVisualBasicCompletionProviders.Last() Assert.Equal("LastBuiltInCompletionProvider", lastCompletionProvider.Metadata.Name) End Sub <Fact> Public Sub TestCompletionProviderNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim visualBasicCompletionProviders = completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic) For Each export In visualBasicCompletionProviders Assert.Equal(export.Value.GetType().Name, export.Metadata.Name) Next 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.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion <UseExportProvider> Public Class CompletionProviderOrderTests ''' <summary> ''' Verifies the exact order of all built-in completion providers. ''' </summary> <Fact> Public Sub TestCompletionProviderOrder() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim actualOrder = orderedVisualBasicCompletionProviders.Select(Function(x) x.Value.GetType()).ToArray() Dim expectedOrder = { GetType(FirstBuiltInCompletionProvider), GetType(KeywordCompletionProvider), GetType(AwaitCompletionProvider), GetType(SymbolCompletionProvider), GetType(PreprocessorCompletionProvider), GetType(ObjectInitializerCompletionProvider), GetType(ObjectCreationCompletionProvider), GetType(EnumCompletionProvider), GetType(NamedParameterCompletionProvider), GetType(VisualBasicSuggestionModeCompletionProvider), GetType(ImplementsClauseCompletionProvider), GetType(HandlesClauseCompletionProvider), GetType(PartialTypeCompletionProvider), GetType(CrefCompletionProvider), GetType(CompletionListTagCompletionProvider), GetType(OverrideCompletionProvider), GetType(XmlDocCommentCompletionProvider), GetType(InternalsVisibleToCompletionProvider), GetType(EmbeddedLanguageCompletionProvider), GetType(TypeImportCompletionProvider), GetType(ExtensionMethodImportCompletionProvider), GetType(LastBuiltInCompletionProvider) } AssertEx.EqualOrDiff( String.Join(Environment.NewLine, expectedOrder.Select(Function(x) x.FullName)), String.Join(Environment.NewLine, actualOrder.Select(Function(x) x.FullName))) End Sub ''' <summary> ''' Verifies that the order of built-in completion providers is deterministic. ''' </summary> <Fact> Public Sub TestCompletionProviderOrderMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) For i = 0 To orderedVisualBasicCompletionProviders.Count - 1 If i = 0 Then Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped) Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped) Continue For ElseIf i = orderedVisualBasicCompletionProviders.Count - 1 Then Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped) If Not orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped.Contains(orderedVisualBasicCompletionProviders(i - 1).Metadata.Name) Then ' Make sure the last built-in provider comes before the marker Assert.Contains(orderedVisualBasicCompletionProviders(i).Metadata.Name, orderedVisualBasicCompletionProviders(i - 1).Metadata.BeforeTyped) End If Continue For End If If orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped.Any() Then Assert.Equal(orderedVisualBasicCompletionProviders.Last().Metadata.Name, Assert.Single(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped)) End If Dim after = Assert.Single(orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped) Assert.Equal(orderedVisualBasicCompletionProviders(i - 1).Metadata.Name, after) Next End Sub <Fact> Public Sub TestCompletionProviderFirstNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim firstCompletionProvider = orderedVisualBasicCompletionProviders.First() Assert.Equal("FirstBuiltInCompletionProvider", firstCompletionProvider.Metadata.Name) End Sub <Fact> Public Sub TestCompletionProviderLastNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim lastCompletionProvider = orderedVisualBasicCompletionProviders.Last() Assert.Equal("LastBuiltInCompletionProvider", lastCompletionProvider.Metadata.Name) End Sub <Fact> Public Sub TestCompletionProviderNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim visualBasicCompletionProviders = completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic) For Each export In visualBasicCompletionProviders Assert.Equal(export.Value.GetType().Name, export.Metadata.Name) Next End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactoryTests.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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxFactoryTests <Fact> Public Sub SyntaxTree() Dim text = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit(), encoding:=Nothing).GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub SyntaxTreeFromNode() Dim text = SyntaxFactory.CompilationUnit().SyntaxTree.GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub TestSpacingOnNullableDatetimeType() Dim node = SyntaxFactory.CompilationUnit().WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C")).WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.PropertyStatement("P").WithAsClause( SyntaxFactory.SimpleAsClause( SyntaxFactory.NullableType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.IntegerKeyword))))) })) })).NormalizeWhitespace() Dim expected = "Class C" & vbCrLf & vbCrLf & " Property P As Integer?" & vbCrLf & "End Class" & vbCrLf Assert.Equal(expected, node.ToFullString()) End Sub <Fact> <WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")> <WorkItem(720708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720708")> Public Sub TestLiteralDefaultStringValues() ' string CheckLiteralToString("A", """A""") CheckLiteralToString(ChrW(7).ToString(), "ChrW(7)") CheckLiteralToString(ChrW(10).ToString(), "vbLf") ' char CheckLiteralToString("A"c, """A""c") CheckLiteralToString(ChrW(7), "ChrW(7)") CheckLiteralToString(ChrW(10), "vbLf") '' Unsupported in VB: byte, sbyte, ushort, short ' uint CheckLiteralToString(UInteger.MinValue, "0UI") CheckLiteralToString(UInteger.MaxValue, "4294967295UI") ' int CheckLiteralToString(0, "0") CheckLiteralToString(Integer.MinValue, "-2147483648") CheckLiteralToString(Integer.MaxValue, "2147483647") ' ulong CheckLiteralToString(ULong.MinValue, "0UL") CheckLiteralToString(ULong.MaxValue, "18446744073709551615UL") ' long CheckLiteralToString(0L, "0L") CheckLiteralToString(Long.MinValue, "-9223372036854775808L") CheckLiteralToString(Long.MaxValue, "9223372036854775807L") ' float CheckLiteralToString(0.0F, "0F") CheckLiteralToString(0.012345F, "0.012345F") #If NET472 Then CheckLiteralToString(Single.MaxValue, "3.40282347E+38F") #Else CheckLiteralToString(Single.MaxValue, "3.4028235E+38F") #End If ' double CheckLiteralToString(0.0, "0") CheckLiteralToString(0.012345, "0.012345") CheckLiteralToString(Double.MaxValue, "1.7976931348623157E+308") ' decimal CheckLiteralToString(0D, "0D") CheckLiteralToString(0.012345D, "0.012345D") CheckLiteralToString(Decimal.MaxValue, "79228162514264337593543950335D") End Sub Private Shared Sub CheckLiteralToString(value As Object, expected As String) Dim factoryType As System.Type = GetType(SyntaxFactory) Dim literalMethods = factoryType.GetMethods().Where(Function(m) m.Name = "Literal" AndAlso m.GetParameters().Count() = 1) Dim literalMethod = literalMethods.Single(Function(m) m.GetParameters().Single().ParameterType = value.GetType()) Assert.Equal(expected, literalMethod.Invoke(Nothing, {value}).ToString()) End Sub <Fact> Public Shared Sub TestParseTypeNameOptions() Dim options As VisualBasicParseOptions = TestOptions.Regular Dim code = " #If Variable String #Else Integer #End If" Dim type1 = SyntaxFactory.ParseTypeName(code, options:=options.WithPreprocessorSymbols(New KeyValuePair(Of String, Object)("Variable", "True"))) Assert.Equal("String", type1.ToString()) Dim type2 = SyntaxFactory.ParseTypeName(code, options:=options) Assert.Equal("Integer", type2.ToString()) 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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxFactoryTests <Fact> Public Sub SyntaxTree() Dim text = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit(), encoding:=Nothing).GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub SyntaxTreeFromNode() Dim text = SyntaxFactory.CompilationUnit().SyntaxTree.GetText() Assert.Null(text.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, text.ChecksumAlgorithm) End Sub <Fact> Public Sub TestSpacingOnNullableDatetimeType() Dim node = SyntaxFactory.CompilationUnit().WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C")).WithMembers( SyntaxFactory.List(Of Syntax.StatementSyntax)( { SyntaxFactory.PropertyStatement("P").WithAsClause( SyntaxFactory.SimpleAsClause( SyntaxFactory.NullableType( SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.IntegerKeyword))))) })) })).NormalizeWhitespace() Dim expected = "Class C" & vbCrLf & vbCrLf & " Property P As Integer?" & vbCrLf & "End Class" & vbCrLf Assert.Equal(expected, node.ToFullString()) End Sub <Fact> <WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")> <WorkItem(720708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720708")> Public Sub TestLiteralDefaultStringValues() ' string CheckLiteralToString("A", """A""") CheckLiteralToString(ChrW(7).ToString(), "ChrW(7)") CheckLiteralToString(ChrW(10).ToString(), "vbLf") ' char CheckLiteralToString("A"c, """A""c") CheckLiteralToString(ChrW(7), "ChrW(7)") CheckLiteralToString(ChrW(10), "vbLf") '' Unsupported in VB: byte, sbyte, ushort, short ' uint CheckLiteralToString(UInteger.MinValue, "0UI") CheckLiteralToString(UInteger.MaxValue, "4294967295UI") ' int CheckLiteralToString(0, "0") CheckLiteralToString(Integer.MinValue, "-2147483648") CheckLiteralToString(Integer.MaxValue, "2147483647") ' ulong CheckLiteralToString(ULong.MinValue, "0UL") CheckLiteralToString(ULong.MaxValue, "18446744073709551615UL") ' long CheckLiteralToString(0L, "0L") CheckLiteralToString(Long.MinValue, "-9223372036854775808L") CheckLiteralToString(Long.MaxValue, "9223372036854775807L") ' float CheckLiteralToString(0.0F, "0F") CheckLiteralToString(0.012345F, "0.012345F") #If NET472 Then CheckLiteralToString(Single.MaxValue, "3.40282347E+38F") #Else CheckLiteralToString(Single.MaxValue, "3.4028235E+38F") #End If ' double CheckLiteralToString(0.0, "0") CheckLiteralToString(0.012345, "0.012345") CheckLiteralToString(Double.MaxValue, "1.7976931348623157E+308") ' decimal CheckLiteralToString(0D, "0D") CheckLiteralToString(0.012345D, "0.012345D") CheckLiteralToString(Decimal.MaxValue, "79228162514264337593543950335D") End Sub Private Shared Sub CheckLiteralToString(value As Object, expected As String) Dim factoryType As System.Type = GetType(SyntaxFactory) Dim literalMethods = factoryType.GetMethods().Where(Function(m) m.Name = "Literal" AndAlso m.GetParameters().Count() = 1) Dim literalMethod = literalMethods.Single(Function(m) m.GetParameters().Single().ParameterType = value.GetType()) Assert.Equal(expected, literalMethod.Invoke(Nothing, {value}).ToString()) End Sub <Fact> Public Shared Sub TestParseTypeNameOptions() Dim options As VisualBasicParseOptions = TestOptions.Regular Dim code = " #If Variable String #Else Integer #End If" Dim type1 = SyntaxFactory.ParseTypeName(code, options:=options.WithPreprocessorSymbols(New KeyValuePair(Of String, Object)("Variable", "True"))) Assert.Equal("String", type1.ToString()) Dim type2 = SyntaxFactory.ParseTypeName(code, options:=options) Assert.Equal("Integer", type2.ToString()) End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/CSharp/Test/PersistentStorage/Mocks/AuthorizationServiceMock.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. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceHub.Framework.Services; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class AuthorizationServiceMock : IAuthorizationService { public event EventHandler? CredentialsChanged; public event EventHandler? AuthorizationChanged; internal bool Allow { get; set; } = true; public ValueTask<bool> CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { return new ValueTask<bool>(this.Allow); } public ValueTask<IReadOnlyDictionary<string, string>> GetCredentialsAsync(CancellationToken cancellationToken = default) { 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. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceHub.Framework.Services; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class AuthorizationServiceMock : IAuthorizationService { public event EventHandler? CredentialsChanged; public event EventHandler? AuthorizationChanged; internal bool Allow { get; set; } = true; public ValueTask<bool> CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { return new ValueTask<bool>(this.Allow); } public ValueTask<IReadOnlyDictionary<string, string>> GetCredentialsAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Portable/Syntax/ExpressionStatementSyntax.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 ExpressionStatementSyntax { /// <summary> /// Returns true if the <see cref="Expression"/> property is allowed by the rules of the /// language to be an arbitrary expression, not just a statement expression. /// </summary> /// <remarks> /// True if, for example, this expression statement represents the last expression statement /// of the interactive top-level code. /// </remarks> public bool AllowsAnyExpression { get { var semicolon = SemicolonToken; return semicolon.IsMissing && !semicolon.ContainsDiagnostics; } } public ExpressionStatementSyntax Update(ExpressionSyntax expression, SyntaxToken semicolonToken) => Update(AttributeLists, expression, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ExpressionStatementSyntax ExpressionStatement(ExpressionSyntax expression, SyntaxToken semicolonToken) => ExpressionStatement(attributeLists: default, expression, 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 ExpressionStatementSyntax { /// <summary> /// Returns true if the <see cref="Expression"/> property is allowed by the rules of the /// language to be an arbitrary expression, not just a statement expression. /// </summary> /// <remarks> /// True if, for example, this expression statement represents the last expression statement /// of the interactive top-level code. /// </remarks> public bool AllowsAnyExpression { get { var semicolon = SemicolonToken; return semicolon.IsMissing && !semicolon.ContainsDiagnostics; } } public ExpressionStatementSyntax Update(ExpressionSyntax expression, SyntaxToken semicolonToken) => Update(AttributeLists, expression, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ExpressionStatementSyntax ExpressionStatement(ExpressionSyntax expression, SyntaxToken semicolonToken) => ExpressionStatement(attributeLists: default, expression, semicolonToken); } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.PreferFrameworkType; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PreferFrameworkTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private OptionsCollection NoFrameworkType => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; private OptionsCollection FrameworkTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotWhenOptionsAreNotSet() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|int|] x = 1; } }", new TestParameters(options: NoFrameworkType)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnSystemVoid() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|void|] Method() { } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnUserdefinedType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p; } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnQualifiedTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"class Program { void Method() { [|System.Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|List|]<int> p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnIdentifierThatIsNotTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { int [|p|]; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementWhenNoUsingFound() { var code = @"class Program { [|string|] _myfield = 5; }"; var expected = @"class Program { System.String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclaration() { var code = @"using System; class Program { [|int|] _myfield; }"; var expected = @"using System; class Program { Int32 _myfield; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclarationWithInitializer() { var code = @"using System; class Program { [|string|] _myfield = 5; }"; var expected = @"using System; class Program { String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateDeclaration() { var code = @"using System; class Program { public delegate [|int|] PerformCalculation(int x, int y); }"; var expected = @"using System; class Program { public delegate Int32 PerformCalculation(int x, int y); }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task PropertyDeclaration() { var code = @"using System; class Program { public [|long|] MyProperty { get; set; } }"; var expected = @"using System; class Program { public Int64 MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericPropertyDeclaration() { var code = @"using System; using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public List<Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementInGenericTypeParameter() { var code = @"using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System.Collections.Generic; class Program { public List<System.Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationReturnType() { var code = @"using System; class Program { public [|long|] Method() { } }"; var expected = @"using System; class Program { public Int64 Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationParameters() { var code = @"using System; class Program { public void Method([|double|] d) { } }"; var expected = @"using System; class Program { public void Method(Double d) { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericMethodInvocation() { var code = @"using System; class Program { public void Method<T>() { } public void Test() { Method<[|int|]>(); } }"; var expected = @"using System; class Program { public void Method<T>() { } public void Test() { Method<Int32>(); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LocalDeclaration() { var code = @"using System; class Program { void Method() { [|int|] f = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 f = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess() { var code = @"using System; class Program { void Method() { Console.Write([|int|].MaxValue); } }"; var expected = @"using System; class Program { void Method() { Console.Write(Int32.MaxValue); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess2() { var code = @"using System; class Program { void Method() { var x = [|int|].Parse(""1""); } }"; var expected = @"using System; class Program { void Method() { var x = Int32.Parse(""1""); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DocCommentTriviaCrefExpression() { var code = @"using System; class Program { /// <see cref=""[|int|].MaxValue""/> void Method() { } }"; var expected = @"using System; class Program { /// <see cref=""Int32.MaxValue""/> void Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DefaultExpression() { var code = @"using System; class Program { void Method() { var v = default([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = default(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TypeOfExpression() { var code = @"using System; class Program { void Method() { var v = typeof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = typeof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NameOfExpression() { var code = @"using System; class Program { void Method() { var v = nameof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = nameof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FormalParametersWithinLambdaExression() { var code = @"using System; class Program { void Method() { Func<int, int> func3 = ([|int|] z) => z + 1; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func3 = (Int32 z) => z + 1; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateMethodExpression() { var code = @"using System; class Program { void Method() { Func<int, int> func7 = delegate ([|int|] dx) { return dx + 1; }; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func7 = delegate (Int32 dx) { return dx + 1; }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ObjectCreationExpression() { var code = @"using System; class Program { void Method() { string s2 = new [|string|]('c', 1); } }"; var expected = @"using System; class Program { void Method() { string s2 = new String('c', 1); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayDeclaration() { var code = @"using System; class Program { void Method() { [|int|][] k = new int[4]; } }"; var expected = @"using System; class Program { void Method() { Int32[] k = new int[4]; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayInitializer() { var code = @"using System; class Program { void Method() { int[] k = new [|int|][] { 1, 2, 3 }; } }"; var expected = @"using System; class Program { void Method() { int[] k = new Int32[] { 1, 2, 3 }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MultiDimentionalArrayAsGenericTypeParameter() { var code = @"using System; using System.Collections.Generic; class Program { void Method() { List<[|string|][][,][,,,]> a; } }"; var expected = @"using System; using System.Collections.Generic; class Program { void Method() { List<String[][,][,,,]> a; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForStatement() { var code = @"using System; class Program { void Method() { for ([|int|] j = 0; j < 4; j++) { } } }"; var expected = @"using System; class Program { void Method() { for (Int32 j = 0; j < 4; j++) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForeachStatement() { var code = @"using System; class Program { void Method() { foreach ([|int|] item in new int[] { 1, 2, 3 }) { } } }"; var expected = @"using System; class Program { void Method() { foreach (Int32 item in new int[] { 1, 2, 3 }) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LeadingTrivia() { var code = @"using System; class Program { void Method() { // this is a comment [|int|] x = 5; } }"; var expected = @"using System; class Program { void Method() { // this is a comment Int32 x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TrailingTrivia() { var code = @"using System; class Program { void Method() { [|int|] /* 2 */ x = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 /* 2 */ x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } } }
// Licensed to the .NET Foundation under one or more 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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.PreferFrameworkType; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PreferFrameworkTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private OptionsCollection NoFrameworkType => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; private OptionsCollection FrameworkTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo }, }; private OptionsCollection FrameworkTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotWhenOptionsAreNotSet() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|int|] x = 1; } }", new TestParameters(options: NoFrameworkType)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnSystemVoid() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|void|] Method() { } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnUserdefinedType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p; } }", new TestParameters(options: FrameworkTypeEverywhere)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnQualifiedTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"class Program { void Method() { [|System.Int32|] p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|List|]<int> p; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotOnIdentifierThatIsNotTypeSyntax() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { int [|p|]; } }", new TestParameters(options: FrameworkTypeInDeclaration)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementWhenNoUsingFound() { var code = @"class Program { [|string|] _myfield = 5; }"; var expected = @"class Program { System.String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclaration() { var code = @"using System; class Program { [|int|] _myfield; }"; var expected = @"using System; class Program { Int32 _myfield; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FieldDeclarationWithInitializer() { var code = @"using System; class Program { [|string|] _myfield = 5; }"; var expected = @"using System; class Program { String _myfield = 5; }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateDeclaration() { var code = @"using System; class Program { public delegate [|int|] PerformCalculation(int x, int y); }"; var expected = @"using System; class Program { public delegate Int32 PerformCalculation(int x, int y); }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task PropertyDeclaration() { var code = @"using System; class Program { public [|long|] MyProperty { get; set; } }"; var expected = @"using System; class Program { public Int64 MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericPropertyDeclaration() { var code = @"using System; using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public List<Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task QualifiedReplacementInGenericTypeParameter() { var code = @"using System.Collections.Generic; class Program { public List<[|long|]> MyProperty { get; set; } }"; var expected = @"using System.Collections.Generic; class Program { public List<System.Int64> MyProperty { get; set; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationReturnType() { var code = @"using System; class Program { public [|long|] Method() { } }"; var expected = @"using System; class Program { public Int64 Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MethodDeclarationParameters() { var code = @"using System; class Program { public void Method([|double|] d) { } }"; var expected = @"using System; class Program { public void Method(Double d) { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task GenericMethodInvocation() { var code = @"using System; class Program { public void Method<T>() { } public void Test() { Method<[|int|]>(); } }"; var expected = @"using System; class Program { public void Method<T>() { } public void Test() { Method<Int32>(); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LocalDeclaration() { var code = @"using System; class Program { void Method() { [|int|] f = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 f = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess() { var code = @"using System; class Program { void Method() { Console.Write([|int|].MaxValue); } }"; var expected = @"using System; class Program { void Method() { Console.Write(Int32.MaxValue); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MemberAccess2() { var code = @"using System; class Program { void Method() { var x = [|int|].Parse(""1""); } }"; var expected = @"using System; class Program { void Method() { var x = Int32.Parse(""1""); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DocCommentTriviaCrefExpression() { var code = @"using System; class Program { /// <see cref=""[|int|].MaxValue""/> void Method() { } }"; var expected = @"using System; class Program { /// <see cref=""Int32.MaxValue""/> void Method() { } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DefaultExpression() { var code = @"using System; class Program { void Method() { var v = default([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = default(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TypeOfExpression() { var code = @"using System; class Program { void Method() { var v = typeof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = typeof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NameOfExpression() { var code = @"using System; class Program { void Method() { var v = nameof([|int|]); } }"; var expected = @"using System; class Program { void Method() { var v = nameof(Int32); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task FormalParametersWithinLambdaExression() { var code = @"using System; class Program { void Method() { Func<int, int> func3 = ([|int|] z) => z + 1; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func3 = (Int32 z) => z + 1; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task DelegateMethodExpression() { var code = @"using System; class Program { void Method() { Func<int, int> func7 = delegate ([|int|] dx) { return dx + 1; }; } }"; var expected = @"using System; class Program { void Method() { Func<int, int> func7 = delegate (Int32 dx) { return dx + 1; }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ObjectCreationExpression() { var code = @"using System; class Program { void Method() { string s2 = new [|string|]('c', 1); } }"; var expected = @"using System; class Program { void Method() { string s2 = new String('c', 1); } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayDeclaration() { var code = @"using System; class Program { void Method() { [|int|][] k = new int[4]; } }"; var expected = @"using System; class Program { void Method() { Int32[] k = new int[4]; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ArrayInitializer() { var code = @"using System; class Program { void Method() { int[] k = new [|int|][] { 1, 2, 3 }; } }"; var expected = @"using System; class Program { void Method() { int[] k = new Int32[] { 1, 2, 3 }; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task MultiDimentionalArrayAsGenericTypeParameter() { var code = @"using System; using System.Collections.Generic; class Program { void Method() { List<[|string|][][,][,,,]> a; } }"; var expected = @"using System; using System.Collections.Generic; class Program { void Method() { List<String[][,][,,,]> a; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForStatement() { var code = @"using System; class Program { void Method() { for ([|int|] j = 0; j < 4; j++) { } } }"; var expected = @"using System; class Program { void Method() { for (Int32 j = 0; j < 4; j++) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task ForeachStatement() { var code = @"using System; class Program { void Method() { foreach ([|int|] item in new int[] { 1, 2, 3 }) { } } }"; var expected = @"using System; class Program { void Method() { foreach (Int32 item in new int[] { 1, 2, 3 }) { } } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task LeadingTrivia() { var code = @"using System; class Program { void Method() { // this is a comment [|int|] x = 5; } }"; var expected = @"using System; class Program { void Method() { // this is a comment Int32 x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task TrailingTrivia() { var code = @"using System; class Program { void Method() { [|int|] /* 2 */ x = 5; } }"; var expected = @"using System; class Program { void Method() { Int32 /* 2 */ x = 5; } }"; await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectCreationInfo.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 Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProjectCreationInfo { public string? AssemblyName { get; set; } public CompilationOptions? CompilationOptions { get; set; } public string? FilePath { get; set; } public ParseOptions? ParseOptions { get; set; } public IVsHierarchy? Hierarchy { get; set; } public Guid ProjectGuid { 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 Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed class VisualStudioProjectCreationInfo { public string? AssemblyName { get; set; } public CompilationOptions? CompilationOptions { get; set; } public string? FilePath { get; set; } public ParseOptions? ParseOptions { get; set; } public IVsHierarchy? Hierarchy { get; set; } public Guid ProjectGuid { get; set; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/Portable/Syntax/SyntaxWalkerDepth.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> /// Syntax the <see cref="SyntaxWalker"/> should descend into. /// </summary> public enum SyntaxWalkerDepth : int { /// <summary> /// descend into only nodes /// </summary> Node = 0, /// <summary> /// descend into nodes and tokens /// </summary> Token = 1, /// <summary> /// descend into nodes, tokens and trivia /// </summary> Trivia = 2, /// <summary> /// descend into everything /// </summary> StructuredTrivia = 3, } }
// Licensed to the .NET Foundation under one or more 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> /// Syntax the <see cref="SyntaxWalker"/> should descend into. /// </summary> public enum SyntaxWalkerDepth : int { /// <summary> /// descend into only nodes /// </summary> Node = 0, /// <summary> /// descend into nodes and tokens /// </summary> Token = 1, /// <summary> /// descend into nodes, tokens and trivia /// </summary> Trivia = 2, /// <summary> /// descend into everything /// </summary> StructuredTrivia = 3, } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.StructData.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.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class StructData Public Property Name As String Public Property Position As Object = 0 Public Property Bases As Object Public Property ImplementedInterfaces As Object Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault 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. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class StructData Public Property Name As String Public Property Position As Object = 0 Public Property Bases As Object Public Property ImplementedInterfaces As Object Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault End Class End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptInlineRenameInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal sealed class VSTypeScriptInlineRenameInfo : IInlineRenameInfo { private readonly IVSTypeScriptInlineRenameInfo _info; public VSTypeScriptInlineRenameInfo(IVSTypeScriptInlineRenameInfo info) { Contract.ThrowIfNull(info); _info = info; } public bool CanRename => _info.CanRename; public string LocalizedErrorMessage => _info.LocalizedErrorMessage; public TextSpan TriggerSpan => _info.TriggerSpan; public bool HasOverloads => _info.HasOverloads; public bool ForceRenameOverloads => _info.ForceRenameOverloads; public string DisplayName => _info.DisplayName; public string FullDisplayName => _info.FullDisplayName; public Glyph Glyph => VSTypeScriptGlyphHelpers.ConvertTo(_info.Glyph); public ImmutableArray<DocumentSpan> DefinitionLocations => _info.DefinitionLocations; public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { var set = await _info.FindRenameLocationsAsync(optionSet, cancellationToken).ConfigureAwait(false); if (set != null) { return new VSTypeScriptInlineRenameLocationSet(set); } else { return null; } } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) { return _info.GetConflictEditSpan(new VSTypeScriptInlineRenameLocationWrapper( new InlineRenameLocation(location.Document, location.TextSpan)), replacementText, cancellationToken); } public string GetFinalSymbolName(string replacementText) => _info.GetFinalSymbolName(replacementText); public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) { return _info.GetReferenceEditSpan(new VSTypeScriptInlineRenameLocationWrapper( new InlineRenameLocation(location.Document, location.TextSpan)), cancellationToken); } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => _info.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => _info.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal sealed class VSTypeScriptInlineRenameInfo : IInlineRenameInfo { private readonly IVSTypeScriptInlineRenameInfo _info; public VSTypeScriptInlineRenameInfo(IVSTypeScriptInlineRenameInfo info) { Contract.ThrowIfNull(info); _info = info; } public bool CanRename => _info.CanRename; public string LocalizedErrorMessage => _info.LocalizedErrorMessage; public TextSpan TriggerSpan => _info.TriggerSpan; public bool HasOverloads => _info.HasOverloads; public bool ForceRenameOverloads => _info.ForceRenameOverloads; public string DisplayName => _info.DisplayName; public string FullDisplayName => _info.FullDisplayName; public Glyph Glyph => VSTypeScriptGlyphHelpers.ConvertTo(_info.Glyph); public ImmutableArray<DocumentSpan> DefinitionLocations => _info.DefinitionLocations; public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { var set = await _info.FindRenameLocationsAsync(optionSet, cancellationToken).ConfigureAwait(false); if (set != null) { return new VSTypeScriptInlineRenameLocationSet(set); } else { return null; } } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) { return _info.GetConflictEditSpan(new VSTypeScriptInlineRenameLocationWrapper( new InlineRenameLocation(location.Document, location.TextSpan)), replacementText, cancellationToken); } public string GetFinalSymbolName(string replacementText) => _info.GetFinalSymbolName(replacementText); public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) { return _info.GetReferenceEditSpan(new VSTypeScriptInlineRenameLocationWrapper( new InlineRenameLocation(location.Document, location.TextSpan)), cancellationToken); } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => _info.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => _info.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Workspaces/Remote/ServiceHub/Services/ProjectTelemetry/RemoteProjectTelemetryIncrementalAnalyzer.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ProjectTelemetry; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.Remote { internal class RemoteProjectTelemetryIncrementalAnalyzer : IncrementalAnalyzerBase { /// <summary> /// Channel back to VS to inform it of the designer attributes we discover. /// </summary> private readonly RemoteCallback<IRemoteProjectTelemetryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; private readonly object _gate = new object(); private readonly Dictionary<ProjectId, ProjectTelemetryData> _projectToData = new Dictionary<ProjectId, ProjectTelemetryData>(); public RemoteProjectTelemetryIncrementalAnalyzer(RemoteCallback<IRemoteProjectTelemetryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } /// <summary> /// Collects data from <paramref name="project"/> and reports it to the telemetry service. /// </summary> /// <remarks> /// Only sends data to the telemetry service when one of the collected data points changes, /// not necessarily every time this code is called. /// </remarks> public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { if (!semanticsChanged) return; var projectId = project.Id; var language = project.Language; var analyzerReferencesCount = project.AnalyzerReferences.Count; var projectReferencesCount = project.AllProjectReferences.Count; var metadataReferencesCount = project.MetadataReferences.Count; var documentsCount = project.DocumentIds.Count; var additionalDocumentsCount = project.AdditionalDocumentIds.Count; var info = new ProjectTelemetryData( projectId: projectId, language: language, analyzerReferencesCount: analyzerReferencesCount, projectReferencesCount: projectReferencesCount, metadataReferencesCount: metadataReferencesCount, documentsCount: documentsCount, additionalDocumentsCount: additionalDocumentsCount); lock (_gate) { if (_projectToData.TryGetValue(projectId, out var existingInfo) && existingInfo.Equals(info)) { // already have reported this. No need to notify VS. return; } _projectToData[projectId] = info; } await _callback.InvokeAsync( (callback, cancellationToken) => callback.ReportProjectTelemetryDataAsync(_callbackId, info, cancellationToken), cancellationToken).ConfigureAwait(false); } public override Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_gate) { _projectToData.Remove(projectId); } return Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ProjectTelemetry; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.Remote { internal class RemoteProjectTelemetryIncrementalAnalyzer : IncrementalAnalyzerBase { /// <summary> /// Channel back to VS to inform it of the designer attributes we discover. /// </summary> private readonly RemoteCallback<IRemoteProjectTelemetryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; private readonly object _gate = new object(); private readonly Dictionary<ProjectId, ProjectTelemetryData> _projectToData = new Dictionary<ProjectId, ProjectTelemetryData>(); public RemoteProjectTelemetryIncrementalAnalyzer(RemoteCallback<IRemoteProjectTelemetryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } /// <summary> /// Collects data from <paramref name="project"/> and reports it to the telemetry service. /// </summary> /// <remarks> /// Only sends data to the telemetry service when one of the collected data points changes, /// not necessarily every time this code is called. /// </remarks> public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { if (!semanticsChanged) return; var projectId = project.Id; var language = project.Language; var analyzerReferencesCount = project.AnalyzerReferences.Count; var projectReferencesCount = project.AllProjectReferences.Count; var metadataReferencesCount = project.MetadataReferences.Count; var documentsCount = project.DocumentIds.Count; var additionalDocumentsCount = project.AdditionalDocumentIds.Count; var info = new ProjectTelemetryData( projectId: projectId, language: language, analyzerReferencesCount: analyzerReferencesCount, projectReferencesCount: projectReferencesCount, metadataReferencesCount: metadataReferencesCount, documentsCount: documentsCount, additionalDocumentsCount: additionalDocumentsCount); lock (_gate) { if (_projectToData.TryGetValue(projectId, out var existingInfo) && existingInfo.Equals(info)) { // already have reported this. No need to notify VS. return; } _projectToData[projectId] = info; } await _callback.InvokeAsync( (callback, cancellationToken) => callback.ReportProjectTelemetryDataAsync(_callbackId, info, cancellationToken), cancellationToken).ConfigureAwait(false); } public override Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_gate) { _projectToData.Remove(projectId); } return Task.CompletedTask; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/BaseTypeResolution.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.Metadata Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE Public Class BaseTypeResolution Inherits BasicTestBase <Fact()> Public Sub Test1() Dim assembly = MetadataTestHelpers.LoadFromBytes(TestMetadata.ResourcesNet40.mscorlib) TestBaseTypeResolutionHelper1(assembly) Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( {TestResources.General.MDTestLib1, TestResources.General.MDTestLib2, TestMetadata.ResourcesNet40.mscorlib}) TestBaseTypeResolutionHelper2(assemblies) assemblies = MetadataTestHelpers.GetSymbolsForReferences( {TestResources.General.MDTestLib1, TestResources.General.MDTestLib2}) TestBaseTypeResolutionHelper3(assemblies) assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestReferences.SymbolsTests.MultiModule.Assembly, TestReferences.SymbolsTests.MultiModule.Consumer }) TestBaseTypeResolutionHelper4(assemblies) End Sub Private Sub TestBaseTypeResolutionHelper1(assembly As AssemblySymbol) Dim module0 = assembly.Modules(0) Dim sys = module0.GlobalNamespace.GetMembers("SYSTEM") Dim collections = DirectCast(sys(0), NamespaceSymbol).GetMembers("CollectionS") Dim generic = DirectCast(collections(0), NamespaceSymbol).GetMembers("Generic") Dim dictionary = DirectCast(generic(0), NamespaceSymbol).GetMembers("Dictionary") Dim base = DirectCast(dictionary(0), NamedTypeSymbol).BaseType AssertBaseType(base, "System.Object") Assert.Null(base.BaseType) Dim concurrent = DirectCast(collections(0), NamespaceSymbol).GetMembers("Concurrent") Dim orderablePartitioners = DirectCast(concurrent(0), NamespaceSymbol).GetMembers("OrderablePartitioner") Dim orderablePartitioner As NamedTypeSymbol = Nothing For Each p In orderablePartitioners Dim t = TryCast(p, NamedTypeSymbol) If t IsNot Nothing AndAlso t.Arity = 1 Then orderablePartitioner = t Exit For End If Next base = orderablePartitioner.BaseType AssertBaseType(base, "System.Collections.Concurrent.Partitioner(Of TSource)") Assert.Same(DirectCast(base, NamedTypeSymbol).TypeArguments(0), orderablePartitioner.TypeParameters(0)) Dim partitioners = DirectCast(concurrent(0), NamespaceSymbol).GetMembers("Partitioner") Dim partitioner As NamedTypeSymbol = Nothing For Each p In partitioners Dim t = TryCast(p, NamedTypeSymbol) If t IsNot Nothing AndAlso t.Arity = 0 Then partitioner = t Exit For End If Next Assert.NotNull(partitioner) End Sub Private Sub TestBaseTypeResolutionHelper2(assemblies() As AssemblySymbol) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(1).Modules(0) Dim TC2 = module1.GlobalNamespace.GetTypeMembers("TC2").Single() Dim TC3 = module1.GlobalNamespace.GetTypeMembers("TC3").Single() Dim TC4 = module1.GlobalNamespace.GetTypeMembers("TC4").Single() AssertBaseType(TC2.BaseType, "C1(Of TC2_T1).C2(Of TC2_T2)") AssertBaseType(TC3.BaseType, "C1(Of TC3_T1).C3") AssertBaseType(TC4.BaseType, "C1(Of TC4_T1).C3.C4(Of TC4_T2)") Dim C1 = module1.GlobalNamespace.GetTypeMembers("C1").Single() AssertBaseType(C1.BaseType, "System.Object") Assert.Equal(0, C1.Interfaces.Length()) Dim TC5 = module2.GlobalNamespace.GetTypeMembers("TC5").Single() Dim TC6 = module2.GlobalNamespace.GetTypeMembers("TC6").Single() Dim TC7 = module2.GlobalNamespace.GetTypeMembers("TC7").Single() Dim TC8 = module2.GlobalNamespace.GetTypeMembers("TC8").Single() Dim TC9 = TC6.GetTypeMembers("TC9").Single() AssertBaseType(TC5.BaseType, "C1(Of TC5_T1).C2(Of TC5_T2)") AssertBaseType(TC6.BaseType, "C1(Of TC6_T1).C3") AssertBaseType(TC7.BaseType, "C1(Of TC7_T1).C3.C4(Of TC7_T2)") AssertBaseType(TC8.BaseType, "C1(Of System.Type)") AssertBaseType(TC9.BaseType, "TC6(Of TC6_T1)") Dim CorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType(Of NamespaceSymbol)().Single() Dim CorTypes_Derived = CorTypes.GetTypeMembers("Derived").Single() AssertBaseType(CorTypes_Derived.BaseType, "CorTypes.NS.Base(Of System.Boolean, System.SByte, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Single, System.Double, System.Char, System.String, System.IntPtr, System.UIntPtr, System.Object)") Dim CorTypes_Derived1 = CorTypes.GetTypeMembers("Derived1").Single() AssertBaseType(CorTypes_Derived1.BaseType, "CorTypes.Base(Of System.Int32(), System.Double(,))") Dim I101 = module1.GlobalNamespace.GetTypeMembers("I101").Single() Dim I102 = module1.GlobalNamespace.GetTypeMembers("I102").Single() Dim C203 = module1.GlobalNamespace.GetTypeMembers("C203").Single() Assert.Equal(1, C203.Interfaces.Length()) Assert.Same(I101, C203.Interfaces(0)) Dim C204 = module1.GlobalNamespace.GetTypeMembers("C204").Single() Assert.Equal(2, C204.Interfaces.Length()) Assert.Same(I101, C204.Interfaces(0)) Assert.Same(I102, C204.Interfaces(1)) Return End Sub Private Sub TestBaseTypeResolutionHelper3(assemblies() As AssemblySymbol) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(1).Modules(0) Dim CorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType(Of NamespaceSymbol)().Single() Dim CorTypes_Derived = CorTypes.GetTypeMembers("Derived").Single() AssertBaseType(CorTypes_Derived.BaseType, "CorTypes.NS.Base(Of System.Boolean[missing], System.SByte[missing], System.Byte[missing], System.Int16[missing], System.UInt16[missing], System.Int32[missing], System.UInt32[missing], System.Int64[missing], System.UInt64[missing], System.Single[missing], System.Double[missing], System.Char[missing], System.String[missing], System.IntPtr[missing], System.UIntPtr[missing], System.Object[missing])") For Each arg In CorTypes_Derived.BaseType.TypeArguments() Assert.IsAssignableFrom(Of MissingMetadataTypeSymbol)(arg) Next Return End Sub Private Sub TestBaseTypeResolutionHelper4(assemblies() As AssemblySymbol) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(0).Modules(1) Dim module3 = assemblies(0).Modules(2) Dim module0 = assemblies(1).Modules(0) Dim Derived1 = module0.GlobalNamespace.GetTypeMembers("Derived1").Single() Dim base1 = Derived1.BaseType Dim Derived2 = module0.GlobalNamespace.GetTypeMembers("Derived2").Single() Dim base2 = Derived2.BaseType Dim Derived3 = module0.GlobalNamespace.GetTypeMembers("Derived3").Single() Dim base3 = Derived3.BaseType AssertBaseType(base1, "Class1") AssertBaseType(base2, "Class2") AssertBaseType(base3, "Class3") Assert.Same(base1, module1.GlobalNamespace.GetTypeMembers("Class1").Single()) Assert.Same(base2, module2.GlobalNamespace.GetTypeMembers("Class2").Single()) Assert.Same(base3, module3.GlobalNamespace.GetTypeMembers("Class3").Single()) End Sub Friend Shared Sub AssertBaseType(base As TypeSymbol, name As String) Assert.NotEqual(SymbolKind.ErrorType, base.Kind) Assert.Equal(name, base.ToTestDisplayString()) End Sub <Fact> Public Sub Test2() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( {TestResources.SymbolsTests.DifferByCase.Consumer, TestResources.SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase}) Dim module0 = TryCast(assemblies(0).Modules(0), PEModuleSymbol) Dim module1 = TryCast(assemblies(1).Modules(0), PEModuleSymbol) Dim bases As New HashSet(Of NamedTypeSymbol)() Dim TC1 = module0.GlobalNamespace.GetTypeMembers("TC1").Single() Dim base1 = TC1.BaseType bases.Add(base1) Assert.NotEqual(SymbolKind.ErrorType, base1.Kind) Assert.Equal("SomeName.Dummy", base1.ToTestDisplayString()) Dim TC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single() Dim base2 = TC2.BaseType bases.Add(base2) Assert.NotEqual(SymbolKind.ErrorType, base2.Kind) Assert.Equal("somEnamE", base2.ToTestDisplayString()) Dim TC3 = module0.GlobalNamespace.GetTypeMembers("TC3").Single() Dim base3 = TC3.BaseType bases.Add(base3) Assert.NotEqual(SymbolKind.ErrorType, base3.Kind) Assert.Equal("somEnamE1", base3.ToTestDisplayString()) Dim TC4 = module0.GlobalNamespace.GetTypeMembers("TC4").Single() Dim base4 = TC4.BaseType bases.Add(base4) Assert.NotEqual(SymbolKind.ErrorType, base4.Kind) Assert.Equal("SomeName1", base4.ToTestDisplayString()) Dim TC5 = module0.GlobalNamespace.GetTypeMembers("TC5").Single() Dim base5 = TC5.BaseType bases.Add(base5) Assert.NotEqual(SymbolKind.ErrorType, base5.Kind) Assert.Equal("somEnamE2.OtherName", base5.ToTestDisplayString()) Dim TC6 = module0.GlobalNamespace.GetTypeMembers("TC6").Single() Dim base6 = TC6.BaseType bases.Add(base6) Assert.NotEqual(SymbolKind.ErrorType, base6.Kind) Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString()) Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString()) Dim TC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single() Dim base7 = TC7.BaseType bases.Add(base7) Assert.NotEqual(SymbolKind.ErrorType, base7.Kind) Assert.Equal("NestingClass.somEnamE3", base7.ToTestDisplayString()) Dim TC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single() Dim base8 = TC8.BaseType bases.Add(base8) Assert.NotEqual(SymbolKind.ErrorType, base8.Kind) Assert.Equal("NestingClass.SomeName3", base8.ToTestDisplayString()) Assert.Equal(8, bases.Count) Assert.Equal(base1, module1.TypeHandleToTypeMap(DirectCast(base1, PENamedTypeSymbol).Handle)) Assert.Equal(base2, module1.TypeHandleToTypeMap(DirectCast(base2, PENamedTypeSymbol).Handle)) Assert.Equal(base3, module1.TypeHandleToTypeMap(DirectCast(base3, PENamedTypeSymbol).Handle)) Assert.Equal(base4, module1.TypeHandleToTypeMap(DirectCast(base4, PENamedTypeSymbol).Handle)) Assert.Equal(base5, module1.TypeHandleToTypeMap(DirectCast(base5, PENamedTypeSymbol).Handle)) Assert.Equal(base6, module1.TypeHandleToTypeMap(DirectCast(base6, PENamedTypeSymbol).Handle)) Assert.Equal(base7, module1.TypeHandleToTypeMap(DirectCast(base7, PENamedTypeSymbol).Handle)) Assert.Equal(base8, module1.TypeHandleToTypeMap(DirectCast(base8, PENamedTypeSymbol).Handle)) Assert.Equal(base1, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC1, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base2, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC2, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base3, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC3, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base4, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC4, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base5, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC5, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base6, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC6, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base7, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC7, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base8, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC8, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Dim assembly1 = DirectCast(assemblies(1), MetadataOrSourceAssemblySymbol) Assert.Equal(base1, assembly1.CachedTypeByEmittedName(base1.ToTestDisplayString())) Assert.Equal(base2, assembly1.CachedTypeByEmittedName(base2.ToTestDisplayString())) Assert.Equal(base3, assembly1.CachedTypeByEmittedName(base3.ToTestDisplayString())) Assert.Equal(base4, assembly1.CachedTypeByEmittedName(base4.ToTestDisplayString())) Assert.Equal(base5, assembly1.CachedTypeByEmittedName(base5.ToTestDisplayString())) Assert.Equal(base6, assembly1.CachedTypeByEmittedName(base6.ToTestDisplayString())) Assert.Equal(base7.ContainingType, assembly1.CachedTypeByEmittedName(base7.ContainingType.ToTestDisplayString())) Assert.Equal(7, assembly1.EmittedNameToTypeMapCount) End Sub <Fact()> Public Sub Test3() Dim mscorlibRef = TestMetadata.Net40.mscorlib Dim c1 = VisualBasicCompilation.Create("Test", references:={mscorlibRef}) Assert.Equal("System.Object", DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()) Dim MTTestLib1Ref = TestReferences.SymbolsTests.V1.MTTestLib1.dll Dim c2 = VisualBasicCompilation.Create("Test2", references:={MTTestLib1Ref}) Assert.Equal("System.Object[missing]", DirectCast(c2.Assembly.Modules(0), SourceModuleSymbol).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()) End Sub <Fact> Public Sub CrossModuleReferences1() Dim compilationDef1 = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Class Test1 Inherits M3 End Class Class Test2 Inherits M4 End Class ]]></file> </compilation> Dim crossRefModule1 = TestReferences.SymbolsTests.netModule.CrossRefModule1 Dim crossRefModule2 = TestReferences.SymbolsTests.netModule.CrossRefModule2 Dim crossRefLib = TestReferences.SymbolsTests.netModule.CrossRefLib Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(compilationDef1, {crossRefLib}, TestOptions.ReleaseDll) AssertNoErrors(compilation1) Dim test1 = compilation1.GetTypeByMetadataName("Test1") Dim test2 = compilation1.GetTypeByMetadataName("Test2") Assert.False(test1.BaseType.IsErrorType()) Assert.False(test1.BaseType.BaseType.IsErrorType()) Assert.False(test2.BaseType.IsErrorType()) Assert.False(test2.BaseType.BaseType.IsErrorType()) Assert.False(test2.BaseType.BaseType.BaseType.IsErrorType()) Dim compilationDef2 = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Public Class M3 Inherits M1 End Class Public Class M4 Inherits M2 End Class ]]></file> </compilation> Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {crossRefModule1, crossRefModule2}, TestOptions.ReleaseDll) AssertNoErrors(compilation2) Dim m3 = compilation2.GetTypeByMetadataName("M3") Dim m4 = compilation2.GetTypeByMetadataName("M4") Assert.False(m3.BaseType.IsErrorType()) Assert.False(m3.BaseType.BaseType.IsErrorType()) Assert.False(m4.BaseType.IsErrorType()) Assert.False(m4.BaseType.BaseType.IsErrorType()) Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {crossRefModule2}, TestOptions.ReleaseDll) m3 = compilation3.GetTypeByMetadataName("M3") m4 = compilation3.GetTypeByMetadataName("M4") Assert.True(m3.BaseType.IsErrorType()) Assert.False(m4.BaseType.IsErrorType()) Assert.True(m4.BaseType.BaseType.IsErrorType()) AssertTheseDiagnostics(compilation3, <expected> BC37221: Reference to 'CrossRefModule1.netmodule' netmodule missing. BC30002: Type 'M1' is not defined. Inherits M1 ~~ BC30653: Reference required to module 'CrossRefModule1.netmodule' containing the type 'M1'. Add one to your project. Inherits M2 ~~ </expected>) 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.Metadata Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE Public Class BaseTypeResolution Inherits BasicTestBase <Fact()> Public Sub Test1() Dim assembly = MetadataTestHelpers.LoadFromBytes(TestMetadata.ResourcesNet40.mscorlib) TestBaseTypeResolutionHelper1(assembly) Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( {TestResources.General.MDTestLib1, TestResources.General.MDTestLib2, TestMetadata.ResourcesNet40.mscorlib}) TestBaseTypeResolutionHelper2(assemblies) assemblies = MetadataTestHelpers.GetSymbolsForReferences( {TestResources.General.MDTestLib1, TestResources.General.MDTestLib2}) TestBaseTypeResolutionHelper3(assemblies) assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestReferences.SymbolsTests.MultiModule.Assembly, TestReferences.SymbolsTests.MultiModule.Consumer }) TestBaseTypeResolutionHelper4(assemblies) End Sub Private Sub TestBaseTypeResolutionHelper1(assembly As AssemblySymbol) Dim module0 = assembly.Modules(0) Dim sys = module0.GlobalNamespace.GetMembers("SYSTEM") Dim collections = DirectCast(sys(0), NamespaceSymbol).GetMembers("CollectionS") Dim generic = DirectCast(collections(0), NamespaceSymbol).GetMembers("Generic") Dim dictionary = DirectCast(generic(0), NamespaceSymbol).GetMembers("Dictionary") Dim base = DirectCast(dictionary(0), NamedTypeSymbol).BaseType AssertBaseType(base, "System.Object") Assert.Null(base.BaseType) Dim concurrent = DirectCast(collections(0), NamespaceSymbol).GetMembers("Concurrent") Dim orderablePartitioners = DirectCast(concurrent(0), NamespaceSymbol).GetMembers("OrderablePartitioner") Dim orderablePartitioner As NamedTypeSymbol = Nothing For Each p In orderablePartitioners Dim t = TryCast(p, NamedTypeSymbol) If t IsNot Nothing AndAlso t.Arity = 1 Then orderablePartitioner = t Exit For End If Next base = orderablePartitioner.BaseType AssertBaseType(base, "System.Collections.Concurrent.Partitioner(Of TSource)") Assert.Same(DirectCast(base, NamedTypeSymbol).TypeArguments(0), orderablePartitioner.TypeParameters(0)) Dim partitioners = DirectCast(concurrent(0), NamespaceSymbol).GetMembers("Partitioner") Dim partitioner As NamedTypeSymbol = Nothing For Each p In partitioners Dim t = TryCast(p, NamedTypeSymbol) If t IsNot Nothing AndAlso t.Arity = 0 Then partitioner = t Exit For End If Next Assert.NotNull(partitioner) End Sub Private Sub TestBaseTypeResolutionHelper2(assemblies() As AssemblySymbol) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(1).Modules(0) Dim TC2 = module1.GlobalNamespace.GetTypeMembers("TC2").Single() Dim TC3 = module1.GlobalNamespace.GetTypeMembers("TC3").Single() Dim TC4 = module1.GlobalNamespace.GetTypeMembers("TC4").Single() AssertBaseType(TC2.BaseType, "C1(Of TC2_T1).C2(Of TC2_T2)") AssertBaseType(TC3.BaseType, "C1(Of TC3_T1).C3") AssertBaseType(TC4.BaseType, "C1(Of TC4_T1).C3.C4(Of TC4_T2)") Dim C1 = module1.GlobalNamespace.GetTypeMembers("C1").Single() AssertBaseType(C1.BaseType, "System.Object") Assert.Equal(0, C1.Interfaces.Length()) Dim TC5 = module2.GlobalNamespace.GetTypeMembers("TC5").Single() Dim TC6 = module2.GlobalNamespace.GetTypeMembers("TC6").Single() Dim TC7 = module2.GlobalNamespace.GetTypeMembers("TC7").Single() Dim TC8 = module2.GlobalNamespace.GetTypeMembers("TC8").Single() Dim TC9 = TC6.GetTypeMembers("TC9").Single() AssertBaseType(TC5.BaseType, "C1(Of TC5_T1).C2(Of TC5_T2)") AssertBaseType(TC6.BaseType, "C1(Of TC6_T1).C3") AssertBaseType(TC7.BaseType, "C1(Of TC7_T1).C3.C4(Of TC7_T2)") AssertBaseType(TC8.BaseType, "C1(Of System.Type)") AssertBaseType(TC9.BaseType, "TC6(Of TC6_T1)") Dim CorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType(Of NamespaceSymbol)().Single() Dim CorTypes_Derived = CorTypes.GetTypeMembers("Derived").Single() AssertBaseType(CorTypes_Derived.BaseType, "CorTypes.NS.Base(Of System.Boolean, System.SByte, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Single, System.Double, System.Char, System.String, System.IntPtr, System.UIntPtr, System.Object)") Dim CorTypes_Derived1 = CorTypes.GetTypeMembers("Derived1").Single() AssertBaseType(CorTypes_Derived1.BaseType, "CorTypes.Base(Of System.Int32(), System.Double(,))") Dim I101 = module1.GlobalNamespace.GetTypeMembers("I101").Single() Dim I102 = module1.GlobalNamespace.GetTypeMembers("I102").Single() Dim C203 = module1.GlobalNamespace.GetTypeMembers("C203").Single() Assert.Equal(1, C203.Interfaces.Length()) Assert.Same(I101, C203.Interfaces(0)) Dim C204 = module1.GlobalNamespace.GetTypeMembers("C204").Single() Assert.Equal(2, C204.Interfaces.Length()) Assert.Same(I101, C204.Interfaces(0)) Assert.Same(I102, C204.Interfaces(1)) Return End Sub Private Sub TestBaseTypeResolutionHelper3(assemblies() As AssemblySymbol) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(1).Modules(0) Dim CorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType(Of NamespaceSymbol)().Single() Dim CorTypes_Derived = CorTypes.GetTypeMembers("Derived").Single() AssertBaseType(CorTypes_Derived.BaseType, "CorTypes.NS.Base(Of System.Boolean[missing], System.SByte[missing], System.Byte[missing], System.Int16[missing], System.UInt16[missing], System.Int32[missing], System.UInt32[missing], System.Int64[missing], System.UInt64[missing], System.Single[missing], System.Double[missing], System.Char[missing], System.String[missing], System.IntPtr[missing], System.UIntPtr[missing], System.Object[missing])") For Each arg In CorTypes_Derived.BaseType.TypeArguments() Assert.IsAssignableFrom(Of MissingMetadataTypeSymbol)(arg) Next Return End Sub Private Sub TestBaseTypeResolutionHelper4(assemblies() As AssemblySymbol) Dim module1 = assemblies(0).Modules(0) Dim module2 = assemblies(0).Modules(1) Dim module3 = assemblies(0).Modules(2) Dim module0 = assemblies(1).Modules(0) Dim Derived1 = module0.GlobalNamespace.GetTypeMembers("Derived1").Single() Dim base1 = Derived1.BaseType Dim Derived2 = module0.GlobalNamespace.GetTypeMembers("Derived2").Single() Dim base2 = Derived2.BaseType Dim Derived3 = module0.GlobalNamespace.GetTypeMembers("Derived3").Single() Dim base3 = Derived3.BaseType AssertBaseType(base1, "Class1") AssertBaseType(base2, "Class2") AssertBaseType(base3, "Class3") Assert.Same(base1, module1.GlobalNamespace.GetTypeMembers("Class1").Single()) Assert.Same(base2, module2.GlobalNamespace.GetTypeMembers("Class2").Single()) Assert.Same(base3, module3.GlobalNamespace.GetTypeMembers("Class3").Single()) End Sub Friend Shared Sub AssertBaseType(base As TypeSymbol, name As String) Assert.NotEqual(SymbolKind.ErrorType, base.Kind) Assert.Equal(name, base.ToTestDisplayString()) End Sub <Fact> Public Sub Test2() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( {TestResources.SymbolsTests.DifferByCase.Consumer, TestResources.SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase}) Dim module0 = TryCast(assemblies(0).Modules(0), PEModuleSymbol) Dim module1 = TryCast(assemblies(1).Modules(0), PEModuleSymbol) Dim bases As New HashSet(Of NamedTypeSymbol)() Dim TC1 = module0.GlobalNamespace.GetTypeMembers("TC1").Single() Dim base1 = TC1.BaseType bases.Add(base1) Assert.NotEqual(SymbolKind.ErrorType, base1.Kind) Assert.Equal("SomeName.Dummy", base1.ToTestDisplayString()) Dim TC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single() Dim base2 = TC2.BaseType bases.Add(base2) Assert.NotEqual(SymbolKind.ErrorType, base2.Kind) Assert.Equal("somEnamE", base2.ToTestDisplayString()) Dim TC3 = module0.GlobalNamespace.GetTypeMembers("TC3").Single() Dim base3 = TC3.BaseType bases.Add(base3) Assert.NotEqual(SymbolKind.ErrorType, base3.Kind) Assert.Equal("somEnamE1", base3.ToTestDisplayString()) Dim TC4 = module0.GlobalNamespace.GetTypeMembers("TC4").Single() Dim base4 = TC4.BaseType bases.Add(base4) Assert.NotEqual(SymbolKind.ErrorType, base4.Kind) Assert.Equal("SomeName1", base4.ToTestDisplayString()) Dim TC5 = module0.GlobalNamespace.GetTypeMembers("TC5").Single() Dim base5 = TC5.BaseType bases.Add(base5) Assert.NotEqual(SymbolKind.ErrorType, base5.Kind) Assert.Equal("somEnamE2.OtherName", base5.ToTestDisplayString()) Dim TC6 = module0.GlobalNamespace.GetTypeMembers("TC6").Single() Dim base6 = TC6.BaseType bases.Add(base6) Assert.NotEqual(SymbolKind.ErrorType, base6.Kind) Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString()) Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString()) Dim TC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single() Dim base7 = TC7.BaseType bases.Add(base7) Assert.NotEqual(SymbolKind.ErrorType, base7.Kind) Assert.Equal("NestingClass.somEnamE3", base7.ToTestDisplayString()) Dim TC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single() Dim base8 = TC8.BaseType bases.Add(base8) Assert.NotEqual(SymbolKind.ErrorType, base8.Kind) Assert.Equal("NestingClass.SomeName3", base8.ToTestDisplayString()) Assert.Equal(8, bases.Count) Assert.Equal(base1, module1.TypeHandleToTypeMap(DirectCast(base1, PENamedTypeSymbol).Handle)) Assert.Equal(base2, module1.TypeHandleToTypeMap(DirectCast(base2, PENamedTypeSymbol).Handle)) Assert.Equal(base3, module1.TypeHandleToTypeMap(DirectCast(base3, PENamedTypeSymbol).Handle)) Assert.Equal(base4, module1.TypeHandleToTypeMap(DirectCast(base4, PENamedTypeSymbol).Handle)) Assert.Equal(base5, module1.TypeHandleToTypeMap(DirectCast(base5, PENamedTypeSymbol).Handle)) Assert.Equal(base6, module1.TypeHandleToTypeMap(DirectCast(base6, PENamedTypeSymbol).Handle)) Assert.Equal(base7, module1.TypeHandleToTypeMap(DirectCast(base7, PENamedTypeSymbol).Handle)) Assert.Equal(base8, module1.TypeHandleToTypeMap(DirectCast(base8, PENamedTypeSymbol).Handle)) Assert.Equal(base1, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC1, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base2, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC2, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base3, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC3, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base4, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC4, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base5, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC5, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base6, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC6, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base7, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC7, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Assert.Equal(base8, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC8, PENamedTypeSymbol).Handle), TypeReferenceHandle))) Dim assembly1 = DirectCast(assemblies(1), MetadataOrSourceAssemblySymbol) Assert.Equal(base1, assembly1.CachedTypeByEmittedName(base1.ToTestDisplayString())) Assert.Equal(base2, assembly1.CachedTypeByEmittedName(base2.ToTestDisplayString())) Assert.Equal(base3, assembly1.CachedTypeByEmittedName(base3.ToTestDisplayString())) Assert.Equal(base4, assembly1.CachedTypeByEmittedName(base4.ToTestDisplayString())) Assert.Equal(base5, assembly1.CachedTypeByEmittedName(base5.ToTestDisplayString())) Assert.Equal(base6, assembly1.CachedTypeByEmittedName(base6.ToTestDisplayString())) Assert.Equal(base7.ContainingType, assembly1.CachedTypeByEmittedName(base7.ContainingType.ToTestDisplayString())) Assert.Equal(7, assembly1.EmittedNameToTypeMapCount) End Sub <Fact()> Public Sub Test3() Dim mscorlibRef = TestMetadata.Net40.mscorlib Dim c1 = VisualBasicCompilation.Create("Test", references:={mscorlibRef}) Assert.Equal("System.Object", DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()) Dim MTTestLib1Ref = TestReferences.SymbolsTests.V1.MTTestLib1.dll Dim c2 = VisualBasicCompilation.Create("Test2", references:={MTTestLib1Ref}) Assert.Equal("System.Object[missing]", DirectCast(c2.Assembly.Modules(0), SourceModuleSymbol).GetCorLibType(SpecialType.System_Object).ToTestDisplayString()) End Sub <Fact> Public Sub CrossModuleReferences1() Dim compilationDef1 = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Class Test1 Inherits M3 End Class Class Test2 Inherits M4 End Class ]]></file> </compilation> Dim crossRefModule1 = TestReferences.SymbolsTests.netModule.CrossRefModule1 Dim crossRefModule2 = TestReferences.SymbolsTests.netModule.CrossRefModule2 Dim crossRefLib = TestReferences.SymbolsTests.netModule.CrossRefLib Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(compilationDef1, {crossRefLib}, TestOptions.ReleaseDll) AssertNoErrors(compilation1) Dim test1 = compilation1.GetTypeByMetadataName("Test1") Dim test2 = compilation1.GetTypeByMetadataName("Test2") Assert.False(test1.BaseType.IsErrorType()) Assert.False(test1.BaseType.BaseType.IsErrorType()) Assert.False(test2.BaseType.IsErrorType()) Assert.False(test2.BaseType.BaseType.IsErrorType()) Assert.False(test2.BaseType.BaseType.BaseType.IsErrorType()) Dim compilationDef2 = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Public Class M3 Inherits M1 End Class Public Class M4 Inherits M2 End Class ]]></file> </compilation> Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {crossRefModule1, crossRefModule2}, TestOptions.ReleaseDll) AssertNoErrors(compilation2) Dim m3 = compilation2.GetTypeByMetadataName("M3") Dim m4 = compilation2.GetTypeByMetadataName("M4") Assert.False(m3.BaseType.IsErrorType()) Assert.False(m3.BaseType.BaseType.IsErrorType()) Assert.False(m4.BaseType.IsErrorType()) Assert.False(m4.BaseType.BaseType.IsErrorType()) Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {crossRefModule2}, TestOptions.ReleaseDll) m3 = compilation3.GetTypeByMetadataName("M3") m4 = compilation3.GetTypeByMetadataName("M4") Assert.True(m3.BaseType.IsErrorType()) Assert.False(m4.BaseType.IsErrorType()) Assert.True(m4.BaseType.BaseType.IsErrorType()) AssertTheseDiagnostics(compilation3, <expected> BC37221: Reference to 'CrossRefModule1.netmodule' netmodule missing. BC30002: Type 'M1' is not defined. Inherits M1 ~~ BC30653: Reference required to module 'CrossRefModule1.netmodule' containing the type 'M1'. Add one to your project. Inherits M2 ~~ </expected>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Def/Implementation/NavigateTo/VisualStudioNavigateToItemProviderFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; namespace Microsoft.VisualStudio.LanguageServices.Implementation.NavigateTo { [Export(typeof(INavigateToItemProviderFactory)), Shared] internal sealed class VisualStudioNavigateToItemProviderFactory : INavigateToItemProviderFactory { private readonly IAsynchronousOperationListener _asyncListener; private readonly VisualStudioWorkspace _workspace; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioNavigateToItemProviderFactory( VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigateTo); _workspace = workspace; _threadingContext = threadingContext; } public bool TryCreateNavigateToItemProvider(IServiceProvider serviceProvider, out INavigateToItemProvider? provider) { // Let LSP handle goto when running under the LSP editor. if (_workspace.Services.GetRequiredService<IWorkspaceContextService>().IsInLspEditorContext()) { provider = null; return false; } provider = new NavigateToItemProvider(_workspace, _asyncListener, _threadingContext); 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.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; namespace Microsoft.VisualStudio.LanguageServices.Implementation.NavigateTo { [Export(typeof(INavigateToItemProviderFactory)), Shared] internal sealed class VisualStudioNavigateToItemProviderFactory : INavigateToItemProviderFactory { private readonly IAsynchronousOperationListener _asyncListener; private readonly VisualStudioWorkspace _workspace; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioNavigateToItemProviderFactory( VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigateTo); _workspace = workspace; _threadingContext = threadingContext; } public bool TryCreateNavigateToItemProvider(IServiceProvider serviceProvider, out INavigateToItemProvider? provider) { // Let LSP handle goto when running under the LSP editor. if (_workspace.Services.GetRequiredService<IWorkspaceContextService>().IsInLspEditorContext()) { provider = null; return false; } provider = new NavigateToItemProvider(_workspace, _asyncListener, _threadingContext); return true; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.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.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitStringLiteral { [UseExportProvider] public class SplitStringLiteralCommandHandlerTests { /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestWorker( string inputMarkup, string expectedOutputMarkup, Action callback, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { using var workspace = TestWorkspace.CreateCSharp(inputMarkup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(SmartIndent, LanguageNames.CSharp, indentStyle) .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); if (useTabs && expectedOutputMarkup != null) { Assert.Contains("\t", expectedOutputMarkup); } var document = workspace.Documents.Single(); var view = document.GetTextView(); var originalSnapshot = view.TextBuffer.CurrentSnapshot; var originalSelections = document.SelectedSpans; var snapshotSpans = new List<SnapshotSpan>(); foreach (var selection in originalSelections) { snapshotSpans.Add(selection.ToSnapshotSpan(originalSnapshot)); } view.SetMultiSelection(snapshotSpans); var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>(); var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitStringLiteralCommandHandler>(nameof(SplitStringLiteralCommandHandler)); if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create())) { callback(); } if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); Assert.Equal(expectedSpans.First().Start, view.Caret.Position.BufferPosition.Position); if (verifyUndo) { // Ensure that after undo we go back to where we were to begin with. var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer()); history.Undo(count: originalSelections.Count); var currentSnapshot = document.GetTextBuffer().CurrentSnapshot; Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText()); Assert.Equal(originalSelections.First().Start, view.Caret.Position.BufferPosition.Position); } } } /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestHandled( string inputMarkup, string expectedOutputMarkup, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { TestWorker( inputMarkup, expectedOutputMarkup, callback: () => { Assert.True(false, "Should not reach here."); }, verifyUndo, indentStyle, useTabs); } private static void TestNotHandled(string inputMarkup) { var notHandled = false; TestWorker( inputMarkup, null, callback: () => { notHandled = true; }); Assert.True(notHandled); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeString() { TestNotHandled( @"class C { void M() { var v = [||]""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeInterpolatedString() { TestNotHandled( @"class C { void M() { var v = [||]$""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_1() { TestNotHandled( @"class C { void M() { var v = """"[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_2() { TestNotHandled( @"class C { void M() { var v = """" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_3() { TestNotHandled( @"class C { void M() { var v = """"[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_4() { TestNotHandled( @"class C { void M() { var v = """" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_1() { TestNotHandled( @"class C { void M() { var v = $""""[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_2() { TestNotHandled( @"class C { void M() { var v = $"""" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_3() { TestNotHandled( @"class C { void M() { var v = $""""[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_4() { TestNotHandled( @"class C { void M() { var v = $"""" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInVerbatimString() { TestNotHandled( @"class C { void M() { var v = @""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolatedVerbatimString() { TestNotHandled( @"class C { void M() { var v = $@""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_BlockIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_NoneIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_BlockIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_NoneIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSimpleString1() { TestHandled( @"class C { void M() { var v = ""now is [||]the time""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the time""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString1() { TestHandled( @"class C { void M() { var v = $""now is [||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is "" + $""[||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString2() { TestHandled( @"class C { void M() { var v = $""now is the [||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the "" + $""[||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString3() { TestHandled( @"class C { void M() { var v = $""now is the { 1 + 2 }[||] time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the { 1 + 2 }"" + $""[||] time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation1() { TestNotHandled( @"class C { void M() { var v = $""now is the {[||] 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation2() { TestNotHandled( @"class C { void M() { var v = $""now is the { 1 + 2 [||]} time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSelection() { TestNotHandled( @"class C { void M() { var v = ""now is [|the|] time""; } }"); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote1() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote2() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote3() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}"" + $""[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote4() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1[||]"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""[||]"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote5() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2[||]"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""[||]"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote6() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3[||]""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3"" + ""[||]""; } }", verifyUndo: false); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretSingleLine() { TestHandled( @"class C { void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretMultiLines() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretInterpolatedString() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var location = ""world""; var s = $""H[||]ello {location}!""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var location = ""world""; var s = $""H"" + $""[||]ello {location}!""; } }"); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled1() { TestHandled( @"class C { void M() { var s = ""Hello [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""[||]world""; } }", useTabs: true); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled2() { TestHandled( @"class C { void M() { var s = ""Hello "" + ""there [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""there "" + ""[||]world""; } }", useTabs: 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 Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitStringLiteral { [UseExportProvider] public class SplitStringLiteralCommandHandlerTests { /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestWorker( string inputMarkup, string expectedOutputMarkup, Action callback, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { using var workspace = TestWorkspace.CreateCSharp(inputMarkup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(SmartIndent, LanguageNames.CSharp, indentStyle) .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); if (useTabs && expectedOutputMarkup != null) { Assert.Contains("\t", expectedOutputMarkup); } var document = workspace.Documents.Single(); var view = document.GetTextView(); var originalSnapshot = view.TextBuffer.CurrentSnapshot; var originalSelections = document.SelectedSpans; var snapshotSpans = new List<SnapshotSpan>(); foreach (var selection in originalSelections) { snapshotSpans.Add(selection.ToSnapshotSpan(originalSnapshot)); } view.SetMultiSelection(snapshotSpans); var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>(); var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitStringLiteralCommandHandler>(nameof(SplitStringLiteralCommandHandler)); if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create())) { callback(); } if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); Assert.Equal(expectedSpans.First().Start, view.Caret.Position.BufferPosition.Position); if (verifyUndo) { // Ensure that after undo we go back to where we were to begin with. var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer()); history.Undo(count: originalSelections.Count); var currentSnapshot = document.GetTextBuffer().CurrentSnapshot; Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText()); Assert.Equal(originalSelections.First().Start, view.Caret.Position.BufferPosition.Position); } } } /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestHandled( string inputMarkup, string expectedOutputMarkup, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { TestWorker( inputMarkup, expectedOutputMarkup, callback: () => { Assert.True(false, "Should not reach here."); }, verifyUndo, indentStyle, useTabs); } private static void TestNotHandled(string inputMarkup) { var notHandled = false; TestWorker( inputMarkup, null, callback: () => { notHandled = true; }); Assert.True(notHandled); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeString() { TestNotHandled( @"class C { void M() { var v = [||]""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeInterpolatedString() { TestNotHandled( @"class C { void M() { var v = [||]$""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_1() { TestNotHandled( @"class C { void M() { var v = """"[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_2() { TestNotHandled( @"class C { void M() { var v = """" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_3() { TestNotHandled( @"class C { void M() { var v = """"[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_4() { TestNotHandled( @"class C { void M() { var v = """" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_1() { TestNotHandled( @"class C { void M() { var v = $""""[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_2() { TestNotHandled( @"class C { void M() { var v = $"""" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_3() { TestNotHandled( @"class C { void M() { var v = $""""[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_4() { TestNotHandled( @"class C { void M() { var v = $"""" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInVerbatimString() { TestNotHandled( @"class C { void M() { var v = @""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolatedVerbatimString() { TestNotHandled( @"class C { void M() { var v = $@""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_BlockIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_NoneIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_BlockIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_NoneIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSimpleString1() { TestHandled( @"class C { void M() { var v = ""now is [||]the time""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the time""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString1() { TestHandled( @"class C { void M() { var v = $""now is [||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is "" + $""[||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString2() { TestHandled( @"class C { void M() { var v = $""now is the [||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the "" + $""[||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString3() { TestHandled( @"class C { void M() { var v = $""now is the { 1 + 2 }[||] time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the { 1 + 2 }"" + $""[||] time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation1() { TestNotHandled( @"class C { void M() { var v = $""now is the {[||] 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation2() { TestNotHandled( @"class C { void M() { var v = $""now is the { 1 + 2 [||]} time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSelection() { TestNotHandled( @"class C { void M() { var v = ""now is [|the|] time""; } }"); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote1() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote2() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote3() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}"" + $""[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote4() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1[||]"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""[||]"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote5() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2[||]"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""[||]"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote6() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3[||]""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3"" + ""[||]""; } }", verifyUndo: false); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretSingleLine() { TestHandled( @"class C { void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretMultiLines() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretInterpolatedString() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var location = ""world""; var s = $""H[||]ello {location}!""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var location = ""world""; var s = $""H"" + $""[||]ello {location}!""; } }"); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled1() { TestHandled( @"class C { void M() { var s = ""Hello [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""[||]world""; } }", useTabs: true); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled2() { TestHandled( @"class C { void M() { var s = ""Hello "" + ""there [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""there "" + ""[||]world""; } }", useTabs: true); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/IRegexNodeVisitor.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.EmbeddedLanguages.RegularExpressions { internal interface IRegexNodeVisitor { void Visit(RegexCompilationUnit node); void Visit(RegexSequenceNode node); void Visit(RegexTextNode node); void Visit(RegexCharacterClassNode node); void Visit(RegexNegatedCharacterClassNode node); void Visit(RegexCharacterClassRangeNode node); void Visit(RegexCharacterClassSubtractionNode node); void Visit(RegexPosixPropertyNode node); void Visit(RegexWildcardNode node); void Visit(RegexZeroOrMoreQuantifierNode node); void Visit(RegexOneOrMoreQuantifierNode node); void Visit(RegexZeroOrOneQuantifierNode node); void Visit(RegexLazyQuantifierNode node); void Visit(RegexExactNumericQuantifierNode node); void Visit(RegexOpenNumericRangeQuantifierNode node); void Visit(RegexClosedNumericRangeQuantifierNode node); void Visit(RegexAnchorNode node); void Visit(RegexAlternationNode node); void Visit(RegexSimpleGroupingNode node); void Visit(RegexSimpleOptionsGroupingNode node); void Visit(RegexNestedOptionsGroupingNode node); void Visit(RegexNonCapturingGroupingNode node); void Visit(RegexPositiveLookaheadGroupingNode node); void Visit(RegexNegativeLookaheadGroupingNode node); void Visit(RegexPositiveLookbehindGroupingNode node); void Visit(RegexNegativeLookbehindGroupingNode node); void Visit(RegexAtomicGroupingNode node); void Visit(RegexCaptureGroupingNode node); void Visit(RegexBalancingGroupingNode node); void Visit(RegexConditionalCaptureGroupingNode node); void Visit(RegexConditionalExpressionGroupingNode node); void Visit(RegexSimpleEscapeNode node); void Visit(RegexAnchorEscapeNode node); void Visit(RegexCharacterClassEscapeNode node); void Visit(RegexControlEscapeNode node); void Visit(RegexHexEscapeNode node); void Visit(RegexUnicodeEscapeNode node); void Visit(RegexCaptureEscapeNode node); void Visit(RegexKCaptureEscapeNode node); void Visit(RegexOctalEscapeNode node); void Visit(RegexBackreferenceEscapeNode node); void Visit(RegexCategoryEscapeNode 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 namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { internal interface IRegexNodeVisitor { void Visit(RegexCompilationUnit node); void Visit(RegexSequenceNode node); void Visit(RegexTextNode node); void Visit(RegexCharacterClassNode node); void Visit(RegexNegatedCharacterClassNode node); void Visit(RegexCharacterClassRangeNode node); void Visit(RegexCharacterClassSubtractionNode node); void Visit(RegexPosixPropertyNode node); void Visit(RegexWildcardNode node); void Visit(RegexZeroOrMoreQuantifierNode node); void Visit(RegexOneOrMoreQuantifierNode node); void Visit(RegexZeroOrOneQuantifierNode node); void Visit(RegexLazyQuantifierNode node); void Visit(RegexExactNumericQuantifierNode node); void Visit(RegexOpenNumericRangeQuantifierNode node); void Visit(RegexClosedNumericRangeQuantifierNode node); void Visit(RegexAnchorNode node); void Visit(RegexAlternationNode node); void Visit(RegexSimpleGroupingNode node); void Visit(RegexSimpleOptionsGroupingNode node); void Visit(RegexNestedOptionsGroupingNode node); void Visit(RegexNonCapturingGroupingNode node); void Visit(RegexPositiveLookaheadGroupingNode node); void Visit(RegexNegativeLookaheadGroupingNode node); void Visit(RegexPositiveLookbehindGroupingNode node); void Visit(RegexNegativeLookbehindGroupingNode node); void Visit(RegexAtomicGroupingNode node); void Visit(RegexCaptureGroupingNode node); void Visit(RegexBalancingGroupingNode node); void Visit(RegexConditionalCaptureGroupingNode node); void Visit(RegexConditionalExpressionGroupingNode node); void Visit(RegexSimpleEscapeNode node); void Visit(RegexAnchorEscapeNode node); void Visit(RegexCharacterClassEscapeNode node); void Visit(RegexControlEscapeNode node); void Visit(RegexHexEscapeNode node); void Visit(RegexUnicodeEscapeNode node); void Visit(RegexCaptureEscapeNode node); void Visit(RegexKCaptureEscapeNode node); void Visit(RegexOctalEscapeNode node); void Visit(RegexBackreferenceEscapeNode node); void Visit(RegexCategoryEscapeNode node); } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingEngineTests : CSharpFormattingEngineTestBase { public FormattingEngineTests(ITestOutputHelper output) : base(output) { } private static Dictionary<OptionKey2, object> SmartIndentButDoNotFormatWhileTyping() { return new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart }, { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }, { new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }, }; } [WpfFact] [WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDocumentCommandHandler() { var code = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; var expected = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; AssertFormatWithView(expected, code); } [WpfFact] [WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDocumentPasteCommandHandler() { var code = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; var expected = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true); } [WpfFact] [WorkItem(547261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547261")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDocumentReadOnlyWorkspacePasteCommandHandler() { var code = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; var expected = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: false); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatUsingStatementOnReturn() { var code = @"class Program { static void Main(string[] args) { using (null) using (null)$$ } } "; var expected = @"class Program { static void Main(string[] args) { using (null) using (null)$$ } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatUsingStatementWhenTypingCloseParen() { var code = @"class Program { static void Main(string[] args) { using (null) using (null)$$ } } "; var expected = @"class Program { static void Main(string[] args) { using (null) using (null) } } "; AssertFormatAfterTypeChar(code, expected); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatNotUsingStatementOnReturn() { var code = @"class Program { static void Main(string[] args) { using (null) for (;;)$$ } } "; var expected = @"class Program { static void Main(string[] args) { using (null) for (;;)$$ } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false); } [WorkItem(977133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977133")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatRangeOrFormatTokenOnOpenBraceOnSameLine() { var code = @"class C { public void M() { if (true) {$$ } }"; var expected = @"class C { public void M() { if (true) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(14491, "https://github.com/dotnet/roslyn/pull/14491")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatRangeButFormatTokenOnOpenBraceOnNextLine() { var code = @"class C { public void M() { if (true) {$$ } }"; var expected = @"class C { public void M() { if (true) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(1007071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007071")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatPragmaWarningInbetweenDelegateDeclarationStatement() { var code = @"using System; class Program { static void Main(string[] args) { Func <bool> a = delegate () #pragma warning disable CA0001 { return true; };$$ } }"; var expected = @"using System; class Program { static void Main(string[] args) { Func<bool> a = delegate () #pragma warning disable CA0001 { return true; }; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatHashRegion() { var code = @"using System; class Program { static void Main(string[] args) { #region$$ } }"; var expected = @"using System; class Program { static void Main(string[] args) { #region } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatHashEndRegion() { var code = @"using System; class Program { static void Main(string[] args) { #region #endregion$$ } }"; var expected = @"using System; class Program { static void Main(string[] args) { #region #endregion } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatSpansIndividuallyWithoutCollapsing() { var code = @"class C { public void M() { [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] if(true){} [|if(true){}|] } }"; var expected = @"class C { public void M() { if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if(true){} if (true) { } } }"; using var workspace = TestWorkspace.CreateCSharp(code); var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = await document.GetSyntaxRootAsync(); var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } [WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatSpansWithCollapsing() { var code = @"class C { public void M() { [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] while(true){} [|if(true){}|] } }"; var expected = @"class C { public void M() { if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } while (true) { } if (true) { } } }"; using var workspace = TestWorkspace.CreateCSharp(code); var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.AllowDisjointSpanMerging, true))); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = await document.GetSyntaxRootAsync(); var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } [WorkItem(1044118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044118")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SemicolonInCommentOnLastLineDoesNotFormat() { var code = @"using System; class Program { static void Main(string[] args) { } } // ;$$"; var expected = @"using System; class Program { static void Main(string[] args) { } } // ;"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineRegularComment_1() { var code = @"class Program { // {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { // { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineRegularComment_2() { var code = @"class Program { // {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { // { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineRegularComment_1() { var code = @"class Program { static void Main(int a/* {$$ */, int b) { } }"; var expected = @"class Program { static void Main(int a/* { */, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineRegularComment_2() { var code = @"class Program { static void Main(int a/* {$$ */, int b) { } }"; var expected = @"class Program { static void Main(int a/* { */, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineRegularComment_3() { var code = @"class Program { static void Main(int a/* {$$ */, int b) { } }"; var expected = @"class Program { static void Main(int a/* { */, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineDocComment_1() { var code = @"class Program { /// {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { /// { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineDocComment_2() { var code = @"class Program { /// {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { /// { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineDocComment_1() { var code = @"class Program { /** {$$ **/ static void Main(int a, int b) { } }"; var expected = @"class Program { /** { **/ static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineDocComment_2() { var code = @"class Program { /** {$$ **/ static void Main(int a, int b) { } }"; var expected = @"class Program { /** { **/ static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineDocComment_3() { var code = @"class Program { /** {$$ **/ static void Main(int a, int b) { } }"; var expected = @"class Program { /** { **/ static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideInactiveCode() { var code = @"class Program { #if false {$$ #endif static void Main(string[] args) { } }"; var expected = @"class Program { #if false { #endif static void Main(string[] args) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideStringLiteral() { var code = @"class Program { static void Main(string[] args) { var asdas = ""{$$"" ; } }"; var expected = @"class Program { static void Main(string[] args) { var asdas = ""{"" ; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideCharLiteral() { var code = @"class Program { static void Main(string[] args) { var asdas = '{$$' ; } }"; var expected = @"class Program { static void Main(string[] args) { var asdas = '{' ; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideCommentsOfPreprocessorDirectives() { var code = @"class Program { #region #endregion // a/*{$$*/ static void Main(string[] args) { } }"; var expected = @"class Program { #region #endregion // a/*{*/ static void Main(string[] args) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInSwitchCase() { var code = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1 :$$ break; } } }"; var expected = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1: break; } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInDefaultSwitchCase() { var code = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1: break; default :$$ break; } } }"; var expected = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1: break; default: break; } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(9097, "https://github.com/dotnet/roslyn/issues/9097")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInPatternSwitchCase01() { var code = @"class Program { static void Main() { switch(f) { case int i :$$ break; } } }"; var expected = @"class Program { static void Main() { switch(f) { case int i: break; } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInLabeledStatement() { var code = @"class Program { static void Main(string[] args) { label1 :$$ int s = 0; } }"; var expected = @"class Program { static void Main(string[] args) { label1: int s = 0; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInTargetAttribute() { var code = @"using System; [method :$$ C] class C : Attribute { }"; var expected = @"using System; [method : C] class C : Attribute { }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInBaseList() { var code = @"class C :$$ Attribute { }"; var expected = @"class C : Attribute { }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInThisConstructor() { var code = @"class Goo { Goo(int s) :$$ this() { } Goo() { } }"; var expected = @"class Goo { Goo(int s) : this() { } Goo() { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInConditionalOperator() { var code = @"class Program { static void Main(string[] args) { var vari = goo() ? true :$$ false; } }"; var expected = @"class Program { static void Main(string[] args) { var vari = goo() ? true : false; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInArgument() { var code = @"class Program { static void Main(string[] args) { Main(args :$$ args); } }"; var expected = @"class Program { static void Main(string[] args) { Main(args : args); } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInTypeParameter() { var code = @"class Program<T> { class C1<U> where T :$$ U { } }"; var expected = @"class Program<T> { class C1<U> where T : U { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(2224, "https://github.com/dotnet/roslyn/issues/2224")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DontSmartFormatBracesOnSmartIndentNone() { var code = @"class Program<T> { class C1<U> {$$ }"; var expected = @"class Program<T> { class C1<U> { }"; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void StillAutoIndentCloseBraceWhenFormatOnCloseBraceIsOff() { var code = @"namespace N { class C { // improperly indented code int x = 10; }$$ } "; var expected = @"namespace N { class C { // improperly indented code int x = 10; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoIndentCloseBraceWhenFormatOnTypingIsOff() { var code = @"namespace N { class C { // improperly indented code int x = 10; }$$ } "; var expected = @"namespace N { class C { // improperly indented code int x = 10; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")] [WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void KeepTabsInCommentsWhenFormattingIsOff() { // There are tabs in this test case. Tools that touch the Roslyn repo should // not remove these as we are explicitly testing tab behavior. var code = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too }$$ }"; var expected = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too } }"; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")] [WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotKeepTabsInCommentsWhenFormattingIsOn() { // There are tabs in this test case. Tools that touch the Roslyn repo should // not remove these as we are explicitly testing tab behavior. var code = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too }$$ }"; var expected = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotFormatStatementIfSemicolonOptionIsOff() { var code = @"namespace N { class C { int x = 10 ;$$ } } "; var expected = @"namespace N { class C { int x = 10 ; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotFormatStatementIfTypingOptionIsOff() { var code = @"namespace N { class C { int x = 10 ;$$ } } "; var expected = @"namespace N { class C { int x = 10 ; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void OpenCurlyNotFormattedIfNotAtStartOfLine() { var code = @" class C { public int P {$$ } "; var expected = @" class C { public int P { } "; AssertFormatAfterTypeChar(code, expected); } [WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void OpenCurlyFormattedIfAtStartOfLine() { var code = @" class C { public int P {$$ } "; var expected = @" class C { public int P { } "; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly1() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true;$$ } }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly2() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true;$$ } }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly3() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get;$$ } }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly1() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; }$$ }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly2() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; }$$ }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly1() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; }$$ }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly2() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }$$"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatCompleteBlockOnSingleLineIfTypingSemicolon() { var code = @"public class Class1 { void M() { try { } catch { return;$$ x.ToString(); } }"; var expected = @"public class Class1 { void M() { try { } catch { return; x.ToString(); } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatCompleteBlockOnSingleLineIfTypingCloseCurlyOnLaterLine() { var code = @"public class Class1 { void M() { try { } catch { return; x.ToString(); }$$ } }"; var expected = @"public class Class1 { void M() { try { } catch { return; x.ToString(); } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatLockStatementWithEmbeddedStatementOnSemicolonDifferentLine() { var code = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d"");$$ } }"; var expected = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d""); } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatLockStatementWithEmbeddedStatementOnSemicolonSameLine() { var code = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d"");$$ } }"; var expected = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d""); } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(11642, "https://github.com/dotnet/roslyn/issues/11642")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatArbitraryNodeParenthesizedLambdaExpression() { // code equivalent to an expression synthesized like so: // ParenthesizedExpression(ParenthesizedLambdaExpression(ParameterList(), Block())) var code = @"(()=>{})"; var node = SyntaxFactory.ParseExpression(code); var expected = @"(() => { })"; AssertFormatOnArbitraryNode(node, expected); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff1() { var code = @"class Program { void M() { if (true) {$$ } }"; var expected = @"class Program { void M() { if (true) { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff2() { var code = @"class Program { void M() { if (true) {}$$ } }"; var expected = @"class Program { void M() { if (true) { } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff3() { // We only smart indent the { if it's on it's own line. var code = @"class Program { void M() { if (true){$$ } }"; var expected = @"class Program { void M() { if (true){ } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff4() { // We only smart indent the { if it's on it's own line. var code = @"class Program { void M() { if (true){}$$ } }"; var expected = @"class Program { void M() { if (true){ } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff5() { // Typing the { should not affect the formating of the preceding tokens. var code = @"class Program { void M() { if ( true ) {$$ } }"; var expected = @"class Program { void M() { if ( true ) { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff6() { // Typing the { should not affect the formating of the preceding tokens. var code = @"class Program { void M() { if ( true ){$$ } }"; var expected = @"class Program { void M() { if ( true ){ } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff7() { var code = @"class Program { void M() {$$ }"; var expected = @"class Program { void M() { }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff1() { var code = @"class Program { void M() { if (true) { }$$ } }"; var expected = @"class Program { void M() { if (true) { } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff2() { // Note that the { is not updated since we are not formatting. var code = @"class Program { void M() { if (true) { }$$ } }"; var expected = @"class Program { void M() { if (true) { } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff3() { var code = @"class Program { void M() { }$$ }"; var expected = @"class Program { void M() { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff4() { // Should not affect formatting of open brace var code = @"class Program { void M() { }$$ }"; var expected = @"class Program { void M() { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(31907, "https://github.com/dotnet/roslyn/issues/31907")] public async Task NullableReferenceTypes() { var code = @"[| class MyClass { void MyMethod() { var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType; } } |]"; var expected = @" class MyClass { void MyMethod() { var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WorkItem(30518, "https://github.com/dotnet/roslyn/issues/30518")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatGeneratedNodeInInitializer() { var code = @"new bool[] { true, true }"; var expected = @"new bool[] { true, true == false, true }"; var tree = SyntaxFactory.ParseSyntaxTree(code, options: TestOptions.Script); var root = tree.GetRoot(); var entry = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression), SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)); var newRoot = root.InsertNodesBefore(root.DescendantNodes().Last(), new[] { entry }); AssertFormatOnArbitraryNode(newRoot, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(27268, "https://github.com/dotnet/roslyn/issues/27268")] public async Task PositionalPattern() { var code = @"[| class MyClass { void MyMethod() { var point = new Point (3, 4); if (point is Point (3, 4) _ && point is Point{x: 3, y: 4} _) { } } } |]"; var expected = @" class MyClass { void MyMethod() { var point = new Point(3, 4); if (point is Point(3, 4) _ && point is Point { x: 3, y: 4 } _) { } } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task WithExpression() { var code = @"[| record C(int Property) { void M() { _ = this with { Property = 1 } ; } } |]"; var expected = @" record C(int Property) { void M() { _ = this with { Property = 1 }; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task WithExpression_MultiLine() { var code = @"[| record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 } ; } } |]"; var expected = @" record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 }; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task WithExpression_MultiLine_UserPositionedBraces() { var code = @"[| record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 } ; } } |]"; var expected = @" record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 }; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_KeepMultipleLinesBetweenGroups() { var code = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; var expected = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_KeepMultipleLinesBetweenGroups_FileScopedNamespace() { var code = @"$$ namespace N; using System.A; using System.B; using MS.A; using MS.B; "; var expected = @"$$ namespace N; using System.A; using System.B; using MS.A; using MS.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_DoNotGroupIfNotSorted() { var code = @"$$ using System.B; using System.A; using MS.B; using MS.A; "; var expected = @"$$ using System.B; using System.A; using MS.B; using MS.A; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_GroupIfSorted() { var code = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; var expected = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst() { var code = @"$$ using MS.A; using MS.B; using System.A; using System.B; "; var expected = @"$$ using MS.A; using MS.B; using System.A; using System.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [Fact, WorkItem(49492, "https://github.com/dotnet/roslyn/issues/49492")] public void PreserveAnnotationsOnMultiLineTrivia() { var text = @" namespace TestApp { class Test { /* __marker__ */ } } "; var position = text.IndexOf("/* __marker__ */"); var syntaxTree = CSharpSyntaxTree.ParseText(text); var root = syntaxTree.GetRoot(); var annotation = new SyntaxAnnotation("marker"); var markerTrivia = root.FindTrivia(position, findInsideTrivia: true); var annotatedMarkerTrivia = markerTrivia.WithAdditionalAnnotations(annotation); root = root.ReplaceTrivia(markerTrivia, annotatedMarkerTrivia); var formattedRoot = Formatter.Format(root, new AdhocWorkspace()); var annotatedTrivia = formattedRoot.GetAnnotatedTrivia("marker"); Assert.Single(annotatedTrivia); } private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary<OptionKey2, object> changedOptionSet = null) { using var workspace = TestWorkspace.CreateCSharp(code); 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 subjectDocument = workspace.Documents.Single(); var commandHandler = workspace.GetService<FormatCommandHandler>(); var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1); commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create()); var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot; Assert.Equal(expected, newSnapshot.GetText()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingEngineTests : CSharpFormattingEngineTestBase { public FormattingEngineTests(ITestOutputHelper output) : base(output) { } private static Dictionary<OptionKey2, object> SmartIndentButDoNotFormatWhileTyping() { return new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart }, { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }, { new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }, }; } [WpfFact] [WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDocumentCommandHandler() { var code = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; var expected = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; AssertFormatWithView(expected, code); } [WpfFact] [WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDocumentPasteCommandHandler() { var code = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; var expected = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true); } [WpfFact] [WorkItem(547261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547261")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDocumentReadOnlyWorkspacePasteCommandHandler() { var code = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; var expected = @"class Program { static void Main(string[] args) { int x;$$ int y; } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: false); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatUsingStatementOnReturn() { var code = @"class Program { static void Main(string[] args) { using (null) using (null)$$ } } "; var expected = @"class Program { static void Main(string[] args) { using (null) using (null)$$ } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatUsingStatementWhenTypingCloseParen() { var code = @"class Program { static void Main(string[] args) { using (null) using (null)$$ } } "; var expected = @"class Program { static void Main(string[] args) { using (null) using (null) } } "; AssertFormatAfterTypeChar(code, expected); } [WpfFact] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatNotUsingStatementOnReturn() { var code = @"class Program { static void Main(string[] args) { using (null) for (;;)$$ } } "; var expected = @"class Program { static void Main(string[] args) { using (null) for (;;)$$ } } "; AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false); } [WorkItem(977133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977133")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatRangeOrFormatTokenOnOpenBraceOnSameLine() { var code = @"class C { public void M() { if (true) {$$ } }"; var expected = @"class C { public void M() { if (true) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(14491, "https://github.com/dotnet/roslyn/pull/14491")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatRangeButFormatTokenOnOpenBraceOnNextLine() { var code = @"class C { public void M() { if (true) {$$ } }"; var expected = @"class C { public void M() { if (true) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(1007071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007071")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatPragmaWarningInbetweenDelegateDeclarationStatement() { var code = @"using System; class Program { static void Main(string[] args) { Func <bool> a = delegate () #pragma warning disable CA0001 { return true; };$$ } }"; var expected = @"using System; class Program { static void Main(string[] args) { Func<bool> a = delegate () #pragma warning disable CA0001 { return true; }; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatHashRegion() { var code = @"using System; class Program { static void Main(string[] args) { #region$$ } }"; var expected = @"using System; class Program { static void Main(string[] args) { #region } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatHashEndRegion() { var code = @"using System; class Program { static void Main(string[] args) { #region #endregion$$ } }"; var expected = @"using System; class Program { static void Main(string[] args) { #region #endregion } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatSpansIndividuallyWithoutCollapsing() { var code = @"class C { public void M() { [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] if(true){} [|if(true){}|] } }"; var expected = @"class C { public void M() { if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if(true){} if (true) { } } }"; using var workspace = TestWorkspace.CreateCSharp(code); var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = await document.GetSyntaxRootAsync(); var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } [WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task FormatSpansWithCollapsing() { var code = @"class C { public void M() { [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] while(true){} [|if(true){}|] } }"; var expected = @"class C { public void M() { if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } while (true) { } if (true) { } } }"; using var workspace = TestWorkspace.CreateCSharp(code); var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.AllowDisjointSpanMerging, true))); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = await document.GetSyntaxRootAsync(); var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } [WorkItem(1044118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044118")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SemicolonInCommentOnLastLineDoesNotFormat() { var code = @"using System; class Program { static void Main(string[] args) { } } // ;$$"; var expected = @"using System; class Program { static void Main(string[] args) { } } // ;"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineRegularComment_1() { var code = @"class Program { // {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { // { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineRegularComment_2() { var code = @"class Program { // {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { // { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineRegularComment_1() { var code = @"class Program { static void Main(int a/* {$$ */, int b) { } }"; var expected = @"class Program { static void Main(int a/* { */, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineRegularComment_2() { var code = @"class Program { static void Main(int a/* {$$ */, int b) { } }"; var expected = @"class Program { static void Main(int a/* { */, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineRegularComment_3() { var code = @"class Program { static void Main(int a/* {$$ */, int b) { } }"; var expected = @"class Program { static void Main(int a/* { */, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineDocComment_1() { var code = @"class Program { /// {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { /// { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideSingleLineDocComment_2() { var code = @"class Program { /// {$$ static void Main(int a, int b) { } }"; var expected = @"class Program { /// { static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineDocComment_1() { var code = @"class Program { /** {$$ **/ static void Main(int a, int b) { } }"; var expected = @"class Program { /** { **/ static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineDocComment_2() { var code = @"class Program { /** {$$ **/ static void Main(int a, int b) { } }"; var expected = @"class Program { /** { **/ static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideMultiLineDocComment_3() { var code = @"class Program { /** {$$ **/ static void Main(int a, int b) { } }"; var expected = @"class Program { /** { **/ static void Main(int a, int b) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideInactiveCode() { var code = @"class Program { #if false {$$ #endif static void Main(string[] args) { } }"; var expected = @"class Program { #if false { #endif static void Main(string[] args) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideStringLiteral() { var code = @"class Program { static void Main(string[] args) { var asdas = ""{$$"" ; } }"; var expected = @"class Program { static void Main(string[] args) { var asdas = ""{"" ; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideCharLiteral() { var code = @"class Program { static void Main(string[] args) { var asdas = '{$$' ; } }"; var expected = @"class Program { static void Main(string[] args) { var asdas = '{' ; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")] [WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void NoFormattingInsideCommentsOfPreprocessorDirectives() { var code = @"class Program { #region #endregion // a/*{$$*/ static void Main(string[] args) { } }"; var expected = @"class Program { #region #endregion // a/*{*/ static void Main(string[] args) { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInSwitchCase() { var code = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1 :$$ break; } } }"; var expected = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1: break; } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInDefaultSwitchCase() { var code = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1: break; default :$$ break; } } }"; var expected = @"class Program { static void Main(string[] args) { int f = 0; switch(f) { case 1: break; default: break; } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(9097, "https://github.com/dotnet/roslyn/issues/9097")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInPatternSwitchCase01() { var code = @"class Program { static void Main() { switch(f) { case int i :$$ break; } } }"; var expected = @"class Program { static void Main() { switch(f) { case int i: break; } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ColonInLabeledStatement() { var code = @"class Program { static void Main(string[] args) { label1 :$$ int s = 0; } }"; var expected = @"class Program { static void Main(string[] args) { label1: int s = 0; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInTargetAttribute() { var code = @"using System; [method :$$ C] class C : Attribute { }"; var expected = @"using System; [method : C] class C : Attribute { }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInBaseList() { var code = @"class C :$$ Attribute { }"; var expected = @"class C : Attribute { }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInThisConstructor() { var code = @"class Goo { Goo(int s) :$$ this() { } Goo() { } }"; var expected = @"class Goo { Goo(int s) : this() { } Goo() { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInConditionalOperator() { var code = @"class Program { static void Main(string[] args) { var vari = goo() ? true :$$ false; } }"; var expected = @"class Program { static void Main(string[] args) { var vari = goo() ? true : false; } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInArgument() { var code = @"class Program { static void Main(string[] args) { Main(args :$$ args); } }"; var expected = @"class Program { static void Main(string[] args) { Main(args : args); } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")] [WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatColonInTypeParameter() { var code = @"class Program<T> { class C1<U> where T :$$ U { } }"; var expected = @"class Program<T> { class C1<U> where T : U { } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(2224, "https://github.com/dotnet/roslyn/issues/2224")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DontSmartFormatBracesOnSmartIndentNone() { var code = @"class Program<T> { class C1<U> {$$ }"; var expected = @"class Program<T> { class C1<U> { }"; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void StillAutoIndentCloseBraceWhenFormatOnCloseBraceIsOff() { var code = @"namespace N { class C { // improperly indented code int x = 10; }$$ } "; var expected = @"namespace N { class C { // improperly indented code int x = 10; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoIndentCloseBraceWhenFormatOnTypingIsOff() { var code = @"namespace N { class C { // improperly indented code int x = 10; }$$ } "; var expected = @"namespace N { class C { // improperly indented code int x = 10; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")] [WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void KeepTabsInCommentsWhenFormattingIsOff() { // There are tabs in this test case. Tools that touch the Roslyn repo should // not remove these as we are explicitly testing tab behavior. var code = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too }$$ }"; var expected = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too } }"; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")] [WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotKeepTabsInCommentsWhenFormattingIsOn() { // There are tabs in this test case. Tools that touch the Roslyn repo should // not remove these as we are explicitly testing tab behavior. var code = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too }$$ }"; var expected = @"class Program { static void Main() { return; /* Comment preceded by tabs */ // This one too } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotFormatStatementIfSemicolonOptionIsOff() { var code = @"namespace N { class C { int x = 10 ;$$ } } "; var expected = @"namespace N { class C { int x = 10 ; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void DoNotFormatStatementIfTypingOptionIsOff() { var code = @"namespace N { class C { int x = 10 ;$$ } } "; var expected = @"namespace N { class C { int x = 10 ; } } "; var optionSet = new Dictionary<OptionKey2, object> { { new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); } [WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void OpenCurlyNotFormattedIfNotAtStartOfLine() { var code = @" class C { public int P {$$ } "; var expected = @" class C { public int P { } "; AssertFormatAfterTypeChar(code, expected); } [WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void OpenCurlyFormattedIfAtStartOfLine() { var code = @" class C { public int P {$$ } "; var expected = @" class C { public int P { } "; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly1() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true;$$ } }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly2() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true;$$ } }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly3() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get;$$ } }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly1() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; }$$ }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly2() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; }$$ }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly1() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; }$$ }"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly2() { var code = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }$$"; var expected = @"namespace ConsoleApplication1 { class Program { static bool Property { get { return true; } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoNotFormatCompleteBlockOnSingleLineIfTypingSemicolon() { var code = @"public class Class1 { void M() { try { } catch { return;$$ x.ToString(); } }"; var expected = @"public class Class1 { void M() { try { } catch { return; x.ToString(); } }"; AssertFormatAfterTypeChar(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatCompleteBlockOnSingleLineIfTypingCloseCurlyOnLaterLine() { var code = @"public class Class1 { void M() { try { } catch { return; x.ToString(); }$$ } }"; var expected = @"public class Class1 { void M() { try { } catch { return; x.ToString(); } } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatLockStatementWithEmbeddedStatementOnSemicolonDifferentLine() { var code = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d"");$$ } }"; var expected = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d""); } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatLockStatementWithEmbeddedStatementOnSemicolonSameLine() { var code = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d"");$$ } }"; var expected = @"class C { private object _l = new object(); public void M() { lock (_l) Console.WriteLine(""d""); } }"; AssertFormatAfterTypeChar(code, expected); } [WorkItem(11642, "https://github.com/dotnet/roslyn/issues/11642")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatArbitraryNodeParenthesizedLambdaExpression() { // code equivalent to an expression synthesized like so: // ParenthesizedExpression(ParenthesizedLambdaExpression(ParameterList(), Block())) var code = @"(()=>{})"; var node = SyntaxFactory.ParseExpression(code); var expected = @"(() => { })"; AssertFormatOnArbitraryNode(node, expected); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff1() { var code = @"class Program { void M() { if (true) {$$ } }"; var expected = @"class Program { void M() { if (true) { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff2() { var code = @"class Program { void M() { if (true) {}$$ } }"; var expected = @"class Program { void M() { if (true) { } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff3() { // We only smart indent the { if it's on it's own line. var code = @"class Program { void M() { if (true){$$ } }"; var expected = @"class Program { void M() { if (true){ } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff4() { // We only smart indent the { if it's on it's own line. var code = @"class Program { void M() { if (true){}$$ } }"; var expected = @"class Program { void M() { if (true){ } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff5() { // Typing the { should not affect the formating of the preceding tokens. var code = @"class Program { void M() { if ( true ) {$$ } }"; var expected = @"class Program { void M() { if ( true ) { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff6() { // Typing the { should not affect the formating of the preceding tokens. var code = @"class Program { void M() { if ( true ){$$ } }"; var expected = @"class Program { void M() { if ( true ){ } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff7() { var code = @"class Program { void M() {$$ }"; var expected = @"class Program { void M() { }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff1() { var code = @"class Program { void M() { if (true) { }$$ } }"; var expected = @"class Program { void M() { if (true) { } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff2() { // Note that the { is not updated since we are not formatting. var code = @"class Program { void M() { if (true) { }$$ } }"; var expected = @"class Program { void M() { if (true) { } } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff3() { var code = @"class Program { void M() { }$$ }"; var expected = @"class Program { void M() { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff4() { // Should not affect formatting of open brace var code = @"class Program { void M() { }$$ }"; var expected = @"class Program { void M() { } }"; AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping()); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(31907, "https://github.com/dotnet/roslyn/issues/31907")] public async Task NullableReferenceTypes() { var code = @"[| class MyClass { void MyMethod() { var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType; } } |]"; var expected = @" class MyClass { void MyMethod() { var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WorkItem(30518, "https://github.com/dotnet/roslyn/issues/30518")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatGeneratedNodeInInitializer() { var code = @"new bool[] { true, true }"; var expected = @"new bool[] { true, true == false, true }"; var tree = SyntaxFactory.ParseSyntaxTree(code, options: TestOptions.Script); var root = tree.GetRoot(); var entry = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression), SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)); var newRoot = root.InsertNodesBefore(root.DescendantNodes().Last(), new[] { entry }); AssertFormatOnArbitraryNode(newRoot, expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(27268, "https://github.com/dotnet/roslyn/issues/27268")] public async Task PositionalPattern() { var code = @"[| class MyClass { void MyMethod() { var point = new Point (3, 4); if (point is Point (3, 4) _ && point is Point{x: 3, y: 4} _) { } } } |]"; var expected = @" class MyClass { void MyMethod() { var point = new Point(3, 4); if (point is Point(3, 4) _ && point is Point { x: 3, y: 4 } _) { } } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task WithExpression() { var code = @"[| record C(int Property) { void M() { _ = this with { Property = 1 } ; } } |]"; var expected = @" record C(int Property) { void M() { _ = this with { Property = 1 }; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task WithExpression_MultiLine() { var code = @"[| record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 } ; } } |]"; var expected = @" record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 }; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WpfFact] [Trait(Traits.Feature, Traits.Features.Formatting)] public async Task WithExpression_MultiLine_UserPositionedBraces() { var code = @"[| record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 } ; } } |]"; var expected = @" record C(int Property, int Property2) { void M() { _ = this with { Property = 1, Property2 = 2 }; } } "; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_KeepMultipleLinesBetweenGroups() { var code = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; var expected = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_KeepMultipleLinesBetweenGroups_FileScopedNamespace() { var code = @"$$ namespace N; using System.A; using System.B; using MS.A; using MS.B; "; var expected = @"$$ namespace N; using System.A; using System.B; using MS.A; using MS.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_DoNotGroupIfNotSorted() { var code = @"$$ using System.B; using System.A; using MS.B; using MS.A; "; var expected = @"$$ using System.B; using System.A; using MS.B; using MS.A; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_GroupIfSorted() { var code = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; var expected = @"$$ using System.A; using System.B; using MS.A; using MS.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst() { var code = @"$$ using MS.A; using MS.B; using System.A; using System.B; "; var expected = @"$$ using MS.A; using MS.B; using System.A; using System.B; "; AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } [Fact, WorkItem(49492, "https://github.com/dotnet/roslyn/issues/49492")] public void PreserveAnnotationsOnMultiLineTrivia() { var text = @" namespace TestApp { class Test { /* __marker__ */ } } "; var position = text.IndexOf("/* __marker__ */"); var syntaxTree = CSharpSyntaxTree.ParseText(text); var root = syntaxTree.GetRoot(); var annotation = new SyntaxAnnotation("marker"); var markerTrivia = root.FindTrivia(position, findInsideTrivia: true); var annotatedMarkerTrivia = markerTrivia.WithAdditionalAnnotations(annotation); root = root.ReplaceTrivia(markerTrivia, annotatedMarkerTrivia); var formattedRoot = Formatter.Format(root, new AdhocWorkspace()); var annotatedTrivia = formattedRoot.GetAnnotatedTrivia("marker"); Assert.Single(annotatedTrivia); } private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary<OptionKey2, object> changedOptionSet = null) { using var workspace = TestWorkspace.CreateCSharp(code); 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 subjectDocument = workspace.Documents.Single(); var commandHandler = workspace.GetService<FormatCommandHandler>(); var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1); commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create()); var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot; Assert.Equal(expected, newSnapshot.GetText()); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/InvertLogical/AbstractInvertLogicalCodeRefactoringProvider.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.InvertLogical { /// <summary> /// Code refactoring to help convert code like `!a || !b` to `!(a &amp;&amp; b)` /// </summary> internal abstract class AbstractInvertLogicalCodeRefactoringProvider< TSyntaxKind, TExpressionSyntax, TBinaryExpressionSyntax> : CodeRefactoringProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TBinaryExpressionSyntax : TExpressionSyntax { /// <summary> /// See comment in <see cref="InvertLogicalAsync"/> to understand the need for this annotation. /// </summary> private static readonly SyntaxAnnotation s_annotation = new(); protected abstract string GetOperatorText(TSyntaxKind binaryExprKind); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var expression = (SyntaxNode?)await context.TryGetRelevantNodeAsync<TBinaryExpressionSyntax>().ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); if (expression == null || (!syntaxFacts.IsLogicalAndExpression(expression) && !syntaxFacts.IsLogicalOrExpression(expression))) { return; } if (span.IsEmpty) { // Walk up to the topmost binary of the same type. When converting || to && (or vice versa) // we want to grab the entire set. i.e. `!a && !b && !c` should become `!(a || b || c)` not // `!(a || b) && !c` while (expression.Parent?.RawKind == expression.RawKind) { expression = expression.Parent; } } else { // When selection is non-empty -> allow only top-level full selections. // Currently the refactoring can't handle invert of arbitrary nodes but only whole subtrees // and allowing it just for selection of those nodes that - by chance - form a full subtree // would produce only confusion. if (CodeRefactoringHelpers.IsNodeUnderselected(expression, span) || syntaxFacts.IsLogicalAndExpression(expression.Parent) || syntaxFacts.IsLogicalOrExpression(expression.Parent)) { return; } } context.RegisterRefactoring( new MyCodeAction( GetTitle(syntaxKinds, expression.RawKind), c => InvertLogicalAsync(document, expression, c)), expression.Span); } private static async Task<Document> InvertLogicalAsync( Document document1, SyntaxNode binaryExpression, CancellationToken cancellationToken) { // We invert in two steps. To invert `a op b` we are effectively generating two negations: // `!(!(a op b)`. The inner `!` will distribute on the inside to make `!a op' !b` leaving // us with `!(!a op' !b)`. // Because we need to do two negations, we actually perform the inner one, marking the // result with an annotation, then we do the outer one (making sure we don't descend in // and undo the work we just did). Because our negation helper needs semantics, we generate // a new document at each step so that we'll be able to properly analyze things as we go // along. var document2 = await InvertInnerExpressionAsync(document1, binaryExpression, cancellationToken).ConfigureAwait(false); var document3 = await InvertOuterExpressionAsync(document2, cancellationToken).ConfigureAwait(false); return document3; } private static async Task<Document> InvertInnerExpressionAsync( Document document, SyntaxNode binaryExpression, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var newBinary = generator.Negate(generator.SyntaxGeneratorInternal, binaryExpression, semanticModel, cancellationToken); return document.WithSyntaxRoot(root.ReplaceNode( binaryExpression, newBinary.WithAdditionalAnnotations(s_annotation))); } private static async Task<Document> InvertOuterExpressionAsync( Document document, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var expression = root.GetAnnotatedNodes(s_annotation).Single()!; // Walk up parens and !'s. That way we don't end up with something like !!. // It also ensures that this refactoring reverses itself when invoked twice. while (syntaxFacts.IsParenthesizedExpression(expression.Parent) || syntaxFacts.IsLogicalNotExpression(expression.Parent)) { expression = expression.Parent; } var generator = SyntaxGenerator.GetGenerator(document); // Negate the containing binary expr. Pass the 'negateBinary:false' flag so we don't // just negate the work we're actually doing right now. return document.WithSyntaxRoot(root.ReplaceNode( expression, generator.Negate(generator.SyntaxGeneratorInternal, expression, semanticModel, negateBinary: false, cancellationToken))); } private string GetTitle(ISyntaxKindsService syntaxKinds, int binaryExprKind) => string.Format(FeaturesResources.Replace_0_with_1, GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(binaryExprKind)), GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(InvertedKind(syntaxKinds, binaryExprKind)))); private static int InvertedKind(ISyntaxKindsService syntaxKinds, int binaryExprKind) => binaryExprKind == syntaxKinds.LogicalAndExpression ? syntaxKinds.LogicalOrExpression : syntaxKinds.LogicalAndExpression; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.InvertLogical { /// <summary> /// Code refactoring to help convert code like `!a || !b` to `!(a &amp;&amp; b)` /// </summary> internal abstract class AbstractInvertLogicalCodeRefactoringProvider< TSyntaxKind, TExpressionSyntax, TBinaryExpressionSyntax> : CodeRefactoringProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TBinaryExpressionSyntax : TExpressionSyntax { /// <summary> /// See comment in <see cref="InvertLogicalAsync"/> to understand the need for this annotation. /// </summary> private static readonly SyntaxAnnotation s_annotation = new(); protected abstract string GetOperatorText(TSyntaxKind binaryExprKind); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var expression = (SyntaxNode?)await context.TryGetRelevantNodeAsync<TBinaryExpressionSyntax>().ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); if (expression == null || (!syntaxFacts.IsLogicalAndExpression(expression) && !syntaxFacts.IsLogicalOrExpression(expression))) { return; } if (span.IsEmpty) { // Walk up to the topmost binary of the same type. When converting || to && (or vice versa) // we want to grab the entire set. i.e. `!a && !b && !c` should become `!(a || b || c)` not // `!(a || b) && !c` while (expression.Parent?.RawKind == expression.RawKind) { expression = expression.Parent; } } else { // When selection is non-empty -> allow only top-level full selections. // Currently the refactoring can't handle invert of arbitrary nodes but only whole subtrees // and allowing it just for selection of those nodes that - by chance - form a full subtree // would produce only confusion. if (CodeRefactoringHelpers.IsNodeUnderselected(expression, span) || syntaxFacts.IsLogicalAndExpression(expression.Parent) || syntaxFacts.IsLogicalOrExpression(expression.Parent)) { return; } } context.RegisterRefactoring( new MyCodeAction( GetTitle(syntaxKinds, expression.RawKind), c => InvertLogicalAsync(document, expression, c)), expression.Span); } private static async Task<Document> InvertLogicalAsync( Document document1, SyntaxNode binaryExpression, CancellationToken cancellationToken) { // We invert in two steps. To invert `a op b` we are effectively generating two negations: // `!(!(a op b)`. The inner `!` will distribute on the inside to make `!a op' !b` leaving // us with `!(!a op' !b)`. // Because we need to do two negations, we actually perform the inner one, marking the // result with an annotation, then we do the outer one (making sure we don't descend in // and undo the work we just did). Because our negation helper needs semantics, we generate // a new document at each step so that we'll be able to properly analyze things as we go // along. var document2 = await InvertInnerExpressionAsync(document1, binaryExpression, cancellationToken).ConfigureAwait(false); var document3 = await InvertOuterExpressionAsync(document2, cancellationToken).ConfigureAwait(false); return document3; } private static async Task<Document> InvertInnerExpressionAsync( Document document, SyntaxNode binaryExpression, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var newBinary = generator.Negate(generator.SyntaxGeneratorInternal, binaryExpression, semanticModel, cancellationToken); return document.WithSyntaxRoot(root.ReplaceNode( binaryExpression, newBinary.WithAdditionalAnnotations(s_annotation))); } private static async Task<Document> InvertOuterExpressionAsync( Document document, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var expression = root.GetAnnotatedNodes(s_annotation).Single()!; // Walk up parens and !'s. That way we don't end up with something like !!. // It also ensures that this refactoring reverses itself when invoked twice. while (syntaxFacts.IsParenthesizedExpression(expression.Parent) || syntaxFacts.IsLogicalNotExpression(expression.Parent)) { expression = expression.Parent; } var generator = SyntaxGenerator.GetGenerator(document); // Negate the containing binary expr. Pass the 'negateBinary:false' flag so we don't // just negate the work we're actually doing right now. return document.WithSyntaxRoot(root.ReplaceNode( expression, generator.Negate(generator.SyntaxGeneratorInternal, expression, semanticModel, negateBinary: false, cancellationToken))); } private string GetTitle(ISyntaxKindsService syntaxKinds, int binaryExprKind) => string.Format(FeaturesResources.Replace_0_with_1, GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(binaryExprKind)), GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(InvertedKind(syntaxKinds, binaryExprKind)))); private static int InvertedKind(ISyntaxKindsService syntaxKinds, int binaryExprKind) => binaryExprKind == syntaxKinds.LogicalAndExpression ? syntaxKinds.LogicalOrExpression : syntaxKinds.LogicalAndExpression; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/IntegrationTest/TestUtilities/Harness/MessageFilterSafeHandle.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.Win32.SafeHandles; using IMessageFilter = Microsoft.VisualStudio.OLE.Interop.IMessageFilter; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Harness { internal sealed class MessageFilterSafeHandle : SafeHandleMinusOneIsInvalid { private readonly IntPtr _oldFilter; private MessageFilterSafeHandle(IntPtr handle) : base(true) { SetHandle(handle); try { if (CoRegisterMessageFilter(handle, out _oldFilter) != VSConstants.S_OK) { throw new InvalidOperationException("Failed to register a new message filter"); } } catch { SetHandleAsInvalid(); throw; } } [DllImport("ole32", SetLastError = true)] private static extern int CoRegisterMessageFilter(IntPtr messageFilter, out IntPtr oldMessageFilter); public static MessageFilterSafeHandle Register<T>(T messageFilter) where T : IMessageFilter { var handle = Marshal.GetComInterfaceForObject<T, IMessageFilter>(messageFilter); return new MessageFilterSafeHandle(handle); } protected override bool ReleaseHandle() { if (CoRegisterMessageFilter(_oldFilter, out _) == VSConstants.S_OK) { Marshal.Release(handle); } 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.Win32.SafeHandles; using IMessageFilter = Microsoft.VisualStudio.OLE.Interop.IMessageFilter; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Harness { internal sealed class MessageFilterSafeHandle : SafeHandleMinusOneIsInvalid { private readonly IntPtr _oldFilter; private MessageFilterSafeHandle(IntPtr handle) : base(true) { SetHandle(handle); try { if (CoRegisterMessageFilter(handle, out _oldFilter) != VSConstants.S_OK) { throw new InvalidOperationException("Failed to register a new message filter"); } } catch { SetHandleAsInvalid(); throw; } } [DllImport("ole32", SetLastError = true)] private static extern int CoRegisterMessageFilter(IntPtr messageFilter, out IntPtr oldMessageFilter); public static MessageFilterSafeHandle Register<T>(T messageFilter) where T : IMessageFilter { var handle = Marshal.GetComInterfaceForObject<T, IMessageFilter>(messageFilter); return new MessageFilterSafeHandle(handle); } protected override bool ReleaseHandle() { if (CoRegisterMessageFilter(_oldFilter, out _) == VSConstants.S_OK) { Marshal.Release(handle); } return true; } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Tools/ExternalAccess/FSharp/Completion/FSharpCommonCompletionItem.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.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCommonCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, CompletionItemRules rules, FSharpGlyph? glyph = null, ImmutableArray<SymbolDisplayPart> description = default, string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string inlineDescription = null) { var roslynGlyph = glyph.HasValue ? FSharpGlyphHelpers.ConvertTo(glyph.Value) : (Glyph?)null; return CommonCompletionItem.Create( displayText, displayTextSuffix, rules, roslynGlyph, description, sortText, filterText, showsWarningIcon, properties, tags, inlineDescription); } } }
// Licensed to the .NET Foundation under one or more 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.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCommonCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, CompletionItemRules rules, FSharpGlyph? glyph = null, ImmutableArray<SymbolDisplayPart> description = default, string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string inlineDescription = null) { var roslynGlyph = glyph.HasValue ? FSharpGlyphHelpers.ConvertTo(glyph.Value) : (Glyph?)null; return CommonCompletionItem.Create( displayText, displayTextSuffix, rules, roslynGlyph, description, sortText, filterText, showsWarningIcon, properties, tags, inlineDescription); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/VisualBasic/Portable/CodeFixes/Suppression/VisualBasicSuppressionCodeFixProvider.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 System.Diagnostics.CodeAnalysis Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression <ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSuppressionCodeFixProvider Inherits AbstractSuppressionCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CreatePragmaRestoreDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.EnableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Protected Overrides Function CreatePragmaDisableDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.DisableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Private Shared Function GetErrorCodes(diagnostic As Diagnostic, ByRef includeTitle As Boolean) As SeparatedSyntaxList(Of IdentifierNameSyntax) Dim text = GetOrMapDiagnosticId(diagnostic, includeTitle) If SyntaxFacts.GetKeywordKind(text) <> SyntaxKind.None Then text = "[" & text & "]" End If Return New SeparatedSyntaxList(Of IdentifierNameSyntax)().Add(SyntaxFactory.IdentifierName(text)) End Function Private Shared Function CreatePragmaDirectiveTrivia(enableOrDisablePragmaDirective As StructuredTriviaSyntax, includeTitle As Boolean, diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList enableOrDisablePragmaDirective = CType(formatNode(enableOrDisablePragmaDirective), StructuredTriviaSyntax) Dim pragmaDirectiveTrivia = SyntaxFactory.Trivia(enableOrDisablePragmaDirective) Dim endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Dim triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia) Dim title = If(includeTitle, diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture), Nothing) If Not String.IsNullOrWhiteSpace(title) Then Dim titleComment = SyntaxFactory.CommentTrivia(String.Format(" ' {0}", title)).WithAdditionalAnnotations(Formatter.Annotation) triviaList = triviaList.Add(titleComment) End If If needsLeadingEndOfLine Then triviaList = triviaList.Insert(0, endOfLineTrivia) End If If needsTrailingEndOfLine Then triviaList = triviaList.Add(endOfLineTrivia) End If Return triviaList End Function Protected Overrides Function GetAdjustedTokenForPragmaDisable(token As SyntaxToken, root As SyntaxNode, lines As TextLineCollection, indexOfLine As Integer) As SyntaxToken Dim containingStatement = token.GetAncestor(Of StatementSyntax) If containingStatement IsNot Nothing AndAlso containingStatement.GetFirstToken() <> token Then indexOfLine = lines.IndexOf(containingStatement.GetFirstToken().SpanStart) Dim line = lines(indexOfLine) token = root.FindToken(line.Start) End If Return token End Function Protected Overrides Function GetAdjustedTokenForPragmaRestore(token As SyntaxToken, root As SyntaxNode, lines As TextLineCollection, indexOfLine As Integer) As SyntaxToken Dim containingStatement = token.GetAncestor(Of StatementSyntax) While True If TokenHasTrailingLineContinuationChar(token) Then indexOfLine = indexOfLine + 1 ElseIf containingStatement IsNot Nothing AndAlso containingStatement.GetLastToken() <> token Then indexOfLine = lines.IndexOf(containingStatement.GetLastToken().SpanStart) containingStatement = Nothing Else Exit While End If Dim line = lines(indexOfLine) token = root.FindToken(line.End) End While Return token End Function Private Shared Function TokenHasTrailingLineContinuationChar(token As SyntaxToken) As Boolean Return token.TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) End Function Protected Overrides ReadOnly Property DefaultFileExtension() As String Get Return ".vb" End Get End Property Protected Overrides ReadOnly Property SingleLineCommentStart() As String Get Return "'" End Get End Property Protected Overrides Function IsAttributeListWithAssemblyAttributes(node As SyntaxNode) As Boolean Dim attributesStatement = TryCast(node, AttributesStatementSyntax) Return attributesStatement IsNot Nothing AndAlso attributesStatement.AttributeLists.All(Function(attributeList) attributeList.Attributes.All(Function(a) a.Target.AttributeModifier.Kind() = SyntaxKind.AssemblyKeyword)) End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsEndOfFileToken(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.EndOfFileToken End Function Protected Overrides Function AddGlobalSuppressMessageAttribute( newRoot As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic, workspace As Workspace, compilation As Compilation, addImportsService As IAddImportsService, cancellationToken As CancellationToken) As SyntaxNode Dim compilationRoot = DirectCast(newRoot, CompilationUnitSyntax) Dim isFirst = Not compilationRoot.Attributes.Any() Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=True) Dim attributeStatement = SyntaxFactory.AttributesStatement(New SyntaxList(Of AttributeListSyntax)().Add(attributeList)) If Not isFirst Then Dim trailingTrivia = compilationRoot.Attributes.Last().GetTrailingTrivia() Dim lastTrivia = If(trailingTrivia.IsEmpty, Nothing, trailingTrivia(trailingTrivia.Count - 1)) If Not IsEndOfLine(lastTrivia) Then ' Add leading end of line trivia to attribute statement attributeStatement = attributeStatement.WithLeadingTrivia(attributeStatement.GetLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed)) End If End If attributeStatement = CType(Formatter.Format(attributeStatement, workspace, cancellationToken:=cancellationToken), AttributesStatementSyntax) Dim leadingTrivia = If(isFirst AndAlso Not compilationRoot.HasLeadingTrivia, SyntaxFactory.TriviaList(SyntaxFactory.CommentTrivia(GlobalSuppressionsFileHeaderComment)), Nothing) leadingTrivia = leadingTrivia.AddRange(compilationRoot.GetLeadingTrivia()) compilationRoot = compilationRoot.WithoutLeadingTrivia() Return compilationRoot.AddAttributes(attributeStatement).WithLeadingTrivia(leadingTrivia) End Function Protected Overrides Function AddLocalSuppressMessageAttribute( targetNode As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic) As SyntaxNode Dim memberNode = DirectCast(targetNode, StatementSyntax) Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=False) Dim leadingTrivia = memberNode.GetLeadingTrivia() memberNode = memberNode.WithoutLeadingTrivia() Return memberNode.AddAttributeLists(attributeList).WithLeadingTrivia(leadingTrivia) End Function Private Shared Function CreateAttributeList( targetSymbol As ISymbol, attributeName As NameSyntax, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As AttributeListSyntax Dim attributeTarget = If(isAssemblyAttribute, SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)), Nothing) Dim attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute) Dim attribute As AttributeSyntax = SyntaxFactory.Attribute(attributeTarget, attributeName, attributeArguments) Return SyntaxFactory.AttributeList().AddAttributes(attribute) End Function Private Shared Function CreateAttributeArguments(targetSymbol As ISymbol, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As ArgumentListSyntax ' SuppressMessage("Rule Category", "Rule Id", Justification := "Justification", Scope := "Scope", Target := "Target") Dim category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)) Dim categoryArgument = SyntaxFactory.SimpleArgument(category) Dim title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) Dim ruleIdText = If(String.IsNullOrWhiteSpace(title), diagnostic.Id, String.Format("{0}:{1}", diagnostic.Id, title)) Dim ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)) Dim ruleIdArgument = SyntaxFactory.SimpleArgument(ruleId) Dim justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)) Dim justificationArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Justification")), expression:=justificationExpr) Dim attributeArgumentList = SyntaxFactory.ArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument) Dim scopeString = GetScopeString(targetSymbol.Kind) If isAssemblyAttribute Then If scopeString IsNot Nothing Then Dim scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)) Dim scopeArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Scope")), expression:=scopeExpr) Dim targetString = GetTargetString(targetSymbol) Dim targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)) Dim targetArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Target")), expression:=targetExpr) attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument) End If End If Return attributeArgumentList End Function Protected Overrides Function IsSingleAttributeInAttributeList(attribute As SyntaxNode) As Boolean Dim attributeSyntax = TryCast(attribute, AttributeSyntax) If attributeSyntax IsNot Nothing Then Dim attributeList = TryCast(attributeSyntax.Parent, AttributeListSyntax) Return attributeList IsNot Nothing AndAlso attributeList.Attributes.Count = 1 End If Return False End Function Protected Overrides Function IsAnyPragmaDirectiveForId(trivia As SyntaxTrivia, id As String, ByRef enableDirective As Boolean, ByRef hasMultipleIds As Boolean) As Boolean Dim errorCodes As SeparatedSyntaxList(Of IdentifierNameSyntax) Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = False Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = True Case Else enableDirective = False hasMultipleIds = False Return False End Select hasMultipleIds = errorCodes.Count > 1 Return errorCodes.Any(Function(node) node.ToString = id) End Function Protected Overrides Function TogglePragmaDirective(trivia As SyntaxTrivia) As SyntaxTrivia Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) Dim disabledKeyword = pragmaWarning.DisableKeyword Dim enabledKeyword = SyntaxFactory.Token(disabledKeyword.LeadingTrivia, SyntaxKind.EnableKeyword, disabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.EnableWarningDirectiveTrivia(pragmaWarning.HashToken, enabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) Dim enabledKeyword = pragmaWarning.EnableKeyword Dim disabledKeyword = SyntaxFactory.Token(enabledKeyword.LeadingTrivia, SyntaxKind.DisableKeyword, enabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.DisableWarningDirectiveTrivia(pragmaWarning.HashToken, disabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case Else throw ExceptionUtilities.UnexpectedValue(trivia.Kind()) End Select 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.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression <ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSuppressionCodeFixProvider Inherits AbstractSuppressionCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CreatePragmaRestoreDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.EnableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Protected Overrides Function CreatePragmaDisableDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.DisableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Private Shared Function GetErrorCodes(diagnostic As Diagnostic, ByRef includeTitle As Boolean) As SeparatedSyntaxList(Of IdentifierNameSyntax) Dim text = GetOrMapDiagnosticId(diagnostic, includeTitle) If SyntaxFacts.GetKeywordKind(text) <> SyntaxKind.None Then text = "[" & text & "]" End If Return New SeparatedSyntaxList(Of IdentifierNameSyntax)().Add(SyntaxFactory.IdentifierName(text)) End Function Private Shared Function CreatePragmaDirectiveTrivia(enableOrDisablePragmaDirective As StructuredTriviaSyntax, includeTitle As Boolean, diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList enableOrDisablePragmaDirective = CType(formatNode(enableOrDisablePragmaDirective), StructuredTriviaSyntax) Dim pragmaDirectiveTrivia = SyntaxFactory.Trivia(enableOrDisablePragmaDirective) Dim endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Dim triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia) Dim title = If(includeTitle, diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture), Nothing) If Not String.IsNullOrWhiteSpace(title) Then Dim titleComment = SyntaxFactory.CommentTrivia(String.Format(" ' {0}", title)).WithAdditionalAnnotations(Formatter.Annotation) triviaList = triviaList.Add(titleComment) End If If needsLeadingEndOfLine Then triviaList = triviaList.Insert(0, endOfLineTrivia) End If If needsTrailingEndOfLine Then triviaList = triviaList.Add(endOfLineTrivia) End If Return triviaList End Function Protected Overrides Function GetAdjustedTokenForPragmaDisable(token As SyntaxToken, root As SyntaxNode, lines As TextLineCollection, indexOfLine As Integer) As SyntaxToken Dim containingStatement = token.GetAncestor(Of StatementSyntax) If containingStatement IsNot Nothing AndAlso containingStatement.GetFirstToken() <> token Then indexOfLine = lines.IndexOf(containingStatement.GetFirstToken().SpanStart) Dim line = lines(indexOfLine) token = root.FindToken(line.Start) End If Return token End Function Protected Overrides Function GetAdjustedTokenForPragmaRestore(token As SyntaxToken, root As SyntaxNode, lines As TextLineCollection, indexOfLine As Integer) As SyntaxToken Dim containingStatement = token.GetAncestor(Of StatementSyntax) While True If TokenHasTrailingLineContinuationChar(token) Then indexOfLine = indexOfLine + 1 ElseIf containingStatement IsNot Nothing AndAlso containingStatement.GetLastToken() <> token Then indexOfLine = lines.IndexOf(containingStatement.GetLastToken().SpanStart) containingStatement = Nothing Else Exit While End If Dim line = lines(indexOfLine) token = root.FindToken(line.End) End While Return token End Function Private Shared Function TokenHasTrailingLineContinuationChar(token As SyntaxToken) As Boolean Return token.TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) End Function Protected Overrides ReadOnly Property DefaultFileExtension() As String Get Return ".vb" End Get End Property Protected Overrides ReadOnly Property SingleLineCommentStart() As String Get Return "'" End Get End Property Protected Overrides Function IsAttributeListWithAssemblyAttributes(node As SyntaxNode) As Boolean Dim attributesStatement = TryCast(node, AttributesStatementSyntax) Return attributesStatement IsNot Nothing AndAlso attributesStatement.AttributeLists.All(Function(attributeList) attributeList.Attributes.All(Function(a) a.Target.AttributeModifier.Kind() = SyntaxKind.AssemblyKeyword)) End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsEndOfFileToken(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.EndOfFileToken End Function Protected Overrides Function AddGlobalSuppressMessageAttribute( newRoot As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic, workspace As Workspace, compilation As Compilation, addImportsService As IAddImportsService, cancellationToken As CancellationToken) As SyntaxNode Dim compilationRoot = DirectCast(newRoot, CompilationUnitSyntax) Dim isFirst = Not compilationRoot.Attributes.Any() Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=True) Dim attributeStatement = SyntaxFactory.AttributesStatement(New SyntaxList(Of AttributeListSyntax)().Add(attributeList)) If Not isFirst Then Dim trailingTrivia = compilationRoot.Attributes.Last().GetTrailingTrivia() Dim lastTrivia = If(trailingTrivia.IsEmpty, Nothing, trailingTrivia(trailingTrivia.Count - 1)) If Not IsEndOfLine(lastTrivia) Then ' Add leading end of line trivia to attribute statement attributeStatement = attributeStatement.WithLeadingTrivia(attributeStatement.GetLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed)) End If End If attributeStatement = CType(Formatter.Format(attributeStatement, workspace, cancellationToken:=cancellationToken), AttributesStatementSyntax) Dim leadingTrivia = If(isFirst AndAlso Not compilationRoot.HasLeadingTrivia, SyntaxFactory.TriviaList(SyntaxFactory.CommentTrivia(GlobalSuppressionsFileHeaderComment)), Nothing) leadingTrivia = leadingTrivia.AddRange(compilationRoot.GetLeadingTrivia()) compilationRoot = compilationRoot.WithoutLeadingTrivia() Return compilationRoot.AddAttributes(attributeStatement).WithLeadingTrivia(leadingTrivia) End Function Protected Overrides Function AddLocalSuppressMessageAttribute( targetNode As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic) As SyntaxNode Dim memberNode = DirectCast(targetNode, StatementSyntax) Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=False) Dim leadingTrivia = memberNode.GetLeadingTrivia() memberNode = memberNode.WithoutLeadingTrivia() Return memberNode.AddAttributeLists(attributeList).WithLeadingTrivia(leadingTrivia) End Function Private Shared Function CreateAttributeList( targetSymbol As ISymbol, attributeName As NameSyntax, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As AttributeListSyntax Dim attributeTarget = If(isAssemblyAttribute, SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)), Nothing) Dim attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute) Dim attribute As AttributeSyntax = SyntaxFactory.Attribute(attributeTarget, attributeName, attributeArguments) Return SyntaxFactory.AttributeList().AddAttributes(attribute) End Function Private Shared Function CreateAttributeArguments(targetSymbol As ISymbol, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As ArgumentListSyntax ' SuppressMessage("Rule Category", "Rule Id", Justification := "Justification", Scope := "Scope", Target := "Target") Dim category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)) Dim categoryArgument = SyntaxFactory.SimpleArgument(category) Dim title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) Dim ruleIdText = If(String.IsNullOrWhiteSpace(title), diagnostic.Id, String.Format("{0}:{1}", diagnostic.Id, title)) Dim ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)) Dim ruleIdArgument = SyntaxFactory.SimpleArgument(ruleId) Dim justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)) Dim justificationArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Justification")), expression:=justificationExpr) Dim attributeArgumentList = SyntaxFactory.ArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument) Dim scopeString = GetScopeString(targetSymbol.Kind) If isAssemblyAttribute Then If scopeString IsNot Nothing Then Dim scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)) Dim scopeArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Scope")), expression:=scopeExpr) Dim targetString = GetTargetString(targetSymbol) Dim targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)) Dim targetArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Target")), expression:=targetExpr) attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument) End If End If Return attributeArgumentList End Function Protected Overrides Function IsSingleAttributeInAttributeList(attribute As SyntaxNode) As Boolean Dim attributeSyntax = TryCast(attribute, AttributeSyntax) If attributeSyntax IsNot Nothing Then Dim attributeList = TryCast(attributeSyntax.Parent, AttributeListSyntax) Return attributeList IsNot Nothing AndAlso attributeList.Attributes.Count = 1 End If Return False End Function Protected Overrides Function IsAnyPragmaDirectiveForId(trivia As SyntaxTrivia, id As String, ByRef enableDirective As Boolean, ByRef hasMultipleIds As Boolean) As Boolean Dim errorCodes As SeparatedSyntaxList(Of IdentifierNameSyntax) Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = False Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = True Case Else enableDirective = False hasMultipleIds = False Return False End Select hasMultipleIds = errorCodes.Count > 1 Return errorCodes.Any(Function(node) node.ToString = id) End Function Protected Overrides Function TogglePragmaDirective(trivia As SyntaxTrivia) As SyntaxTrivia Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) Dim disabledKeyword = pragmaWarning.DisableKeyword Dim enabledKeyword = SyntaxFactory.Token(disabledKeyword.LeadingTrivia, SyntaxKind.EnableKeyword, disabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.EnableWarningDirectiveTrivia(pragmaWarning.HashToken, enabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) Dim enabledKeyword = pragmaWarning.EnableKeyword Dim disabledKeyword = SyntaxFactory.Token(enabledKeyword.LeadingTrivia, SyntaxKind.DisableKeyword, enabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.DisableWarningDirectiveTrivia(pragmaWarning.HashToken, disabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case Else throw ExceptionUtilities.UnexpectedValue(trivia.Kind()) End Select End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/SyntaxListExtensions.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.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module SyntaxListExtensions <Extension()> Public Function RemoveRange(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, count As Integer) As SyntaxList(Of T) Dim result = New List(Of T)(syntaxList) result.RemoveRange(index, count) Return SyntaxFactory.List(result) End Function <Extension()> Public Function ToSyntaxList(Of T As SyntaxNode)(sequence As IEnumerable(Of T)) As SyntaxList(Of T) Return SyntaxFactory.List(sequence) End Function <Extension()> Public Function Insert(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, item As T) As SyntaxList(Of T) Return syntaxList.Take(index).Concat(item).Concat(syntaxList.Skip(index)).ToSyntaxList 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.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module SyntaxListExtensions <Extension()> Public Function RemoveRange(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, count As Integer) As SyntaxList(Of T) Dim result = New List(Of T)(syntaxList) result.RemoveRange(index, count) Return SyntaxFactory.List(result) End Function <Extension()> Public Function ToSyntaxList(Of T As SyntaxNode)(sequence As IEnumerable(Of T)) As SyntaxList(Of T) Return SyntaxFactory.List(sequence) End Function <Extension()> Public Function Insert(Of T As SyntaxNode)(syntaxList As SyntaxList(Of T), index As Integer, item As T) As SyntaxList(Of T) Return syntaxList.Take(index).Concat(item).Concat(syntaxList.Skip(index)).ToSyntaxList End Function End Module End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/Core/EditorConfigSettings/Updater/SettingsUpdateHelper.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.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater { internal static partial class SettingsUpdateHelper { private const string DiagnosticOptionPrefix = "dotnet_diagnostic."; private const string SeveritySuffix = ".severity"; public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value)).ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (string option, string value, Language language) TryGetOptionValueAndLanguage(AnalyzerSetting diagnostic, DiagnosticSeverity severity) { var optionName = $"{DiagnosticOptionPrefix}{diagnostic.Id}{SeveritySuffix}"; var optionValue = severity.ToEditorConfigString(); var language = diagnostic.Language; return (optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, OptionSet optionSet, IReadOnlyList<(IOption2 option, object value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var updatedText = originalText; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value, optionSet)) .Where(x => x.success) .Select(x => (x.option, x.value, x.language)) .ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (bool success, string option, string value, Language language) TryGetOptionValueAndLanguage(IOption2 option, object value, OptionSet optionSet) { if (option.StorageLocations.FirstOrDefault(x => x is IEditorConfigStorageLocation2) is not IEditorConfigStorageLocation2 storageLocation) { return (false, null!, null!, default); } var optionName = storageLocation.KeyName; var optionValue = storageLocation.GetEditorConfigStringValue(value, optionSet); if (value is ICodeStyleOption codeStyleOption && !optionValue.Contains(':')) { var severity = codeStyleOption.Notification switch { { Severity: ReportDiagnostic.Hidden } => "silent", { Severity: ReportDiagnostic.Info } => "suggestion", { Severity: ReportDiagnostic.Warn } => "warning", { Severity: ReportDiagnostic.Error } => "error", _ => string.Empty }; optionValue = $"{optionValue}:{severity}"; } var language = option.IsPerLanguage ? Language.CSharp | Language.VisualBasic : Language.CSharp; return (true, optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(string option, string value, Language language)> settingsToUpdate) { if (originalText is null) throw new ArgumentNullException(nameof(originalText)); if (filePath is null) throw new ArgumentNullException(nameof(filePath)); if (settingsToUpdate is null) throw new ArgumentNullException(nameof(settingsToUpdate)); var updatedText = originalText; TextLine? lastValidHeaderSpanEnd; TextLine? lastValidSpecificHeaderSpanEnd; foreach (var (option, value, language) in settingsToUpdate) { SourceText? newText; (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = UpdateIfExistsInFile(updatedText, filePath, option, value, language); if (newText != null) { updatedText = newText; continue; } (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = AddMissingRule(updatedText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd, option, value, language); if (newText != null) { updatedText = newText; } } return updatedText.Equals(originalText) ? null : updatedText; } /// <summary> /// <para>Regular expression for .editorconfig header.</para> /// <para>For example: "[*.cs] # Optional comment"</para> /// <para> "[*.{vb,cs}]"</para> /// <para> "[*] ; Optional comment"</para> /// <para> "[ConsoleApp/Program.cs]"</para> /// </summary> private static readonly Regex s_headerPattern = new(@"\[(\*|[^ #;\[\]]+\.({[^ #;{}\.\[\]]+}|[^ #;{}\.\[\]]+))\]\s*([#;].*)?"); /// <summary> /// <para>Regular expression for .editorconfig code style option entry.</para> /// <para>For example:</para> /// <para> 1. "dotnet_style_object_initializer = true # Optional comment"</para> /// <para> 2. "dotnet_style_object_initializer = true:suggestion ; Optional comment"</para> /// <para> 3. "dotnet_diagnostic.CA2000.severity = suggestion # Optional comment"</para> /// <para> 4. "dotnet_analyzer_diagnostic.category-Security.severity = suggestion # Optional comment"</para> /// <para> 5. "dotnet_analyzer_diagnostic.severity = suggestion # Optional comment"</para> /// <para>Regex groups:</para> /// <para> 1. Option key</para> /// <para> 2. Option value</para> /// <para> 3. Optional severity suffix in option value, i.e. ':severity' suffix</para> /// <para>4. Optional comment suffix</para> /// </summary> private static readonly Regex s_optionEntryPattern = new($@"(.*)=([\w, ]*)(:[\w]+)?([ ]*[;#].*)?"); private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) UpdateIfExistsInFile(SourceText editorConfigText, string filePath, string optionName, string optionValue, Language language) { var editorConfigDirectory = PathUtilities.GetDirectoryName(filePath); Assumes.NotNull(editorConfigDirectory); var relativePath = PathUtilities.GetRelativePath(editorConfigDirectory.ToLowerInvariant(), filePath); TextLine? mostRecentHeader = null; TextLine? lastValidHeader = null; TextLine? lastValidHeaderSpanEnd = null; TextLine? lastValidSpecificHeader = null; TextLine? lastValidSpecificHeaderSpanEnd = null; var textChange = new TextChange(); foreach (var curLine in editorConfigText.Lines) { var curLineText = curLine.ToString(); if (s_optionEntryPattern.IsMatch(curLineText)) { var groups = s_optionEntryPattern.Match(curLineText).Groups; var (untrimmedKey, key, value, severity, comment) = GetGroups(groups); // Verify the most recent header is a valid header if (IsValidHeader(mostRecentHeader, lastValidHeader) && string.Equals(key, optionName, StringComparison.OrdinalIgnoreCase)) { // We found the rule in the file -- replace it with updated option value. textChange = new TextChange(curLine.Span, $"{untrimmedKey}={optionValue}{comment}"); } } else if (s_headerPattern.IsMatch(curLineText.Trim())) { mostRecentHeader = curLine; if (ShouldSetAsLastValidHeader(curLineText, out var mostRecentHeaderText)) { lastValidHeader = mostRecentHeader; } else { var (fileName, splicedFileExtensions) = ParseHeaderParts(mostRecentHeaderText); if ((relativePath.IsEmpty() || new Regex(fileName).IsMatch(relativePath)) && HeaderMatchesLanguageRequirements(language, splicedFileExtensions)) { lastValidHeader = mostRecentHeader; } } } // We want to keep track of how far this (valid) section spans. if (IsValidHeader(mostRecentHeader, lastValidHeader) && IsNotEmptyOrComment(curLineText)) { lastValidHeaderSpanEnd = curLine; if (lastValidSpecificHeader != null && mostRecentHeader.Equals(lastValidSpecificHeader)) { lastValidSpecificHeaderSpanEnd = curLine; } } } // We return only the last text change in case of duplicate entries for the same rule. if (textChange != default) { return (editorConfigText.WithChanges(textChange), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // Rule not found. return (null, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); static (string untrimmedKey, string key, string value, string severitySuffixInValue, string commentValue) GetGroups(GroupCollection groups) { var untrimmedKey = groups[1].Value.ToString(); var key = untrimmedKey.Trim(); var value = groups[2].Value.ToString(); var severitySuffixInValue = groups[3].Value.ToString(); var commentValue = groups[4].Value.ToString(); return (untrimmedKey, key, value, severitySuffixInValue, commentValue); } static bool IsValidHeader(TextLine? mostRecentHeader, TextLine? lastValidHeader) { return mostRecentHeader is not null && lastValidHeader is not null && mostRecentHeader.Equals(lastValidHeader); } static bool ShouldSetAsLastValidHeader(string curLineText, out string mostRecentHeaderText) { var groups = s_headerPattern.Match(curLineText.Trim()).Groups; mostRecentHeaderText = groups[1].Value.ToString().ToLowerInvariant(); return mostRecentHeaderText.Equals("*", StringComparison.Ordinal); } static (string fileName, string[] splicedFileExtensions) ParseHeaderParts(string mostRecentHeaderText) { // We splice on the last occurrence of '.' to account for filenames containing periods. var nameExtensionSplitIndex = mostRecentHeaderText.LastIndexOf('.'); var fileName = mostRecentHeaderText.Substring(0, nameExtensionSplitIndex); var splicedFileExtensions = mostRecentHeaderText[(nameExtensionSplitIndex + 1)..].Split(',', ' ', '{', '}'); // Replacing characters in the header with the regex equivalent. fileName = fileName.Replace(".", @"\."); fileName = fileName.Replace("*", ".*"); fileName = fileName.Replace("/", @"\/"); return (fileName, splicedFileExtensions); } static bool IsNotEmptyOrComment(string currentLineText) { return !string.IsNullOrWhiteSpace(currentLineText) && !currentLineText.Trim().StartsWith("#", StringComparison.OrdinalIgnoreCase); } static bool HeaderMatchesLanguageRequirements(Language language, string[] splicedFileExtensions) { return IsCSharpOnly(language, splicedFileExtensions) || IsVisualBasicOnly(language, splicedFileExtensions) || IsBothVisualBasicAndCSharp(language, splicedFileExtensions); } static bool IsCSharpOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.CSharp) && !language.HasFlag(Language.VisualBasic) && splicedFileExtensions.Contains("cs") && splicedFileExtensions.Length == 1; } static bool IsVisualBasicOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && !language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Length == 1; } static bool IsBothVisualBasicAndCSharp(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Contains("cs"); } } private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) AddMissingRule(SourceText editorConfigText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd, string optionName, string optionValue, Language language) { var newEntry = $"{optionName}={optionValue}"; if (lastValidSpecificHeaderSpanEnd.HasValue) { if (lastValidSpecificHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidSpecificHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } else if (lastValidHeaderSpanEnd.HasValue) { if (lastValidHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // We need to generate a new header such as '[*.cs]' or '[*.vb]': // - For compiler diagnostic entries and code style entries which have per-language option = false, generate only [*.cs] or [*.vb]. // - For the remainder, generate [*.{cs,vb}] // Insert a newline if not already present var lines = editorConfigText.Lines; var lastLine = lines.Count > 0 ? lines[^1] : default; var prefix = string.Empty; if (lastLine.ToString().Trim().Length != 0) { prefix = "\r\n"; } // Insert newline if file is not empty if (lines.Count > 1 && lastLine.ToString().Trim().Length == 0) { prefix += "\r\n"; } if (language.HasFlag(Language.CSharp) && language.HasFlag(Language.VisualBasic)) { prefix += "[*.{cs,vb}]\r\n"; } else if (language.HasFlag(Language.CSharp)) { prefix += "[*.cs]\r\n"; } else if (language.HasFlag(Language.VisualBasic)) { prefix += "[*.vb]\r\n"; } var result = editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(editorConfigText.Length, 0), prefix + newEntry)); return (result, lastValidHeaderSpanEnd, result.Lines[^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. using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater { internal static partial class SettingsUpdateHelper { private const string DiagnosticOptionPrefix = "dotnet_diagnostic."; private const string SeveritySuffix = ".severity"; public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value)).ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (string option, string value, Language language) TryGetOptionValueAndLanguage(AnalyzerSetting diagnostic, DiagnosticSeverity severity) { var optionName = $"{DiagnosticOptionPrefix}{diagnostic.Id}{SeveritySuffix}"; var optionValue = severity.ToEditorConfigString(); var language = diagnostic.Language; return (optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, OptionSet optionSet, IReadOnlyList<(IOption2 option, object value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var updatedText = originalText; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value, optionSet)) .Where(x => x.success) .Select(x => (x.option, x.value, x.language)) .ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (bool success, string option, string value, Language language) TryGetOptionValueAndLanguage(IOption2 option, object value, OptionSet optionSet) { if (option.StorageLocations.FirstOrDefault(x => x is IEditorConfigStorageLocation2) is not IEditorConfigStorageLocation2 storageLocation) { return (false, null!, null!, default); } var optionName = storageLocation.KeyName; var optionValue = storageLocation.GetEditorConfigStringValue(value, optionSet); if (value is ICodeStyleOption codeStyleOption && !optionValue.Contains(':')) { var severity = codeStyleOption.Notification switch { { Severity: ReportDiagnostic.Hidden } => "silent", { Severity: ReportDiagnostic.Info } => "suggestion", { Severity: ReportDiagnostic.Warn } => "warning", { Severity: ReportDiagnostic.Error } => "error", _ => string.Empty }; optionValue = $"{optionValue}:{severity}"; } var language = option.IsPerLanguage ? Language.CSharp | Language.VisualBasic : Language.CSharp; return (true, optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(string option, string value, Language language)> settingsToUpdate) { if (originalText is null) throw new ArgumentNullException(nameof(originalText)); if (filePath is null) throw new ArgumentNullException(nameof(filePath)); if (settingsToUpdate is null) throw new ArgumentNullException(nameof(settingsToUpdate)); var updatedText = originalText; TextLine? lastValidHeaderSpanEnd; TextLine? lastValidSpecificHeaderSpanEnd; foreach (var (option, value, language) in settingsToUpdate) { SourceText? newText; (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = UpdateIfExistsInFile(updatedText, filePath, option, value, language); if (newText != null) { updatedText = newText; continue; } (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = AddMissingRule(updatedText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd, option, value, language); if (newText != null) { updatedText = newText; } } return updatedText.Equals(originalText) ? null : updatedText; } /// <summary> /// <para>Regular expression for .editorconfig header.</para> /// <para>For example: "[*.cs] # Optional comment"</para> /// <para> "[*.{vb,cs}]"</para> /// <para> "[*] ; Optional comment"</para> /// <para> "[ConsoleApp/Program.cs]"</para> /// </summary> private static readonly Regex s_headerPattern = new(@"\[(\*|[^ #;\[\]]+\.({[^ #;{}\.\[\]]+}|[^ #;{}\.\[\]]+))\]\s*([#;].*)?"); /// <summary> /// <para>Regular expression for .editorconfig code style option entry.</para> /// <para>For example:</para> /// <para> 1. "dotnet_style_object_initializer = true # Optional comment"</para> /// <para> 2. "dotnet_style_object_initializer = true:suggestion ; Optional comment"</para> /// <para> 3. "dotnet_diagnostic.CA2000.severity = suggestion # Optional comment"</para> /// <para> 4. "dotnet_analyzer_diagnostic.category-Security.severity = suggestion # Optional comment"</para> /// <para> 5. "dotnet_analyzer_diagnostic.severity = suggestion # Optional comment"</para> /// <para>Regex groups:</para> /// <para> 1. Option key</para> /// <para> 2. Option value</para> /// <para> 3. Optional severity suffix in option value, i.e. ':severity' suffix</para> /// <para>4. Optional comment suffix</para> /// </summary> private static readonly Regex s_optionEntryPattern = new($@"(.*)=([\w, ]*)(:[\w]+)?([ ]*[;#].*)?"); private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) UpdateIfExistsInFile(SourceText editorConfigText, string filePath, string optionName, string optionValue, Language language) { var editorConfigDirectory = PathUtilities.GetDirectoryName(filePath); Assumes.NotNull(editorConfigDirectory); var relativePath = PathUtilities.GetRelativePath(editorConfigDirectory.ToLowerInvariant(), filePath); TextLine? mostRecentHeader = null; TextLine? lastValidHeader = null; TextLine? lastValidHeaderSpanEnd = null; TextLine? lastValidSpecificHeader = null; TextLine? lastValidSpecificHeaderSpanEnd = null; var textChange = new TextChange(); foreach (var curLine in editorConfigText.Lines) { var curLineText = curLine.ToString(); if (s_optionEntryPattern.IsMatch(curLineText)) { var groups = s_optionEntryPattern.Match(curLineText).Groups; var (untrimmedKey, key, value, severity, comment) = GetGroups(groups); // Verify the most recent header is a valid header if (IsValidHeader(mostRecentHeader, lastValidHeader) && string.Equals(key, optionName, StringComparison.OrdinalIgnoreCase)) { // We found the rule in the file -- replace it with updated option value. textChange = new TextChange(curLine.Span, $"{untrimmedKey}={optionValue}{comment}"); } } else if (s_headerPattern.IsMatch(curLineText.Trim())) { mostRecentHeader = curLine; if (ShouldSetAsLastValidHeader(curLineText, out var mostRecentHeaderText)) { lastValidHeader = mostRecentHeader; } else { var (fileName, splicedFileExtensions) = ParseHeaderParts(mostRecentHeaderText); if ((relativePath.IsEmpty() || new Regex(fileName).IsMatch(relativePath)) && HeaderMatchesLanguageRequirements(language, splicedFileExtensions)) { lastValidHeader = mostRecentHeader; } } } // We want to keep track of how far this (valid) section spans. if (IsValidHeader(mostRecentHeader, lastValidHeader) && IsNotEmptyOrComment(curLineText)) { lastValidHeaderSpanEnd = curLine; if (lastValidSpecificHeader != null && mostRecentHeader.Equals(lastValidSpecificHeader)) { lastValidSpecificHeaderSpanEnd = curLine; } } } // We return only the last text change in case of duplicate entries for the same rule. if (textChange != default) { return (editorConfigText.WithChanges(textChange), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // Rule not found. return (null, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); static (string untrimmedKey, string key, string value, string severitySuffixInValue, string commentValue) GetGroups(GroupCollection groups) { var untrimmedKey = groups[1].Value.ToString(); var key = untrimmedKey.Trim(); var value = groups[2].Value.ToString(); var severitySuffixInValue = groups[3].Value.ToString(); var commentValue = groups[4].Value.ToString(); return (untrimmedKey, key, value, severitySuffixInValue, commentValue); } static bool IsValidHeader(TextLine? mostRecentHeader, TextLine? lastValidHeader) { return mostRecentHeader is not null && lastValidHeader is not null && mostRecentHeader.Equals(lastValidHeader); } static bool ShouldSetAsLastValidHeader(string curLineText, out string mostRecentHeaderText) { var groups = s_headerPattern.Match(curLineText.Trim()).Groups; mostRecentHeaderText = groups[1].Value.ToString().ToLowerInvariant(); return mostRecentHeaderText.Equals("*", StringComparison.Ordinal); } static (string fileName, string[] splicedFileExtensions) ParseHeaderParts(string mostRecentHeaderText) { // We splice on the last occurrence of '.' to account for filenames containing periods. var nameExtensionSplitIndex = mostRecentHeaderText.LastIndexOf('.'); var fileName = mostRecentHeaderText.Substring(0, nameExtensionSplitIndex); var splicedFileExtensions = mostRecentHeaderText[(nameExtensionSplitIndex + 1)..].Split(',', ' ', '{', '}'); // Replacing characters in the header with the regex equivalent. fileName = fileName.Replace(".", @"\."); fileName = fileName.Replace("*", ".*"); fileName = fileName.Replace("/", @"\/"); return (fileName, splicedFileExtensions); } static bool IsNotEmptyOrComment(string currentLineText) { return !string.IsNullOrWhiteSpace(currentLineText) && !currentLineText.Trim().StartsWith("#", StringComparison.OrdinalIgnoreCase); } static bool HeaderMatchesLanguageRequirements(Language language, string[] splicedFileExtensions) { return IsCSharpOnly(language, splicedFileExtensions) || IsVisualBasicOnly(language, splicedFileExtensions) || IsBothVisualBasicAndCSharp(language, splicedFileExtensions); } static bool IsCSharpOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.CSharp) && !language.HasFlag(Language.VisualBasic) && splicedFileExtensions.Contains("cs") && splicedFileExtensions.Length == 1; } static bool IsVisualBasicOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && !language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Length == 1; } static bool IsBothVisualBasicAndCSharp(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Contains("cs"); } } private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) AddMissingRule(SourceText editorConfigText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd, string optionName, string optionValue, Language language) { var newEntry = $"{optionName}={optionValue}"; if (lastValidSpecificHeaderSpanEnd.HasValue) { if (lastValidSpecificHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidSpecificHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } else if (lastValidHeaderSpanEnd.HasValue) { if (lastValidHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // We need to generate a new header such as '[*.cs]' or '[*.vb]': // - For compiler diagnostic entries and code style entries which have per-language option = false, generate only [*.cs] or [*.vb]. // - For the remainder, generate [*.{cs,vb}] // Insert a newline if not already present var lines = editorConfigText.Lines; var lastLine = lines.Count > 0 ? lines[^1] : default; var prefix = string.Empty; if (lastLine.ToString().Trim().Length != 0) { prefix = "\r\n"; } // Insert newline if file is not empty if (lines.Count > 1 && lastLine.ToString().Trim().Length == 0) { prefix += "\r\n"; } if (language.HasFlag(Language.CSharp) && language.HasFlag(Language.VisualBasic)) { prefix += "[*.{cs,vb}]\r\n"; } else if (language.HasFlag(Language.CSharp)) { prefix += "[*.cs]\r\n"; } else if (language.HasFlag(Language.VisualBasic)) { prefix += "[*.vb]\r\n"; } var result = editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(editorConfigText.Length, 0), prefix + newEntry)); return (result, lastValidHeaderSpanEnd, result.Lines[^2]); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/CSharp/Portable/Structure/Providers/DocumentationCommentStructureProvider.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.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class DocumentationCommentStructureProvider : AbstractSyntaxNodeStructureProvider<DocumentationCommentTriviaSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, DocumentationCommentTriviaSyntax documentationComment, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var startPos = documentationComment.FullSpan.Start; // The trailing newline is included in XmlDocCommentSyntax, so we need to strip it. var endPos = documentationComment.SpanStart + documentationComment.ToString().TrimEnd().Length; var span = TextSpan.FromBounds(startPos, endPos); var bannerLength = optionProvider.GetOption(BlockStructureOptions.MaximumBannerLength, LanguageNames.CSharp); var bannerText = CSharpSyntaxFacts.Instance.GetBannerText( documentationComment, bannerLength, cancellationToken); spans.Add(new BlockSpan( isCollapsible: true, textSpan: span, type: BlockTypes.Comment, bannerText: bannerText, autoCollapse: 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.Threading; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class DocumentationCommentStructureProvider : AbstractSyntaxNodeStructureProvider<DocumentationCommentTriviaSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, DocumentationCommentTriviaSyntax documentationComment, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var startPos = documentationComment.FullSpan.Start; // The trailing newline is included in XmlDocCommentSyntax, so we need to strip it. var endPos = documentationComment.SpanStart + documentationComment.ToString().TrimEnd().Length; var span = TextSpan.FromBounds(startPos, endPos); var bannerLength = optionProvider.GetOption(BlockStructureOptions.MaximumBannerLength, LanguageNames.CSharp); var bannerText = CSharpSyntaxFacts.Instance.GetBannerText( documentationComment, bannerLength, cancellationToken); spans.Add(new BlockSpan( isCollapsible: true, textSpan: span, type: BlockTypes.Comment, bannerText: bannerText, autoCollapse: true)); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.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.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { /// <summary> /// represents a general trivia between two tokens. slightly more expensive than others since it /// needs to calculate stuff unlike other cases /// </summary> private class ComplexTrivia : AbstractComplexTrivia { public ComplexTrivia(AnalyzerConfigOptions options, TreeData treeInfo, SyntaxToken token1, SyntaxToken token2) : base(options, treeInfo, token1, token2) { } protected override void ExtractLineAndSpace(string text, out int lines, out int spaces) => text.ProcessTextBetweenTokens(this.TreeInfo, this.Token1, this.Options.GetOption(FormattingOptions2.TabSize), out lines, out spaces); protected override TriviaData CreateComplexTrivia(int line, int space) => CreateModifiedComplexTrivia(line, space); protected override TriviaData CreateComplexTrivia(int line, int space, int indentation) => CreateModifiedComplexTrivia(line, space); private TriviaData CreateModifiedComplexTrivia(int line, int space) => new ModifiedComplexTrivia(this.Options, this, line, space); protected override TriviaDataWithList Format( FormattingContext context, ChainedFormattingRules formattingRules, int lines, int spaces, CancellationToken cancellationToken) { return new FormattedComplexTrivia(context, formattingRules, this.Token1, this.Token2, lines, spaces, this.OriginalString, cancellationToken); } protected override bool ContainsSkippedTokensOrText(TriviaList list) => CodeShapeAnalyzer.ContainsSkippedTokensOrText(list); private bool ShouldFormat(FormattingContext context) { var commonToken1 = this.Token1; var commonToken2 = this.Token2; var formatSpanEnd = commonToken2.Kind() == SyntaxKind.None ? commonToken1.Span.End : commonToken2.Span.Start; var span = TextSpan.FromBounds(commonToken1.Span.End, formatSpanEnd); if (context.IsSpacingSuppressed(span, TreatAsElastic)) { return false; } var triviaList = new TriviaList(commonToken1.TrailingTrivia, commonToken2.LeadingTrivia); Contract.ThrowIfFalse(triviaList.Count > 0); // okay, now, check whether we need or are able to format noisy tokens if (ContainsSkippedTokensOrText(triviaList)) { return false; } if (!this.SecondTokenIsFirstTokenOnLine) { return CodeShapeAnalyzer.ShouldFormatSingleLine(triviaList); } Debug.Assert(this.SecondTokenIsFirstTokenOnLine); if (this.Options.GetOption(FormattingOptions2.UseTabs)) { return true; } var firstTriviaInTree = this.Token1.Kind() == SyntaxKind.None; return CodeShapeAnalyzer.ShouldFormatMultiLine(context, firstTriviaInTree, triviaList); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { if (!ShouldFormat(context)) { return; } formattingResultApplier(tokenPairIndex, context.TokenStream, Format(context, formattingRules, this.LineBreaks, this.Spaces, cancellationToken)); } public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => throw new NotImplementedException(); public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => 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.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { /// <summary> /// represents a general trivia between two tokens. slightly more expensive than others since it /// needs to calculate stuff unlike other cases /// </summary> private class ComplexTrivia : AbstractComplexTrivia { public ComplexTrivia(AnalyzerConfigOptions options, TreeData treeInfo, SyntaxToken token1, SyntaxToken token2) : base(options, treeInfo, token1, token2) { } protected override void ExtractLineAndSpace(string text, out int lines, out int spaces) => text.ProcessTextBetweenTokens(this.TreeInfo, this.Token1, this.Options.GetOption(FormattingOptions2.TabSize), out lines, out spaces); protected override TriviaData CreateComplexTrivia(int line, int space) => CreateModifiedComplexTrivia(line, space); protected override TriviaData CreateComplexTrivia(int line, int space, int indentation) => CreateModifiedComplexTrivia(line, space); private TriviaData CreateModifiedComplexTrivia(int line, int space) => new ModifiedComplexTrivia(this.Options, this, line, space); protected override TriviaDataWithList Format( FormattingContext context, ChainedFormattingRules formattingRules, int lines, int spaces, CancellationToken cancellationToken) { return new FormattedComplexTrivia(context, formattingRules, this.Token1, this.Token2, lines, spaces, this.OriginalString, cancellationToken); } protected override bool ContainsSkippedTokensOrText(TriviaList list) => CodeShapeAnalyzer.ContainsSkippedTokensOrText(list); private bool ShouldFormat(FormattingContext context) { var commonToken1 = this.Token1; var commonToken2 = this.Token2; var formatSpanEnd = commonToken2.Kind() == SyntaxKind.None ? commonToken1.Span.End : commonToken2.Span.Start; var span = TextSpan.FromBounds(commonToken1.Span.End, formatSpanEnd); if (context.IsSpacingSuppressed(span, TreatAsElastic)) { return false; } var triviaList = new TriviaList(commonToken1.TrailingTrivia, commonToken2.LeadingTrivia); Contract.ThrowIfFalse(triviaList.Count > 0); // okay, now, check whether we need or are able to format noisy tokens if (ContainsSkippedTokensOrText(triviaList)) { return false; } if (!this.SecondTokenIsFirstTokenOnLine) { return CodeShapeAnalyzer.ShouldFormatSingleLine(triviaList); } Debug.Assert(this.SecondTokenIsFirstTokenOnLine); if (this.Options.GetOption(FormattingOptions2.UseTabs)) { return true; } var firstTriviaInTree = this.Token1.Kind() == SyntaxKind.None; return CodeShapeAnalyzer.ShouldFormatMultiLine(context, firstTriviaInTree, triviaList); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { if (!ShouldFormat(context)) { return; } formattingResultApplier(tokenPairIndex, context.TokenStream, Format(context, formattingRules, this.LineBreaks, this.Spaces, cancellationToken)); } public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => throw new NotImplementedException(); public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private const string ArgumentElementName = "Argument"; private const string ArrayElementName = "Array"; private const string ArrayElementAccessElementName = "ArrayElementAccess"; private const string ArrayTypeElementName = "ArrayType"; private const string AssignmentElementName = "Assignment"; private const string BaseReferenceElementName = "BaseReference"; private const string BinaryOperationElementName = "BinaryOperation"; private const string BlockElementName = "Block"; private const string BooleanElementName = "Boolean"; private const string BoundElementName = "Bound"; private const string CastElementName = "Cast"; private const string CharElementName = "Char"; private const string CommentElementName = "Comment"; private const string ExpressionElementName = "Expression"; private const string ExpressionStatementElementName = "ExpressionStatement"; private const string LiteralElementName = "Literal"; private const string LocalElementName = "Local"; private const string MethodCallElementName = "MethodCall"; private const string NameElementName = "Name"; private const string NameRefElementName = "NameRef"; private const string NewArrayElementName = "NewArray"; private const string NewClassElementName = "NewClass"; private const string NewDelegateElementName = "NewDelegate"; private const string NullElementName = "Null"; private const string NumberElementName = "Number"; private const string ParenthesesElementName = "Parentheses"; private const string QuoteElementName = "Quote"; private const string StringElementName = "String"; private const string ThisReferenceElementName = "ThisReference"; private const string TypeElementName = "Type"; private const string BinaryOperatorAttributeName = "binaryoperator"; private const string DirectCastAttributeName = "directcast"; private const string FullNameAttributeName = "fullname"; private const string ImplicitAttributeName = "implicit"; private const string LineAttributeName = "line"; private const string NameAttributeName = "name"; private const string RankAttributeName = "rank"; private const string TryCastAttributeName = "trycast"; private const string TypeAttributeName = "type"; private const string VariableKindAttributeName = "variablekind"; private static readonly char[] s_encodedChars = new[] { '<', '>', '&' }; private static readonly string[] s_encodings = new[] { "&lt;", "&gt;", "&amp;" }; private readonly StringBuilder _builder; protected readonly IMethodSymbol Symbol; protected readonly SemanticModel SemanticModel; protected readonly SourceText Text; protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel) { _builder = new StringBuilder(); this.Symbol = symbol; this.SemanticModel = semanticModel; this.Text = semanticModel.SyntaxTree.GetText(); } public override string ToString() => _builder.ToString(); private void AppendEncoded(string text) { var length = text.Length; var startIndex = 0; int index; for (index = 0; index < length; index++) { var encodingIndex = Array.IndexOf(s_encodedChars, text[index]); if (encodingIndex >= 0) { if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } _builder.Append(s_encodings[encodingIndex]); startIndex = index + 1; } } if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } } private void AppendOpenTag(string name, AttributeInfo[] attributes) { _builder.Append('<'); _builder.Append(name); foreach (var attribute in attributes.Where(a => !a.IsEmpty)) { _builder.Append(' '); _builder.Append(attribute.Name); _builder.Append("=\""); AppendEncoded(attribute.Value); _builder.Append('"'); } _builder.Append('>'); } private void AppendCloseTag(string name) { _builder.Append("</"); _builder.Append(name); _builder.Append('>'); } private void AppendLeafTag(string name) { _builder.Append('<'); _builder.Append(name); _builder.Append("/>"); } private static string GetBinaryOperatorKindText(BinaryOperatorKind kind) => kind switch { BinaryOperatorKind.Plus => "plus", BinaryOperatorKind.BitwiseOr => "bitor", BinaryOperatorKind.BitwiseAnd => "bitand", BinaryOperatorKind.Concatenate => "concatenate", BinaryOperatorKind.AddDelegate => "adddelegate", _ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()), }; private static string GetVariableKindText(VariableKind kind) => kind switch { VariableKind.Property => "property", VariableKind.Method => "method", VariableKind.Field => "field", VariableKind.Local => "local", VariableKind.Unknown => "unknown", _ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()), }; private IDisposable Tag(string name, params AttributeInfo[] attributes) => new AutoTag(this, name, attributes); private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind) { if (kind == BinaryOperatorKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind)); } private AttributeInfo FullNameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(FullNameAttributeName, name); } private AttributeInfo ImplicitAttribute(bool? @implicit) { if (@implicit == null) { return AttributeInfo.Empty; } return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no"); } private AttributeInfo LineNumberAttribute(int lineNumber) => new AttributeInfo(LineAttributeName, lineNumber.ToString()); private AttributeInfo NameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(NameAttributeName, name); } private AttributeInfo RankAttribute(int rank) => new AttributeInfo(RankAttributeName, rank.ToString()); private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null) => specialCastKind switch { SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"), SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"), _ => AttributeInfo.Empty, }; private AttributeInfo TypeAttribute(string typeName) { if (string.IsNullOrWhiteSpace(typeName)) { return AttributeInfo.Empty; } return new AttributeInfo(TypeAttributeName, typeName); } private AttributeInfo VariableKindAttribute(VariableKind kind) { if (kind == VariableKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind)); } protected IDisposable ArgumentTag() => Tag(ArgumentElementName); protected IDisposable ArrayElementAccessTag() => Tag(ArrayElementAccessElementName); protected IDisposable ArrayTag() => Tag(ArrayElementName); protected IDisposable ArrayTypeTag(int rank) => Tag(ArrayTypeElementName, RankAttribute(rank)); protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None) => Tag(AssignmentElementName, BinaryOperatorAttribute(kind)); protected void BaseReferenceTag() => AppendLeafTag(BaseReferenceElementName); protected IDisposable BinaryOperationTag(BinaryOperatorKind kind) => Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind)); protected IDisposable BlockTag() => Tag(BlockElementName); protected IDisposable BooleanTag() => Tag(BooleanElementName); protected IDisposable BoundTag() => Tag(BoundElementName); protected IDisposable CastTag(SpecialCastKind? specialCastKind = null) => Tag(CastElementName, SpecialCastKindAttribute(specialCastKind)); protected IDisposable CharTag() => Tag(CharElementName); protected IDisposable CommentTag() => Tag(CommentElementName); protected IDisposable ExpressionTag() => Tag(ExpressionElementName); protected IDisposable ExpressionStatementTag(int lineNumber) => Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber)); protected IDisposable LiteralTag() => Tag(LiteralElementName); protected IDisposable LocalTag(int lineNumber) => Tag(LocalElementName, LineNumberAttribute(lineNumber)); protected IDisposable MethodCallTag() => Tag(MethodCallElementName); protected IDisposable NameTag() => Tag(NameElementName); protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null) => Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName)); protected IDisposable NewArrayTag() => Tag(NewArrayElementName); protected IDisposable NewClassTag() => Tag(NewClassElementName); protected IDisposable NewDelegateTag(string name) => Tag(NewDelegateElementName, NameAttribute(name)); protected void NullTag() => AppendLeafTag(NullElementName); protected IDisposable NumberTag(string typeName = null) => Tag(NumberElementName, TypeAttribute(typeName)); protected IDisposable ParenthesesTag() => Tag(ParenthesesElementName); protected IDisposable QuoteTag(int lineNumber) => Tag(QuoteElementName, LineNumberAttribute(lineNumber)); protected IDisposable StringTag() => Tag(StringElementName); protected void ThisReferenceTag() => AppendLeafTag(ThisReferenceElementName); protected IDisposable TypeTag(bool? @implicit = null) => Tag(TypeElementName, ImplicitAttribute(@implicit)); protected void LineBreak() => _builder.AppendLine(); protected void EncodedText(string text) => AppendEncoded(text); protected int GetMark() => _builder.Length; protected void Rewind(int mark) => _builder.Length = mark; protected virtual VariableKind GetVariableKind(ISymbol symbol) { if (symbol == null) { return VariableKind.Unknown; } switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: return VariableKind.Field; case SymbolKind.Local: case SymbolKind.Parameter: return VariableKind.Local; case SymbolKind.Method: return VariableKind.Method; case SymbolKind.Property: return VariableKind.Property; default: throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString()); } } protected string GetTypeName(ITypeSymbol typeSymbol) => MetadataNameHelpers.GetMetadataName(typeSymbol); protected int GetLineNumber(SyntaxNode node) => Text.Lines.IndexOf(node.SpanStart); protected void GenerateUnknown(SyntaxNode node) { using (QuoteTag(GetLineNumber(node))) { EncodedText(node.ToString()); } } protected void GenerateName(string name) { using (NameTag()) { EncodedText(name); } } protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false) { if (type.TypeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; using var tag = ArrayTypeTag(arrayType.Rank); GenerateType(arrayType.ElementType, @implicit, assemblyQualify); } else { using (TypeTag(@implicit)) { var typeName = assemblyQualify ? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString() : GetTypeName(type); EncodedText(typeName); } } } protected void GenerateType(SpecialType specialType) => GenerateType(SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateNullLiteral() { using (LiteralTag()) { NullTag(); } } protected void GenerateNumber(object value, ITypeSymbol type) { using (NumberTag(GetTypeName(type))) { if (value is double d) { // Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit EncodedText(d.ToString("G17", CultureInfo.InvariantCulture)); } else if (value is float f) { EncodedText(f.ToString("R", CultureInfo.InvariantCulture)); } else { EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture)); } } } protected void GenerateNumber(object value, SpecialType specialType) => GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateChar(char value) { using (CharTag()) { EncodedText(value.ToString()); } } protected void GenerateString(string value) { using (StringTag()) { EncodedText(value); } } protected void GenerateBoolean(bool value) { using (BooleanTag()) { EncodedText(value.ToString().ToLower()); } } protected void GenerateThisReference() => ThisReferenceTag(); protected void GenerateBaseReference() => BaseReferenceTag(); } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private const string ArgumentElementName = "Argument"; private const string ArrayElementName = "Array"; private const string ArrayElementAccessElementName = "ArrayElementAccess"; private const string ArrayTypeElementName = "ArrayType"; private const string AssignmentElementName = "Assignment"; private const string BaseReferenceElementName = "BaseReference"; private const string BinaryOperationElementName = "BinaryOperation"; private const string BlockElementName = "Block"; private const string BooleanElementName = "Boolean"; private const string BoundElementName = "Bound"; private const string CastElementName = "Cast"; private const string CharElementName = "Char"; private const string CommentElementName = "Comment"; private const string ExpressionElementName = "Expression"; private const string ExpressionStatementElementName = "ExpressionStatement"; private const string LiteralElementName = "Literal"; private const string LocalElementName = "Local"; private const string MethodCallElementName = "MethodCall"; private const string NameElementName = "Name"; private const string NameRefElementName = "NameRef"; private const string NewArrayElementName = "NewArray"; private const string NewClassElementName = "NewClass"; private const string NewDelegateElementName = "NewDelegate"; private const string NullElementName = "Null"; private const string NumberElementName = "Number"; private const string ParenthesesElementName = "Parentheses"; private const string QuoteElementName = "Quote"; private const string StringElementName = "String"; private const string ThisReferenceElementName = "ThisReference"; private const string TypeElementName = "Type"; private const string BinaryOperatorAttributeName = "binaryoperator"; private const string DirectCastAttributeName = "directcast"; private const string FullNameAttributeName = "fullname"; private const string ImplicitAttributeName = "implicit"; private const string LineAttributeName = "line"; private const string NameAttributeName = "name"; private const string RankAttributeName = "rank"; private const string TryCastAttributeName = "trycast"; private const string TypeAttributeName = "type"; private const string VariableKindAttributeName = "variablekind"; private static readonly char[] s_encodedChars = new[] { '<', '>', '&' }; private static readonly string[] s_encodings = new[] { "&lt;", "&gt;", "&amp;" }; private readonly StringBuilder _builder; protected readonly IMethodSymbol Symbol; protected readonly SemanticModel SemanticModel; protected readonly SourceText Text; protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel) { _builder = new StringBuilder(); this.Symbol = symbol; this.SemanticModel = semanticModel; this.Text = semanticModel.SyntaxTree.GetText(); } public override string ToString() => _builder.ToString(); private void AppendEncoded(string text) { var length = text.Length; var startIndex = 0; int index; for (index = 0; index < length; index++) { var encodingIndex = Array.IndexOf(s_encodedChars, text[index]); if (encodingIndex >= 0) { if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } _builder.Append(s_encodings[encodingIndex]); startIndex = index + 1; } } if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } } private void AppendOpenTag(string name, AttributeInfo[] attributes) { _builder.Append('<'); _builder.Append(name); foreach (var attribute in attributes.Where(a => !a.IsEmpty)) { _builder.Append(' '); _builder.Append(attribute.Name); _builder.Append("=\""); AppendEncoded(attribute.Value); _builder.Append('"'); } _builder.Append('>'); } private void AppendCloseTag(string name) { _builder.Append("</"); _builder.Append(name); _builder.Append('>'); } private void AppendLeafTag(string name) { _builder.Append('<'); _builder.Append(name); _builder.Append("/>"); } private static string GetBinaryOperatorKindText(BinaryOperatorKind kind) => kind switch { BinaryOperatorKind.Plus => "plus", BinaryOperatorKind.BitwiseOr => "bitor", BinaryOperatorKind.BitwiseAnd => "bitand", BinaryOperatorKind.Concatenate => "concatenate", BinaryOperatorKind.AddDelegate => "adddelegate", _ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()), }; private static string GetVariableKindText(VariableKind kind) => kind switch { VariableKind.Property => "property", VariableKind.Method => "method", VariableKind.Field => "field", VariableKind.Local => "local", VariableKind.Unknown => "unknown", _ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()), }; private IDisposable Tag(string name, params AttributeInfo[] attributes) => new AutoTag(this, name, attributes); private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind) { if (kind == BinaryOperatorKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind)); } private AttributeInfo FullNameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(FullNameAttributeName, name); } private AttributeInfo ImplicitAttribute(bool? @implicit) { if (@implicit == null) { return AttributeInfo.Empty; } return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no"); } private AttributeInfo LineNumberAttribute(int lineNumber) => new AttributeInfo(LineAttributeName, lineNumber.ToString()); private AttributeInfo NameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(NameAttributeName, name); } private AttributeInfo RankAttribute(int rank) => new AttributeInfo(RankAttributeName, rank.ToString()); private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null) => specialCastKind switch { SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"), SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"), _ => AttributeInfo.Empty, }; private AttributeInfo TypeAttribute(string typeName) { if (string.IsNullOrWhiteSpace(typeName)) { return AttributeInfo.Empty; } return new AttributeInfo(TypeAttributeName, typeName); } private AttributeInfo VariableKindAttribute(VariableKind kind) { if (kind == VariableKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind)); } protected IDisposable ArgumentTag() => Tag(ArgumentElementName); protected IDisposable ArrayElementAccessTag() => Tag(ArrayElementAccessElementName); protected IDisposable ArrayTag() => Tag(ArrayElementName); protected IDisposable ArrayTypeTag(int rank) => Tag(ArrayTypeElementName, RankAttribute(rank)); protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None) => Tag(AssignmentElementName, BinaryOperatorAttribute(kind)); protected void BaseReferenceTag() => AppendLeafTag(BaseReferenceElementName); protected IDisposable BinaryOperationTag(BinaryOperatorKind kind) => Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind)); protected IDisposable BlockTag() => Tag(BlockElementName); protected IDisposable BooleanTag() => Tag(BooleanElementName); protected IDisposable BoundTag() => Tag(BoundElementName); protected IDisposable CastTag(SpecialCastKind? specialCastKind = null) => Tag(CastElementName, SpecialCastKindAttribute(specialCastKind)); protected IDisposable CharTag() => Tag(CharElementName); protected IDisposable CommentTag() => Tag(CommentElementName); protected IDisposable ExpressionTag() => Tag(ExpressionElementName); protected IDisposable ExpressionStatementTag(int lineNumber) => Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber)); protected IDisposable LiteralTag() => Tag(LiteralElementName); protected IDisposable LocalTag(int lineNumber) => Tag(LocalElementName, LineNumberAttribute(lineNumber)); protected IDisposable MethodCallTag() => Tag(MethodCallElementName); protected IDisposable NameTag() => Tag(NameElementName); protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null) => Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName)); protected IDisposable NewArrayTag() => Tag(NewArrayElementName); protected IDisposable NewClassTag() => Tag(NewClassElementName); protected IDisposable NewDelegateTag(string name) => Tag(NewDelegateElementName, NameAttribute(name)); protected void NullTag() => AppendLeafTag(NullElementName); protected IDisposable NumberTag(string typeName = null) => Tag(NumberElementName, TypeAttribute(typeName)); protected IDisposable ParenthesesTag() => Tag(ParenthesesElementName); protected IDisposable QuoteTag(int lineNumber) => Tag(QuoteElementName, LineNumberAttribute(lineNumber)); protected IDisposable StringTag() => Tag(StringElementName); protected void ThisReferenceTag() => AppendLeafTag(ThisReferenceElementName); protected IDisposable TypeTag(bool? @implicit = null) => Tag(TypeElementName, ImplicitAttribute(@implicit)); protected void LineBreak() => _builder.AppendLine(); protected void EncodedText(string text) => AppendEncoded(text); protected int GetMark() => _builder.Length; protected void Rewind(int mark) => _builder.Length = mark; protected virtual VariableKind GetVariableKind(ISymbol symbol) { if (symbol == null) { return VariableKind.Unknown; } switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: return VariableKind.Field; case SymbolKind.Local: case SymbolKind.Parameter: return VariableKind.Local; case SymbolKind.Method: return VariableKind.Method; case SymbolKind.Property: return VariableKind.Property; default: throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString()); } } protected string GetTypeName(ITypeSymbol typeSymbol) => MetadataNameHelpers.GetMetadataName(typeSymbol); protected int GetLineNumber(SyntaxNode node) => Text.Lines.IndexOf(node.SpanStart); protected void GenerateUnknown(SyntaxNode node) { using (QuoteTag(GetLineNumber(node))) { EncodedText(node.ToString()); } } protected void GenerateName(string name) { using (NameTag()) { EncodedText(name); } } protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false) { if (type.TypeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; using var tag = ArrayTypeTag(arrayType.Rank); GenerateType(arrayType.ElementType, @implicit, assemblyQualify); } else { using (TypeTag(@implicit)) { var typeName = assemblyQualify ? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString() : GetTypeName(type); EncodedText(typeName); } } } protected void GenerateType(SpecialType specialType) => GenerateType(SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateNullLiteral() { using (LiteralTag()) { NullTag(); } } protected void GenerateNumber(object value, ITypeSymbol type) { using (NumberTag(GetTypeName(type))) { if (value is double d) { // Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit EncodedText(d.ToString("G17", CultureInfo.InvariantCulture)); } else if (value is float f) { EncodedText(f.ToString("R", CultureInfo.InvariantCulture)); } else { EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture)); } } } protected void GenerateNumber(object value, SpecialType specialType) => GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateChar(char value) { using (CharTag()) { EncodedText(value.ToString()); } } protected void GenerateString(string value) { using (StringTag()) { EncodedText(value); } } protected void GenerateBoolean(bool value) { using (BooleanTag()) { EncodedText(value.ToString().ToLower()); } } protected void GenerateThisReference() => ThisReferenceTag(); protected void GenerateBaseReference() => BaseReferenceTag(); } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/LocationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LocationExtensions { public static SyntaxTree GetSourceTreeOrThrow(this Location location) { Contract.ThrowIfNull(location.SourceTree); return location.SourceTree; } public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindToken(location.SourceSpan.Start); public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan); public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie); public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie); public static bool IsVisibleSourceLocation(this Location loc) { if (!loc.IsInSource) { return false; } var tree = loc.SourceTree; return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start)); } public static bool IntersectsWith(this Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource && loc2.IsInSource); return loc1.SourceTree == loc2.SourceTree && loc1.SourceSpan.IntersectsWith(loc2.SourceSpan); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LocationExtensions { public static SyntaxTree GetSourceTreeOrThrow(this Location location) { Contract.ThrowIfNull(location.SourceTree); return location.SourceTree; } public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindToken(location.SourceSpan.Start); public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan); public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie); public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie); public static bool IsVisibleSourceLocation(this Location loc) { if (!loc.IsInSource) { return false; } var tree = loc.SourceTree; return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start)); } public static bool IntersectsWith(this Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource && loc2.IsInSource); return loc1.SourceTree == loc2.SourceTree && loc1.SourceSpan.IntersectsWith(loc2.SourceSpan); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Def/ExternalAccess/LegacyCodeAnalysis/LegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Suppression; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis { [Export(typeof(ILegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor))] [Shared] internal sealed class LegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor : ILegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor { private readonly VisualStudioWorkspace _workspace; private readonly IVisualStudioSuppressionFixService _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor( VisualStudioWorkspace workspace, IVisualStudioSuppressionFixService implementation) { _workspace = workspace; _implementation = implementation; } public bool AddSuppressions(IVsHierarchy? projectHierarchy) { var errorReportingService = _workspace.Services.GetRequiredService<IErrorReportingService>(); try { return _implementation.AddSuppressions(projectHierarchy); } catch (Exception ex) { errorReportingService.ShowGlobalErrorInfo( string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message), new InfoBarUI( WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true)); return false; } } public bool AddSuppressions(bool selectedErrorListEntriesOnly, bool suppressInSource, IVsHierarchy? projectHierarchy) { var errorReportingService = _workspace.Services.GetRequiredService<IErrorReportingService>(); try { return _implementation.AddSuppressions(selectedErrorListEntriesOnly, suppressInSource, projectHierarchy); } catch (Exception ex) { errorReportingService.ShowGlobalErrorInfo( string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message), new InfoBarUI( WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true)); return false; } } public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy? projectHierarchy) { var errorReportingService = _workspace.Services.GetRequiredService<IErrorReportingService>(); try { return _implementation.RemoveSuppressions(selectedErrorListEntriesOnly, projectHierarchy); } catch (Exception ex) { errorReportingService.ShowGlobalErrorInfo( string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message), new InfoBarUI( WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: 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; using System.Composition; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Suppression; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis { [Export(typeof(ILegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor))] [Shared] internal sealed class LegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor : ILegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor { private readonly VisualStudioWorkspace _workspace; private readonly IVisualStudioSuppressionFixService _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LegacyCodeAnalysisVisualStudioSuppressionFixServiceAccessor( VisualStudioWorkspace workspace, IVisualStudioSuppressionFixService implementation) { _workspace = workspace; _implementation = implementation; } public bool AddSuppressions(IVsHierarchy? projectHierarchy) { var errorReportingService = _workspace.Services.GetRequiredService<IErrorReportingService>(); try { return _implementation.AddSuppressions(projectHierarchy); } catch (Exception ex) { errorReportingService.ShowGlobalErrorInfo( string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message), new InfoBarUI( WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true)); return false; } } public bool AddSuppressions(bool selectedErrorListEntriesOnly, bool suppressInSource, IVsHierarchy? projectHierarchy) { var errorReportingService = _workspace.Services.GetRequiredService<IErrorReportingService>(); try { return _implementation.AddSuppressions(selectedErrorListEntriesOnly, suppressInSource, projectHierarchy); } catch (Exception ex) { errorReportingService.ShowGlobalErrorInfo( string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message), new InfoBarUI( WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true)); return false; } } public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy? projectHierarchy) { var errorReportingService = _workspace.Services.GetRequiredService<IErrorReportingService>(); try { return _implementation.RemoveSuppressions(selectedErrorListEntriesOnly, projectHierarchy); } catch (Exception ex) { errorReportingService.ShowGlobalErrorInfo( string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message), new InfoBarUI( WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true)); return false; } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/Portable/SymbolDisplay/FormattedSymbolList.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.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class FormattedSymbolList : IFormattable { private readonly IEnumerable<ISymbol> _symbols; private readonly SymbolDisplayFormat _symbolDisplayFormat; internal FormattedSymbolList(IEnumerable<ISymbol> symbols, SymbolDisplayFormat symbolDisplayFormat = null) { Debug.Assert(symbols != null); _symbols = symbols; _symbolDisplayFormat = symbolDisplayFormat; } public override string ToString() { PooledStringBuilder pooled = PooledStringBuilder.GetInstance(); StringBuilder builder = pooled.Builder; bool first = true; foreach (var symbol in _symbols) { if (first) { first = false; } else { builder.Append(", "); } builder.Append(symbol.ToDisplayString(_symbolDisplayFormat)); } return pooled.ToStringAndFree(); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class FormattedSymbolList : IFormattable { private readonly IEnumerable<ISymbol> _symbols; private readonly SymbolDisplayFormat _symbolDisplayFormat; internal FormattedSymbolList(IEnumerable<ISymbol> symbols, SymbolDisplayFormat symbolDisplayFormat = null) { Debug.Assert(symbols != null); _symbols = symbols; _symbolDisplayFormat = symbolDisplayFormat; } public override string ToString() { PooledStringBuilder pooled = PooledStringBuilder.GetInstance(); StringBuilder builder = pooled.Builder; bool first = true; foreach (var symbol in _symbols) { if (first) { first = false; } else { builder.Append(", "); } builder.Append(symbol.ToDisplayString(_symbolDisplayFormat)); } return pooled.ToStringAndFree(); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal static partial class SymbolCompletionItem { private static readonly Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> s_addSymbolEncoding = AddSymbolEncoding; private static readonly Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> s_addSymbolInfo = AddSymbolInfo; private static CompletionItem CreateWorker( string displayText, string displayTextSuffix, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> symbolEncoder, string sortText = null, string insertionText = null, string filterText = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string displayTextPrefix = null, string inlineDescription = null, Glyph? glyph = null, bool isComplexTextEdit = false) { var props = properties ?? ImmutableDictionary<string, string>.Empty; if (insertionText != null) { props = props.Add("InsertionText", insertionText); } props = props.Add("ContextPosition", contextPosition.ToString()); var firstSymbol = symbols[0]; var item = CommonCompletionItem.Create( displayText: displayText, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, rules: rules, filterText: filterText ?? (displayText.Length > 0 && displayText[0] == '@' ? displayText : firstSymbol.Name), sortText: sortText ?? firstSymbol.Name, glyph: glyph ?? firstSymbol.GetGlyph(), showsWarningIcon: supportedPlatforms != null, properties: props, tags: tags, isComplexTextEdit: isComplexTextEdit); item = WithSupportedPlatforms(item, supportedPlatforms); return symbolEncoder(symbols, item); } public static CompletionItem AddSymbolEncoding(IReadOnlyList<ISymbol> symbols, CompletionItem item) => item.AddProperty("Symbols", EncodeSymbols(symbols)); public static CompletionItem AddSymbolInfo(IReadOnlyList<ISymbol> symbols, CompletionItem item) { var symbol = symbols[0]; var isGeneric = symbol.GetArity() > 0; item = item .AddProperty("SymbolKind", ((int)symbol.Kind).ToString()) .AddProperty("SymbolName", symbol.Name); return isGeneric ? item.AddProperty("IsGeneric", isGeneric.ToString()) : item; } public static CompletionItem AddShouldProvideParenthesisCompletion(CompletionItem item) => item.AddProperty("ShouldProvideParenthesisCompletion", true.ToString()); public static bool GetShouldProvideParenthesisCompletion(CompletionItem item) { if (item.Properties.TryGetValue("ShouldProvideParenthesisCompletion", out _)) { return true; } return false; } public static string EncodeSymbols(IReadOnlyList<ISymbol> symbols) { if (symbols.Count > 1) { return string.Join("|", symbols.Select(s => EncodeSymbol(s))); } else if (symbols.Count == 1) { return EncodeSymbol(symbols[0]); } else { return string.Empty; } } public static string EncodeSymbol(ISymbol symbol) => SymbolKey.CreateString(symbol); public static bool HasSymbols(CompletionItem item) => item.Properties.ContainsKey("Symbols"); private static readonly char[] s_symbolSplitters = new[] { '|' }; public static async Task<ImmutableArray<ISymbol>> GetSymbolsAsync(CompletionItem item, Document document, CancellationToken cancellationToken) { if (item.Properties.TryGetValue("Symbols", out var symbolIds)) { var idList = symbolIds.Split(s_symbolSplitters, StringSplitOptions.RemoveEmptyEntries).ToList(); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); DecodeSymbols(idList, compilation, symbols); // merge in symbols from other linked documents if (idList.Count > 0) { var linkedIds = document.GetLinkedDocumentIds(); if (linkedIds.Length > 0) { foreach (var id in linkedIds) { var linkedDoc = document.Project.Solution.GetDocument(id); var linkedCompilation = await linkedDoc.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); DecodeSymbols(idList, linkedCompilation, symbols); } } } return symbols.ToImmutable(); } return ImmutableArray<ISymbol>.Empty; } private static void DecodeSymbols(List<string> ids, Compilation compilation, ArrayBuilder<ISymbol> symbols) { for (var i = 0; i < ids.Count;) { var id = ids[i]; var symbol = DecodeSymbol(id, compilation); if (symbol != null) { ids.RemoveAt(i); // consume id from the list symbols.Add(symbol); // add symbol to the results } else { i++; } } } private static ISymbol DecodeSymbol(string id, Compilation compilation) => SymbolKey.ResolveString(id, compilation).GetAnySymbol(); public static async Task<CompletionDescription> GetDescriptionAsync( CompletionItem item, Document document, CancellationToken cancellationToken) { var symbols = await GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false); return await GetDescriptionForSymbolsAsync(item, document, symbols, cancellationToken).ConfigureAwait(false); } public static async Task<CompletionDescription> GetDescriptionForSymbolsAsync( CompletionItem item, Document document, ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { if (symbols.Length == 0) return CompletionDescription.Empty; var position = GetDescriptionPosition(item); if (position == -1) position = item.Span.Start; var workspace = document.Project.Solution.Workspace; var supportedPlatforms = GetSupportedPlatforms(item, workspace); var contextDocument = FindAppropriateDocumentForDescriptionContext(document, supportedPlatforms); var semanticModel = await contextDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); return await CommonCompletionUtilities.CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms, cancellationToken).ConfigureAwait(false); } private static Document FindAppropriateDocumentForDescriptionContext(Document document, SupportedPlatformData supportedPlatforms) { var contextDocument = document; if (supportedPlatforms != null && supportedPlatforms.InvalidProjects.Contains(document.Id.ProjectId)) { var contextId = document.GetLinkedDocumentIds().FirstOrDefault(id => !supportedPlatforms.InvalidProjects.Contains(id.ProjectId)); if (contextId != null) { contextDocument = document.Project.Solution.GetDocument(contextId); } } return contextDocument; } private static CompletionItem WithSupportedPlatforms(CompletionItem completionItem, SupportedPlatformData supportedPlatforms) { if (supportedPlatforms != null) { return completionItem .AddProperty("InvalidProjects", string.Join(";", supportedPlatforms.InvalidProjects.Select(id => id.Id))) .AddProperty("CandidateProjects", string.Join(";", supportedPlatforms.CandidateProjects.Select(id => id.Id))); } else { return completionItem; } } private static readonly char[] projectSeperators = new[] { ';' }; public static SupportedPlatformData GetSupportedPlatforms(CompletionItem item, Workspace workspace) { if (item.Properties.TryGetValue("InvalidProjects", out var invalidProjects) && item.Properties.TryGetValue("CandidateProjects", out var candidateProjects)) { return new SupportedPlatformData( invalidProjects.Split(projectSeperators).Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s))).ToList(), candidateProjects.Split(projectSeperators).Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s))).ToList(), workspace); } return null; } public static int GetContextPosition(CompletionItem item) { if (item.Properties.TryGetValue("ContextPosition", out var text) && int.TryParse(text, out var number)) { return number; } else { return -1; } } public static int GetDescriptionPosition(CompletionItem item) => GetContextPosition(item); public static string GetInsertionText(CompletionItem item) { item.Properties.TryGetValue("InsertionText", out var text); return text; } // COMPAT OVERLOAD: This is used by IntelliCode. public static CompletionItem CreateWithSymbolId( string displayText, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string sortText = null, string insertionText = null, string filterText = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, bool isComplexTextEdit = false) { return CreateWithSymbolId( displayText, displayTextSuffix: null, symbols, rules, contextPosition, sortText, insertionText, filterText, displayTextPrefix: null, inlineDescription: null, glyph: null, supportedPlatforms, properties, tags, isComplexTextEdit); } public static CompletionItem CreateWithSymbolId( string displayText, string displayTextSuffix, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string sortText = null, string insertionText = null, string filterText = null, string displayTextPrefix = null, string inlineDescription = null, Glyph? glyph = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, bool isComplexTextEdit = false) { return CreateWorker( displayText, displayTextSuffix, symbols, rules, contextPosition, s_addSymbolEncoding, sortText, insertionText, filterText, supportedPlatforms, properties, tags, displayTextPrefix, inlineDescription, glyph, isComplexTextEdit); } public static CompletionItem CreateWithNameAndKind( string displayText, string displayTextSuffix, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string sortText = null, string insertionText = null, string filterText = null, string displayTextPrefix = null, string inlineDescription = null, Glyph? glyph = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, bool isComplexTextEdit = false) { return CreateWorker( displayText, displayTextSuffix, symbols, rules, contextPosition, s_addSymbolInfo, sortText, insertionText, filterText, supportedPlatforms, properties, tags, displayTextPrefix, inlineDescription, glyph, isComplexTextEdit); } internal static string GetSymbolName(CompletionItem item) => item.Properties.TryGetValue("SymbolName", out var name) ? name : null; internal static SymbolKind? GetKind(CompletionItem item) => item.Properties.TryGetValue("SymbolKind", out var kind) ? (SymbolKind?)int.Parse(kind) : null; internal static bool GetSymbolIsGeneric(CompletionItem item) => item.Properties.TryGetValue("IsGeneric", out var v) && bool.TryParse(v, out var isGeneric) && isGeneric; public static async Task<CompletionDescription> GetDescriptionAsync( CompletionItem item, IReadOnlyList<ISymbol> symbols, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var position = GetDescriptionPosition(item); var supportedPlatforms = GetSupportedPlatforms(item, workspace); if (symbols.Count != 0) { return await CommonCompletionUtilities.CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms, cancellationToken).ConfigureAwait(false); } else { return CompletionDescription.Empty; } } } }
// Licensed to the .NET Foundation under one or more 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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal static partial class SymbolCompletionItem { private static readonly Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> s_addSymbolEncoding = AddSymbolEncoding; private static readonly Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> s_addSymbolInfo = AddSymbolInfo; private static CompletionItem CreateWorker( string displayText, string displayTextSuffix, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> symbolEncoder, string sortText = null, string insertionText = null, string filterText = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string displayTextPrefix = null, string inlineDescription = null, Glyph? glyph = null, bool isComplexTextEdit = false) { var props = properties ?? ImmutableDictionary<string, string>.Empty; if (insertionText != null) { props = props.Add("InsertionText", insertionText); } props = props.Add("ContextPosition", contextPosition.ToString()); var firstSymbol = symbols[0]; var item = CommonCompletionItem.Create( displayText: displayText, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, rules: rules, filterText: filterText ?? (displayText.Length > 0 && displayText[0] == '@' ? displayText : firstSymbol.Name), sortText: sortText ?? firstSymbol.Name, glyph: glyph ?? firstSymbol.GetGlyph(), showsWarningIcon: supportedPlatforms != null, properties: props, tags: tags, isComplexTextEdit: isComplexTextEdit); item = WithSupportedPlatforms(item, supportedPlatforms); return symbolEncoder(symbols, item); } public static CompletionItem AddSymbolEncoding(IReadOnlyList<ISymbol> symbols, CompletionItem item) => item.AddProperty("Symbols", EncodeSymbols(symbols)); public static CompletionItem AddSymbolInfo(IReadOnlyList<ISymbol> symbols, CompletionItem item) { var symbol = symbols[0]; var isGeneric = symbol.GetArity() > 0; item = item .AddProperty("SymbolKind", ((int)symbol.Kind).ToString()) .AddProperty("SymbolName", symbol.Name); return isGeneric ? item.AddProperty("IsGeneric", isGeneric.ToString()) : item; } public static CompletionItem AddShouldProvideParenthesisCompletion(CompletionItem item) => item.AddProperty("ShouldProvideParenthesisCompletion", true.ToString()); public static bool GetShouldProvideParenthesisCompletion(CompletionItem item) { if (item.Properties.TryGetValue("ShouldProvideParenthesisCompletion", out _)) { return true; } return false; } public static string EncodeSymbols(IReadOnlyList<ISymbol> symbols) { if (symbols.Count > 1) { return string.Join("|", symbols.Select(s => EncodeSymbol(s))); } else if (symbols.Count == 1) { return EncodeSymbol(symbols[0]); } else { return string.Empty; } } public static string EncodeSymbol(ISymbol symbol) => SymbolKey.CreateString(symbol); public static bool HasSymbols(CompletionItem item) => item.Properties.ContainsKey("Symbols"); private static readonly char[] s_symbolSplitters = new[] { '|' }; public static async Task<ImmutableArray<ISymbol>> GetSymbolsAsync(CompletionItem item, Document document, CancellationToken cancellationToken) { if (item.Properties.TryGetValue("Symbols", out var symbolIds)) { var idList = symbolIds.Split(s_symbolSplitters, StringSplitOptions.RemoveEmptyEntries).ToList(); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); DecodeSymbols(idList, compilation, symbols); // merge in symbols from other linked documents if (idList.Count > 0) { var linkedIds = document.GetLinkedDocumentIds(); if (linkedIds.Length > 0) { foreach (var id in linkedIds) { var linkedDoc = document.Project.Solution.GetDocument(id); var linkedCompilation = await linkedDoc.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); DecodeSymbols(idList, linkedCompilation, symbols); } } } return symbols.ToImmutable(); } return ImmutableArray<ISymbol>.Empty; } private static void DecodeSymbols(List<string> ids, Compilation compilation, ArrayBuilder<ISymbol> symbols) { for (var i = 0; i < ids.Count;) { var id = ids[i]; var symbol = DecodeSymbol(id, compilation); if (symbol != null) { ids.RemoveAt(i); // consume id from the list symbols.Add(symbol); // add symbol to the results } else { i++; } } } private static ISymbol DecodeSymbol(string id, Compilation compilation) => SymbolKey.ResolveString(id, compilation).GetAnySymbol(); public static async Task<CompletionDescription> GetDescriptionAsync( CompletionItem item, Document document, CancellationToken cancellationToken) { var symbols = await GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false); return await GetDescriptionForSymbolsAsync(item, document, symbols, cancellationToken).ConfigureAwait(false); } public static async Task<CompletionDescription> GetDescriptionForSymbolsAsync( CompletionItem item, Document document, ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { if (symbols.Length == 0) return CompletionDescription.Empty; var position = GetDescriptionPosition(item); if (position == -1) position = item.Span.Start; var workspace = document.Project.Solution.Workspace; var supportedPlatforms = GetSupportedPlatforms(item, workspace); var contextDocument = FindAppropriateDocumentForDescriptionContext(document, supportedPlatforms); var semanticModel = await contextDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); return await CommonCompletionUtilities.CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms, cancellationToken).ConfigureAwait(false); } private static Document FindAppropriateDocumentForDescriptionContext(Document document, SupportedPlatformData supportedPlatforms) { var contextDocument = document; if (supportedPlatforms != null && supportedPlatforms.InvalidProjects.Contains(document.Id.ProjectId)) { var contextId = document.GetLinkedDocumentIds().FirstOrDefault(id => !supportedPlatforms.InvalidProjects.Contains(id.ProjectId)); if (contextId != null) { contextDocument = document.Project.Solution.GetDocument(contextId); } } return contextDocument; } private static CompletionItem WithSupportedPlatforms(CompletionItem completionItem, SupportedPlatformData supportedPlatforms) { if (supportedPlatforms != null) { return completionItem .AddProperty("InvalidProjects", string.Join(";", supportedPlatforms.InvalidProjects.Select(id => id.Id))) .AddProperty("CandidateProjects", string.Join(";", supportedPlatforms.CandidateProjects.Select(id => id.Id))); } else { return completionItem; } } private static readonly char[] projectSeperators = new[] { ';' }; public static SupportedPlatformData GetSupportedPlatforms(CompletionItem item, Workspace workspace) { if (item.Properties.TryGetValue("InvalidProjects", out var invalidProjects) && item.Properties.TryGetValue("CandidateProjects", out var candidateProjects)) { return new SupportedPlatformData( invalidProjects.Split(projectSeperators).Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s))).ToList(), candidateProjects.Split(projectSeperators).Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s))).ToList(), workspace); } return null; } public static int GetContextPosition(CompletionItem item) { if (item.Properties.TryGetValue("ContextPosition", out var text) && int.TryParse(text, out var number)) { return number; } else { return -1; } } public static int GetDescriptionPosition(CompletionItem item) => GetContextPosition(item); public static string GetInsertionText(CompletionItem item) { item.Properties.TryGetValue("InsertionText", out var text); return text; } // COMPAT OVERLOAD: This is used by IntelliCode. public static CompletionItem CreateWithSymbolId( string displayText, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string sortText = null, string insertionText = null, string filterText = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, bool isComplexTextEdit = false) { return CreateWithSymbolId( displayText, displayTextSuffix: null, symbols, rules, contextPosition, sortText, insertionText, filterText, displayTextPrefix: null, inlineDescription: null, glyph: null, supportedPlatforms, properties, tags, isComplexTextEdit); } public static CompletionItem CreateWithSymbolId( string displayText, string displayTextSuffix, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string sortText = null, string insertionText = null, string filterText = null, string displayTextPrefix = null, string inlineDescription = null, Glyph? glyph = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, bool isComplexTextEdit = false) { return CreateWorker( displayText, displayTextSuffix, symbols, rules, contextPosition, s_addSymbolEncoding, sortText, insertionText, filterText, supportedPlatforms, properties, tags, displayTextPrefix, inlineDescription, glyph, isComplexTextEdit); } public static CompletionItem CreateWithNameAndKind( string displayText, string displayTextSuffix, IReadOnlyList<ISymbol> symbols, CompletionItemRules rules, int contextPosition, string sortText = null, string insertionText = null, string filterText = null, string displayTextPrefix = null, string inlineDescription = null, Glyph? glyph = null, SupportedPlatformData supportedPlatforms = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, bool isComplexTextEdit = false) { return CreateWorker( displayText, displayTextSuffix, symbols, rules, contextPosition, s_addSymbolInfo, sortText, insertionText, filterText, supportedPlatforms, properties, tags, displayTextPrefix, inlineDescription, glyph, isComplexTextEdit); } internal static string GetSymbolName(CompletionItem item) => item.Properties.TryGetValue("SymbolName", out var name) ? name : null; internal static SymbolKind? GetKind(CompletionItem item) => item.Properties.TryGetValue("SymbolKind", out var kind) ? (SymbolKind?)int.Parse(kind) : null; internal static bool GetSymbolIsGeneric(CompletionItem item) => item.Properties.TryGetValue("IsGeneric", out var v) && bool.TryParse(v, out var isGeneric) && isGeneric; public static async Task<CompletionDescription> GetDescriptionAsync( CompletionItem item, IReadOnlyList<ISymbol> symbols, Document document, SemanticModel semanticModel, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var position = GetDescriptionPosition(item); var supportedPlatforms = GetSupportedPlatforms(item, workspace); if (symbols.Count != 0) { return await CommonCompletionUtilities.CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms, cancellationToken).ConfigureAwait(false); } else { return CompletionDescription.Empty; } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActionSetComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { internal class UnifiedSuggestedActionSetComparer : IComparer<UnifiedSuggestedActionSet> { private readonly TextSpan? _targetSpan; public UnifiedSuggestedActionSetComparer(TextSpan? targetSpan) => _targetSpan = targetSpan; private static int Distance(TextSpan? maybeA, TextSpan? maybeB) { // If we don't have a text span or target point we cannot calculate the distance between them if (!maybeA.HasValue || !maybeB.HasValue) { return int.MaxValue; } var a = maybeA.Value; var b = maybeB.Value; // The distance of two spans is symetric sumation of: // - the distance of a's start to b's start // - the distance of a's end to b's end // // This particular metric has been chosen because it is both simple // and uses the all the information in both spans. A weighting (i.e. // the distance of starts is more important) could be added but it // didn't seem necessary. // // E.g.: for spans [ ] and $ $ the distance is distanceOfStarts+distanceOfEnds: // $ $ [ ] has distance 2+3 // $ [ ]$ has distance 1+0 // $[ ]$ has distance 0+0 // $ [] $ has distance 1+3 // $[] $ has distance 0+4 var startsDistance = Math.Abs(a.Start - b.Start); var endsDistance = Math.Abs(a.End - b.End); return startsDistance + endsDistance; } public int Compare(UnifiedSuggestedActionSet x, UnifiedSuggestedActionSet y) { if (!_targetSpan.HasValue || !x.ApplicableToSpan.HasValue || !y.ApplicableToSpan.HasValue) { // Not enough data to compare, consider them equal return 0; } var distanceX = Distance(x.ApplicableToSpan, _targetSpan); var distanceY = Distance(y.ApplicableToSpan, _targetSpan); return distanceX.CompareTo(distanceY); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { internal class UnifiedSuggestedActionSetComparer : IComparer<UnifiedSuggestedActionSet> { private readonly TextSpan? _targetSpan; public UnifiedSuggestedActionSetComparer(TextSpan? targetSpan) => _targetSpan = targetSpan; private static int Distance(TextSpan? maybeA, TextSpan? maybeB) { // If we don't have a text span or target point we cannot calculate the distance between them if (!maybeA.HasValue || !maybeB.HasValue) { return int.MaxValue; } var a = maybeA.Value; var b = maybeB.Value; // The distance of two spans is symetric sumation of: // - the distance of a's start to b's start // - the distance of a's end to b's end // // This particular metric has been chosen because it is both simple // and uses the all the information in both spans. A weighting (i.e. // the distance of starts is more important) could be added but it // didn't seem necessary. // // E.g.: for spans [ ] and $ $ the distance is distanceOfStarts+distanceOfEnds: // $ $ [ ] has distance 2+3 // $ [ ]$ has distance 1+0 // $[ ]$ has distance 0+0 // $ [] $ has distance 1+3 // $[] $ has distance 0+4 var startsDistance = Math.Abs(a.Start - b.Start); var endsDistance = Math.Abs(a.End - b.End); return startsDistance + endsDistance; } public int Compare(UnifiedSuggestedActionSet x, UnifiedSuggestedActionSet y) { if (!_targetSpan.HasValue || !x.ApplicableToSpan.HasValue || !y.ApplicableToSpan.HasValue) { // Not enough data to compare, consider them equal return 0; } var distanceX = Distance(x.ApplicableToSpan, _targetSpan); var distanceY = Distance(y.ApplicableToSpan, _targetSpan); return distanceX.CompareTo(distanceY); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/TestUtilities2/ObjectBrowser/Mocks/MockObjectBrowserDescription.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.Text Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ObjectBrowser.Mocks Public Class MockObjectBrowserDescription Implements IVsObjectBrowserDescription3 Private ReadOnly _builder As New StringBuilder() Public Function AddDescriptionText3(pText As String, obdSect As VSOBDESCRIPTIONSECTION, pHyperJump As IVsNavInfo) As Integer Implements IVsObjectBrowserDescription3.AddDescriptionText3 If pText = vbLf Then _builder.AppendLine() Else _builder.Append(pText) End If Return VSConstants.S_OK End Function Public Function ClearDescriptionText() As Integer Implements IVsObjectBrowserDescription3.ClearDescriptionText Throw New NotSupportedException() End Function Public Overrides Function ToString() As String Return _builder.ToString() 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.Text Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ObjectBrowser.Mocks Public Class MockObjectBrowserDescription Implements IVsObjectBrowserDescription3 Private ReadOnly _builder As New StringBuilder() Public Function AddDescriptionText3(pText As String, obdSect As VSOBDESCRIPTIONSECTION, pHyperJump As IVsNavInfo) As Integer Implements IVsObjectBrowserDescription3.AddDescriptionText3 If pText = vbLf Then _builder.AppendLine() Else _builder.Append(pText) End If Return VSConstants.S_OK End Function Public Function ClearDescriptionText() As Integer Implements IVsObjectBrowserDescription3.ClearDescriptionText Throw New NotSupportedException() End Function Public Overrides Function ToString() As String Return _builder.ToString() End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Interactive/Host/PublicAPI.Unshipped.txt
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/Core/Portable/Diagnostics/DocumentAnalysisExecutor.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.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Executes analyzers on a document for computing local syntax/semantic/additional file diagnostics for a specific <see cref="DocumentAnalysisScope"/>. /// </summary> internal sealed class DocumentAnalysisExecutor { private readonly CompilationWithAnalyzers? _compilationWithAnalyzers; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; private readonly bool _logPerformanceInfo; private readonly Action? _onAnalysisException; private readonly ImmutableArray<DiagnosticAnalyzer> _compilationBasedAnalyzersInAnalysisScope; private ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? _lazySyntaxDiagnostics; private ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? _lazySemanticDiagnostics; public DocumentAnalysisExecutor( DocumentAnalysisScope analysisScope, CompilationWithAnalyzers? compilationWithAnalyzers, InProcOrRemoteHostAnalyzerRunner diagnosticAnalyzerRunner, bool logPerformanceInfo, Action? onAnalysisException = null) { AnalysisScope = analysisScope; _compilationWithAnalyzers = compilationWithAnalyzers; _diagnosticAnalyzerRunner = diagnosticAnalyzerRunner; _logPerformanceInfo = logPerformanceInfo; _onAnalysisException = onAnalysisException; var compilationBasedAnalyzers = compilationWithAnalyzers?.Analyzers.ToImmutableHashSet(); _compilationBasedAnalyzersInAnalysisScope = compilationBasedAnalyzers != null ? analysisScope.Analyzers.WhereAsArray(compilationBasedAnalyzers.Contains) : ImmutableArray<DiagnosticAnalyzer>.Empty; } public DocumentAnalysisScope AnalysisScope { get; } /// <summary> /// Return all local diagnostics (syntax, semantic) that belong to given document for the given analyzer by calculating them. /// </summary> public async Task<IEnumerable<DiagnosticData>> ComputeDiagnosticsAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) { Contract.ThrowIfFalse(AnalysisScope.Analyzers.Contains(analyzer)); var textDocument = AnalysisScope.TextDocument; var span = AnalysisScope.Span; var kind = AnalysisScope.Kind; var document = textDocument as Document; RoslynDebug.Assert(document != null || kind == AnalysisKind.Syntax, "We only support syntactic analysis for non-source documents"); var loadDiagnostic = await textDocument.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (analyzer == FileContentLoadAnalyzer.Instance) { return loadDiagnostic != null ? SpecializedCollections.SingletonEnumerable(DiagnosticData.Create(loadDiagnostic, textDocument)) : SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } if (loadDiagnostic != null) { return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } if (analyzer is DocumentDiagnosticAnalyzer documentAnalyzer) { if (document == null) { return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } var documentDiagnostics = await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync( documentAnalyzer, document, kind, _compilationWithAnalyzers?.Compilation, cancellationToken).ConfigureAwait(false); return documentDiagnostics.ConvertToLocalDiagnostics(document, span); } // quick optimization to reduce allocations. if (_compilationWithAnalyzers == null || !analyzer.SupportAnalysisKind(kind)) { if (kind == AnalysisKind.Syntax) { Logger.Log(FunctionId.Diagnostics_SyntaxDiagnostic, (r, d, a, k) => $"Driver: {r != null}, {d.Id}, {d.Project.Id}, {a}, {k}", _compilationWithAnalyzers, textDocument, analyzer, kind); } return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } // if project is not loaded successfully then, we disable semantic errors for compiler analyzers var isCompilerAnalyzer = analyzer.IsCompilerAnalyzer(); if (kind != AnalysisKind.Syntax && isCompilerAnalyzer) { var isEnabled = await textDocument.Project.HasSuccessfullyLoadedAsync(cancellationToken).ConfigureAwait(false); Logger.Log(FunctionId.Diagnostics_SemanticDiagnostic, (a, d, e) => $"{a}, ({d.Id}, {d.Project.Id}), Enabled:{e}", analyzer, textDocument, isEnabled); if (!isEnabled) { return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } } if (document == null && textDocument is not AdditionalDocument) { // We currently support document analysis only for source documents and additional documents. return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } var diagnostics = kind switch { AnalysisKind.Syntax => await GetSyntaxDiagnosticsAsync(analyzer, isCompilerAnalyzer, cancellationToken).ConfigureAwait(false), AnalysisKind.Semantic => await GetSemanticDiagnosticsAsync(analyzer, isCompilerAnalyzer, cancellationToken).ConfigureAwait(false), _ => throw ExceptionUtilities.UnexpectedValue(kind), }; // Remap diagnostic locations, if required. diagnostics = await RemapDiagnosticLocationsIfRequiredAsync(textDocument, diagnostics, cancellationToken).ConfigureAwait(false); #if DEBUG var diags = await diagnostics.ToDiagnosticsAsync(textDocument.Project, cancellationToken).ConfigureAwait(false); Debug.Assert(diags.Length == CompilationWithAnalyzers.GetEffectiveDiagnostics(diags, _compilationWithAnalyzers.Compilation).Count()); Debug.Assert(diagnostics.Length == diags.ConvertToLocalDiagnostics(textDocument, span).Count()); #endif return diagnostics; } private async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> GetAnalysisResultAsync(DocumentAnalysisScope analysisScope, CancellationToken cancellationToken) { RoslynDebug.Assert(_compilationWithAnalyzers != null); try { var resultAndTelemetry = await _diagnosticAnalyzerRunner.AnalyzeDocumentAsync(analysisScope, _compilationWithAnalyzers, _logPerformanceInfo, getTelemetryInfo: false, cancellationToken).ConfigureAwait(false); return resultAndTelemetry.AnalysisResult; } catch { _onAnalysisException?.Invoke(); throw; } } private async Task<ImmutableArray<DiagnosticData>> GetCompilerAnalyzerDiagnosticsAsync(DiagnosticAnalyzer analyzer, TextSpan? span, CancellationToken cancellationToken) { RoslynDebug.Assert(analyzer.IsCompilerAnalyzer()); RoslynDebug.Assert(_compilationWithAnalyzers != null); RoslynDebug.Assert(_compilationBasedAnalyzersInAnalysisScope.Contains(analyzer)); RoslynDebug.Assert(AnalysisScope.TextDocument is Document); var analysisScope = AnalysisScope.WithAnalyzers(ImmutableArray.Create(analyzer)).WithSpan(span); var analysisResult = await GetAnalysisResultAsync(analysisScope, cancellationToken).ConfigureAwait(false); if (!analysisResult.TryGetValue(analyzer, out var result)) { return ImmutableArray<DiagnosticData>.Empty; } return result.GetDocumentDiagnostics(analysisScope.TextDocument.Id, analysisScope.Kind); } private async Task<ImmutableArray<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzer analyzer, bool isCompilerAnalyzer, CancellationToken cancellationToken) { // PERF: // 1. Compute diagnostics for all analyzers with a single invocation into CompilationWithAnalyzers. // This is critical for better analyzer execution performance. // 2. Ensure that the compiler analyzer is treated specially and does not block on diagnostic computation // for rest of the analyzers. This is needed to ensure faster refresh for compiler diagnostics while typing. RoslynDebug.Assert(_compilationWithAnalyzers != null); RoslynDebug.Assert(_compilationBasedAnalyzersInAnalysisScope.Contains(analyzer)); if (isCompilerAnalyzer) { if (AnalysisScope.TextDocument is not Document) { return ImmutableArray<DiagnosticData>.Empty; } return await GetCompilerAnalyzerDiagnosticsAsync(analyzer, AnalysisScope.Span, cancellationToken).ConfigureAwait(false); } if (_lazySyntaxDiagnostics == null) { var analysisScope = AnalysisScope.WithAnalyzers(_compilationBasedAnalyzersInAnalysisScope); var syntaxDiagnostics = await GetAnalysisResultAsync(analysisScope, cancellationToken).ConfigureAwait(false); Interlocked.CompareExchange(ref _lazySyntaxDiagnostics, syntaxDiagnostics, null); } return _lazySyntaxDiagnostics.TryGetValue(analyzer, out var diagnosticAnalysisResult) ? diagnosticAnalysisResult.GetDocumentDiagnostics(AnalysisScope.TextDocument.Id, AnalysisScope.Kind) : ImmutableArray<DiagnosticData>.Empty; } private async Task<ImmutableArray<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzer analyzer, bool isCompilerAnalyzer, CancellationToken cancellationToken) { // PERF: // 1. Compute diagnostics for all analyzers with a single invocation into CompilationWithAnalyzers. // This is critical for better analyzer execution performance through re-use of bound node cache. // 2. Ensure that the compiler analyzer is treated specially and does not block on diagnostic computation // for rest of the analyzers. This is needed to ensure faster refresh for compiler diagnostics while typing. RoslynDebug.Assert(_compilationWithAnalyzers != null); var span = AnalysisScope.Span; var document = (Document)AnalysisScope.TextDocument; if (isCompilerAnalyzer) { #if DEBUG await VerifySpanBasedCompilerDiagnosticsAsync().ConfigureAwait(false); #endif var adjustedSpan = await GetAdjustedSpanForCompilerAnalyzerAsync().ConfigureAwait(false); return await GetCompilerAnalyzerDiagnosticsAsync(analyzer, adjustedSpan, cancellationToken).ConfigureAwait(false); } if (_lazySemanticDiagnostics == null) { var analysisScope = AnalysisScope.WithAnalyzers(_compilationBasedAnalyzersInAnalysisScope); var semanticDiagnostics = await GetAnalysisResultAsync(analysisScope, cancellationToken).ConfigureAwait(false); Interlocked.CompareExchange(ref _lazySemanticDiagnostics, semanticDiagnostics, null); } return _lazySemanticDiagnostics.TryGetValue(analyzer, out var diagnosticAnalysisResult) ? diagnosticAnalysisResult.GetDocumentDiagnostics(AnalysisScope.TextDocument.Id, AnalysisScope.Kind) : ImmutableArray<DiagnosticData>.Empty; async Task<TextSpan?> GetAdjustedSpanForCompilerAnalyzerAsync() { // This method is to workaround a bug (https://github.com/dotnet/roslyn/issues/1557) // once that bug is fixed, we should be able to use given span as it is. Debug.Assert(isCompilerAnalyzer); if (!span.HasValue) { return null; } var service = document.GetRequiredLanguageService<ISyntaxFactsService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var startNode = service.GetContainingMemberDeclaration(root, span.Value.Start); var endNode = service.GetContainingMemberDeclaration(root, span.Value.End); if (startNode == endNode) { // use full member span if (service.IsMethodLevelMember(startNode)) { return startNode.FullSpan; } // use span as it is return span; } var startSpan = service.IsMethodLevelMember(startNode) ? startNode.FullSpan : span.Value; var endSpan = service.IsMethodLevelMember(endNode) ? endNode.FullSpan : span.Value; return TextSpan.FromBounds(Math.Min(startSpan.Start, endSpan.Start), Math.Max(startSpan.End, endSpan.End)); } #if DEBUG async Task VerifySpanBasedCompilerDiagnosticsAsync() { if (!span.HasValue) { return; } // make sure what we got from range is same as what we got from whole diagnostics var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rangeDeclaractionDiagnostics = model.GetDeclarationDiagnostics(span.Value, cancellationToken).ToArray(); var rangeMethodBodyDiagnostics = model.GetMethodBodyDiagnostics(span.Value, cancellationToken).ToArray(); var rangeDiagnostics = rangeDeclaractionDiagnostics.Concat(rangeMethodBodyDiagnostics).Where(shouldInclude).ToArray(); var wholeDeclarationDiagnostics = model.GetDeclarationDiagnostics(cancellationToken: cancellationToken).ToArray(); var wholeMethodBodyDiagnostics = model.GetMethodBodyDiagnostics(cancellationToken: cancellationToken).ToArray(); var wholeDiagnostics = wholeDeclarationDiagnostics.Concat(wholeMethodBodyDiagnostics).Where(shouldInclude).ToArray(); if (!AnalyzerHelper.AreEquivalent(rangeDiagnostics, wholeDiagnostics)) { // otherwise, report non-fatal watson so that we can fix those cases FatalError.ReportAndCatch(new Exception("Bug in GetDiagnostics")); // make sure we hold onto these for debugging. GC.KeepAlive(rangeDeclaractionDiagnostics); GC.KeepAlive(rangeMethodBodyDiagnostics); GC.KeepAlive(rangeDiagnostics); GC.KeepAlive(wholeDeclarationDiagnostics); GC.KeepAlive(wholeMethodBodyDiagnostics); GC.KeepAlive(wholeDiagnostics); } return; static bool IsUnusedImportDiagnostic(Diagnostic d) { switch (d.Id) { case "CS8019": case "BC50000": case "BC50001": return true; default: return false; } } // Exclude unused import diagnostics since they are never reported when a span is passed. // (See CSharp/VisualBasicCompilation.GetDiagnosticsForMethodBodiesInTree.) bool shouldInclude(Diagnostic d) => span.Value.IntersectsWith(d.Location.SourceSpan) && !IsUnusedImportDiagnostic(d); } #endif } private static async Task<ImmutableArray<DiagnosticData>> RemapDiagnosticLocationsIfRequiredAsync( TextDocument textDocument, ImmutableArray<DiagnosticData> diagnostics, CancellationToken cancellationToken) { if (diagnostics.IsEmpty) { return diagnostics; } // Check if IWorkspaceVenusSpanMappingService is present for remapping. var diagnosticSpanMappingService = textDocument.Project.Solution.Workspace.Services.GetService<IWorkspaceVenusSpanMappingService>(); if (diagnosticSpanMappingService == null) { return diagnostics; } // Round tripping the diagnostics should ensure they get correctly remapped. using var _ = ArrayBuilder<DiagnosticData>.GetInstance(diagnostics.Length, out var builder); foreach (var diagnosticData in diagnostics) { var diagnostic = await diagnosticData.ToDiagnosticAsync(textDocument.Project, cancellationToken).ConfigureAwait(false); builder.Add(DiagnosticData.Create(diagnostic, textDocument)); } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more 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.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Executes analyzers on a document for computing local syntax/semantic/additional file diagnostics for a specific <see cref="DocumentAnalysisScope"/>. /// </summary> internal sealed class DocumentAnalysisExecutor { private readonly CompilationWithAnalyzers? _compilationWithAnalyzers; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; private readonly bool _logPerformanceInfo; private readonly Action? _onAnalysisException; private readonly ImmutableArray<DiagnosticAnalyzer> _compilationBasedAnalyzersInAnalysisScope; private ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? _lazySyntaxDiagnostics; private ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? _lazySemanticDiagnostics; public DocumentAnalysisExecutor( DocumentAnalysisScope analysisScope, CompilationWithAnalyzers? compilationWithAnalyzers, InProcOrRemoteHostAnalyzerRunner diagnosticAnalyzerRunner, bool logPerformanceInfo, Action? onAnalysisException = null) { AnalysisScope = analysisScope; _compilationWithAnalyzers = compilationWithAnalyzers; _diagnosticAnalyzerRunner = diagnosticAnalyzerRunner; _logPerformanceInfo = logPerformanceInfo; _onAnalysisException = onAnalysisException; var compilationBasedAnalyzers = compilationWithAnalyzers?.Analyzers.ToImmutableHashSet(); _compilationBasedAnalyzersInAnalysisScope = compilationBasedAnalyzers != null ? analysisScope.Analyzers.WhereAsArray(compilationBasedAnalyzers.Contains) : ImmutableArray<DiagnosticAnalyzer>.Empty; } public DocumentAnalysisScope AnalysisScope { get; } /// <summary> /// Return all local diagnostics (syntax, semantic) that belong to given document for the given analyzer by calculating them. /// </summary> public async Task<IEnumerable<DiagnosticData>> ComputeDiagnosticsAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) { Contract.ThrowIfFalse(AnalysisScope.Analyzers.Contains(analyzer)); var textDocument = AnalysisScope.TextDocument; var span = AnalysisScope.Span; var kind = AnalysisScope.Kind; var document = textDocument as Document; RoslynDebug.Assert(document != null || kind == AnalysisKind.Syntax, "We only support syntactic analysis for non-source documents"); var loadDiagnostic = await textDocument.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (analyzer == FileContentLoadAnalyzer.Instance) { return loadDiagnostic != null ? SpecializedCollections.SingletonEnumerable(DiagnosticData.Create(loadDiagnostic, textDocument)) : SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } if (loadDiagnostic != null) { return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } if (analyzer is DocumentDiagnosticAnalyzer documentAnalyzer) { if (document == null) { return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } var documentDiagnostics = await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync( documentAnalyzer, document, kind, _compilationWithAnalyzers?.Compilation, cancellationToken).ConfigureAwait(false); return documentDiagnostics.ConvertToLocalDiagnostics(document, span); } // quick optimization to reduce allocations. if (_compilationWithAnalyzers == null || !analyzer.SupportAnalysisKind(kind)) { if (kind == AnalysisKind.Syntax) { Logger.Log(FunctionId.Diagnostics_SyntaxDiagnostic, (r, d, a, k) => $"Driver: {r != null}, {d.Id}, {d.Project.Id}, {a}, {k}", _compilationWithAnalyzers, textDocument, analyzer, kind); } return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } // if project is not loaded successfully then, we disable semantic errors for compiler analyzers var isCompilerAnalyzer = analyzer.IsCompilerAnalyzer(); if (kind != AnalysisKind.Syntax && isCompilerAnalyzer) { var isEnabled = await textDocument.Project.HasSuccessfullyLoadedAsync(cancellationToken).ConfigureAwait(false); Logger.Log(FunctionId.Diagnostics_SemanticDiagnostic, (a, d, e) => $"{a}, ({d.Id}, {d.Project.Id}), Enabled:{e}", analyzer, textDocument, isEnabled); if (!isEnabled) { return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } } if (document == null && textDocument is not AdditionalDocument) { // We currently support document analysis only for source documents and additional documents. return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } var diagnostics = kind switch { AnalysisKind.Syntax => await GetSyntaxDiagnosticsAsync(analyzer, isCompilerAnalyzer, cancellationToken).ConfigureAwait(false), AnalysisKind.Semantic => await GetSemanticDiagnosticsAsync(analyzer, isCompilerAnalyzer, cancellationToken).ConfigureAwait(false), _ => throw ExceptionUtilities.UnexpectedValue(kind), }; // Remap diagnostic locations, if required. diagnostics = await RemapDiagnosticLocationsIfRequiredAsync(textDocument, diagnostics, cancellationToken).ConfigureAwait(false); #if DEBUG var diags = await diagnostics.ToDiagnosticsAsync(textDocument.Project, cancellationToken).ConfigureAwait(false); Debug.Assert(diags.Length == CompilationWithAnalyzers.GetEffectiveDiagnostics(diags, _compilationWithAnalyzers.Compilation).Count()); Debug.Assert(diagnostics.Length == diags.ConvertToLocalDiagnostics(textDocument, span).Count()); #endif return diagnostics; } private async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> GetAnalysisResultAsync(DocumentAnalysisScope analysisScope, CancellationToken cancellationToken) { RoslynDebug.Assert(_compilationWithAnalyzers != null); try { var resultAndTelemetry = await _diagnosticAnalyzerRunner.AnalyzeDocumentAsync(analysisScope, _compilationWithAnalyzers, _logPerformanceInfo, getTelemetryInfo: false, cancellationToken).ConfigureAwait(false); return resultAndTelemetry.AnalysisResult; } catch { _onAnalysisException?.Invoke(); throw; } } private async Task<ImmutableArray<DiagnosticData>> GetCompilerAnalyzerDiagnosticsAsync(DiagnosticAnalyzer analyzer, TextSpan? span, CancellationToken cancellationToken) { RoslynDebug.Assert(analyzer.IsCompilerAnalyzer()); RoslynDebug.Assert(_compilationWithAnalyzers != null); RoslynDebug.Assert(_compilationBasedAnalyzersInAnalysisScope.Contains(analyzer)); RoslynDebug.Assert(AnalysisScope.TextDocument is Document); var analysisScope = AnalysisScope.WithAnalyzers(ImmutableArray.Create(analyzer)).WithSpan(span); var analysisResult = await GetAnalysisResultAsync(analysisScope, cancellationToken).ConfigureAwait(false); if (!analysisResult.TryGetValue(analyzer, out var result)) { return ImmutableArray<DiagnosticData>.Empty; } return result.GetDocumentDiagnostics(analysisScope.TextDocument.Id, analysisScope.Kind); } private async Task<ImmutableArray<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzer analyzer, bool isCompilerAnalyzer, CancellationToken cancellationToken) { // PERF: // 1. Compute diagnostics for all analyzers with a single invocation into CompilationWithAnalyzers. // This is critical for better analyzer execution performance. // 2. Ensure that the compiler analyzer is treated specially and does not block on diagnostic computation // for rest of the analyzers. This is needed to ensure faster refresh for compiler diagnostics while typing. RoslynDebug.Assert(_compilationWithAnalyzers != null); RoslynDebug.Assert(_compilationBasedAnalyzersInAnalysisScope.Contains(analyzer)); if (isCompilerAnalyzer) { if (AnalysisScope.TextDocument is not Document) { return ImmutableArray<DiagnosticData>.Empty; } return await GetCompilerAnalyzerDiagnosticsAsync(analyzer, AnalysisScope.Span, cancellationToken).ConfigureAwait(false); } if (_lazySyntaxDiagnostics == null) { var analysisScope = AnalysisScope.WithAnalyzers(_compilationBasedAnalyzersInAnalysisScope); var syntaxDiagnostics = await GetAnalysisResultAsync(analysisScope, cancellationToken).ConfigureAwait(false); Interlocked.CompareExchange(ref _lazySyntaxDiagnostics, syntaxDiagnostics, null); } return _lazySyntaxDiagnostics.TryGetValue(analyzer, out var diagnosticAnalysisResult) ? diagnosticAnalysisResult.GetDocumentDiagnostics(AnalysisScope.TextDocument.Id, AnalysisScope.Kind) : ImmutableArray<DiagnosticData>.Empty; } private async Task<ImmutableArray<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzer analyzer, bool isCompilerAnalyzer, CancellationToken cancellationToken) { // PERF: // 1. Compute diagnostics for all analyzers with a single invocation into CompilationWithAnalyzers. // This is critical for better analyzer execution performance through re-use of bound node cache. // 2. Ensure that the compiler analyzer is treated specially and does not block on diagnostic computation // for rest of the analyzers. This is needed to ensure faster refresh for compiler diagnostics while typing. RoslynDebug.Assert(_compilationWithAnalyzers != null); var span = AnalysisScope.Span; var document = (Document)AnalysisScope.TextDocument; if (isCompilerAnalyzer) { #if DEBUG await VerifySpanBasedCompilerDiagnosticsAsync().ConfigureAwait(false); #endif var adjustedSpan = await GetAdjustedSpanForCompilerAnalyzerAsync().ConfigureAwait(false); return await GetCompilerAnalyzerDiagnosticsAsync(analyzer, adjustedSpan, cancellationToken).ConfigureAwait(false); } if (_lazySemanticDiagnostics == null) { var analysisScope = AnalysisScope.WithAnalyzers(_compilationBasedAnalyzersInAnalysisScope); var semanticDiagnostics = await GetAnalysisResultAsync(analysisScope, cancellationToken).ConfigureAwait(false); Interlocked.CompareExchange(ref _lazySemanticDiagnostics, semanticDiagnostics, null); } return _lazySemanticDiagnostics.TryGetValue(analyzer, out var diagnosticAnalysisResult) ? diagnosticAnalysisResult.GetDocumentDiagnostics(AnalysisScope.TextDocument.Id, AnalysisScope.Kind) : ImmutableArray<DiagnosticData>.Empty; async Task<TextSpan?> GetAdjustedSpanForCompilerAnalyzerAsync() { // This method is to workaround a bug (https://github.com/dotnet/roslyn/issues/1557) // once that bug is fixed, we should be able to use given span as it is. Debug.Assert(isCompilerAnalyzer); if (!span.HasValue) { return null; } var service = document.GetRequiredLanguageService<ISyntaxFactsService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var startNode = service.GetContainingMemberDeclaration(root, span.Value.Start); var endNode = service.GetContainingMemberDeclaration(root, span.Value.End); if (startNode == endNode) { // use full member span if (service.IsMethodLevelMember(startNode)) { return startNode.FullSpan; } // use span as it is return span; } var startSpan = service.IsMethodLevelMember(startNode) ? startNode.FullSpan : span.Value; var endSpan = service.IsMethodLevelMember(endNode) ? endNode.FullSpan : span.Value; return TextSpan.FromBounds(Math.Min(startSpan.Start, endSpan.Start), Math.Max(startSpan.End, endSpan.End)); } #if DEBUG async Task VerifySpanBasedCompilerDiagnosticsAsync() { if (!span.HasValue) { return; } // make sure what we got from range is same as what we got from whole diagnostics var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rangeDeclaractionDiagnostics = model.GetDeclarationDiagnostics(span.Value, cancellationToken).ToArray(); var rangeMethodBodyDiagnostics = model.GetMethodBodyDiagnostics(span.Value, cancellationToken).ToArray(); var rangeDiagnostics = rangeDeclaractionDiagnostics.Concat(rangeMethodBodyDiagnostics).Where(shouldInclude).ToArray(); var wholeDeclarationDiagnostics = model.GetDeclarationDiagnostics(cancellationToken: cancellationToken).ToArray(); var wholeMethodBodyDiagnostics = model.GetMethodBodyDiagnostics(cancellationToken: cancellationToken).ToArray(); var wholeDiagnostics = wholeDeclarationDiagnostics.Concat(wholeMethodBodyDiagnostics).Where(shouldInclude).ToArray(); if (!AnalyzerHelper.AreEquivalent(rangeDiagnostics, wholeDiagnostics)) { // otherwise, report non-fatal watson so that we can fix those cases FatalError.ReportAndCatch(new Exception("Bug in GetDiagnostics")); // make sure we hold onto these for debugging. GC.KeepAlive(rangeDeclaractionDiagnostics); GC.KeepAlive(rangeMethodBodyDiagnostics); GC.KeepAlive(rangeDiagnostics); GC.KeepAlive(wholeDeclarationDiagnostics); GC.KeepAlive(wholeMethodBodyDiagnostics); GC.KeepAlive(wholeDiagnostics); } return; static bool IsUnusedImportDiagnostic(Diagnostic d) { switch (d.Id) { case "CS8019": case "BC50000": case "BC50001": return true; default: return false; } } // Exclude unused import diagnostics since they are never reported when a span is passed. // (See CSharp/VisualBasicCompilation.GetDiagnosticsForMethodBodiesInTree.) bool shouldInclude(Diagnostic d) => span.Value.IntersectsWith(d.Location.SourceSpan) && !IsUnusedImportDiagnostic(d); } #endif } private static async Task<ImmutableArray<DiagnosticData>> RemapDiagnosticLocationsIfRequiredAsync( TextDocument textDocument, ImmutableArray<DiagnosticData> diagnostics, CancellationToken cancellationToken) { if (diagnostics.IsEmpty) { return diagnostics; } // Check if IWorkspaceVenusSpanMappingService is present for remapping. var diagnosticSpanMappingService = textDocument.Project.Solution.Workspace.Services.GetService<IWorkspaceVenusSpanMappingService>(); if (diagnosticSpanMappingService == null) { return diagnostics; } // Round tripping the diagnostics should ensure they get correctly remapped. using var _ = ArrayBuilder<DiagnosticData>.GetInstance(diagnostics.Length, out var builder); foreach (var diagnosticData in diagnostics) { var diagnostic = await diagnosticData.ToDiagnosticAsync(textDocument.Project, cancellationToken).ConfigureAwait(false); builder.Add(DiagnosticData.Create(diagnostic, textDocument)); } return builder.ToImmutable(); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/VisualBasic/Portable/Completion/CompletionProviders/OverrideCompletionProvider.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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(OverrideCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(CompletionListTagCompletionProvider))> <[Shared]> Friend Class OverrideCompletionProvider Inherits AbstractOverrideCompletionProvider Private _isFunction As Boolean Private _isSub As Boolean Private _isProperty As Boolean <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetSyntax(commonSyntaxToken As SyntaxToken) As SyntaxNode Dim token = CType(commonSyntaxToken, SyntaxToken) Dim propertyBlock = token.GetAncestor(Of PropertyBlockSyntax)() If propertyBlock IsNot Nothing Then Return propertyBlock End If Dim methodBlock = token.GetAncestor(Of MethodBlockBaseSyntax)() If methodBlock IsNot Nothing Then Return methodBlock End If Return token.GetAncestor(Of MethodStatementSyntax)() End Function Protected Overrides Function GetToken(completionItem As CompletionItem, syntaxTree As SyntaxTree, cancellationToken As CancellationToken) As SyntaxToken Dim tokenSpanEnd = MemberInsertionCompletionItem.GetTokenSpanEnd(completionItem) Return syntaxTree.FindTokenOnLeftOfPosition(tokenSpanEnd, cancellationToken) End Function Public Overrides Function FindStartingToken(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxToken Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) Return token.GetPreviousTokenIfTouchingWord(position) End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options) End Function Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.SpaceTriggerChar Public Overrides Function TryDetermineModifiers(startToken As SyntaxToken, text As SourceText, startLine As Integer, ByRef seenAccessibility As Accessibility, ByRef modifiers As DeclarationModifiers) As Boolean Dim token = CType(startToken, SyntaxToken) modifiers = New DeclarationModifiers() seenAccessibility = Accessibility.NotApplicable Dim overridesToken = New SyntaxToken() Dim isMustOverride = False Dim isNotOverridable = False Me._isSub = False Me._isFunction = False Me._isProperty = False Do While IsOnStartLine(token.SpanStart, text, startLine) Select Case token.Kind Case SyntaxKind.OverridesKeyword overridesToken = token Case SyntaxKind.MustOverrideKeyword isMustOverride = True Case SyntaxKind.NotOverridableKeyword isNotOverridable = True Case SyntaxKind.FunctionKeyword _isFunction = True Case SyntaxKind.PropertyKeyword _isProperty = True Case SyntaxKind.SubKeyword _isSub = True ' Filter on accessibility by keeping the first one that we see Case SyntaxKind.PublicKeyword If seenAccessibility = Accessibility.NotApplicable Then seenAccessibility = Accessibility.Public End If Case SyntaxKind.FriendKeyword If seenAccessibility = Accessibility.NotApplicable Then seenAccessibility = Accessibility.Internal End If ' If we see Friend AND Protected, assume Friend Protected If seenAccessibility = Accessibility.Protected Then seenAccessibility = Accessibility.ProtectedOrInternal End If Case SyntaxKind.ProtectedKeyword If seenAccessibility = Accessibility.NotApplicable Then seenAccessibility = Accessibility.Protected End If ' If we see Protected and Friend, assume Protected Friend If seenAccessibility = Accessibility.Internal Then seenAccessibility = Accessibility.ProtectedOrInternal End If Case Else ' If we see anything else, give up Return False End Select Dim previousToken = token.GetPreviousToken() ' Consume only modifiers on the same line If previousToken.Kind = SyntaxKind.None OrElse Not IsOnStartLine(previousToken.SpanStart, text, startLine) Then Exit Do End If token = previousToken Loop modifiers = New DeclarationModifiers(isAbstract:=isMustOverride, isOverride:=True, isSealed:=isNotOverridable) Return overridesToken.Kind = SyntaxKind.OverridesKeyword AndAlso IsOnStartLine(overridesToken.Parent.SpanStart, text, startLine) End Function Public Overrides Function TryDetermineReturnType(startToken As SyntaxToken, semanticModel As SemanticModel, cancellationToken As CancellationToken, ByRef returnType As ITypeSymbol, ByRef nextToken As SyntaxToken) As Boolean nextToken = startToken returnType = Nothing Return True End Function Public Overrides Function FilterOverrides(members As ImmutableArray(Of ISymbol), returnType As ITypeSymbol) As ImmutableArray(Of ISymbol) ' Start by removing Finalize(), which we never want to show. Dim finalizeMethod = members.OfType(Of IMethodSymbol)().Where(Function(x) x.Name = "Finalize" AndAlso OverridesObjectMethod(x)).SingleOrDefault() If finalizeMethod IsNot Nothing Then members = members.Remove(finalizeMethod) End If If Me._isFunction Then ' Function: look for non-void return types Dim filteredMembers = members.OfType(Of IMethodSymbol)().Where(Function(m) Not m.ReturnsVoid) If filteredMembers.Any Then Return ImmutableArray(Of ISymbol).CastUp(filteredMembers.ToImmutableArray()) End If ElseIf Me._isProperty Then ' Property: return properties Dim filteredMembers = members.Where(Function(m) m.Kind = SymbolKind.Property) If filteredMembers.Any Then Return filteredMembers.ToImmutableArray() End If ElseIf Me._isSub Then ' Sub: look for void return types Dim filteredMembers = members.OfType(Of IMethodSymbol)().Where(Function(m) m.ReturnsVoid) If filteredMembers.Any Then Return ImmutableArray(Of ISymbol).CastUp(filteredMembers.ToImmutableArray()) End If End If Return members.WhereAsArray(Function(m) Not m.IsKind(SymbolKind.Event)) End Function Private Shared Function OverridesObjectMethod(method As IMethodSymbol) As Boolean Dim overriddenMember = method Do While overriddenMember.OverriddenMethod IsNot Nothing overriddenMember = overriddenMember.OverriddenMethod Loop If overriddenMember.ContainingType.SpecialType = SpecialType.System_Object Then Return True End If Return False End Function Protected Overrides Function GetTargetCaretPosition(caretTarget As SyntaxNode) As Integer Dim node = DirectCast(caretTarget, SyntaxNode) ' MustOverride Sub | MustOverride Function: move to end of line Dim methodStatement = TryCast(node, MethodStatementSyntax) If methodStatement IsNot Nothing Then Return methodStatement.GetLocation().SourceSpan.End End If Dim methodBlock = TryCast(node, MethodBlockBaseSyntax) If methodBlock IsNot Nothing Then Dim lastStatement = methodBlock.Statements.LastOrDefault() If lastStatement IsNot Nothing Then Return lastStatement.GetLocation().SourceSpan.End End If End If Dim propertyBlock = TryCast(node, PropertyBlockSyntax) If propertyBlock IsNot Nothing Then Dim firstAccessor = propertyBlock.Accessors.FirstOrDefault() If firstAccessor IsNot Nothing Then Dim lastAccessorStatement = firstAccessor.Statements.LastOrDefault() If lastAccessorStatement IsNot Nothing Then Return lastAccessorStatement.GetLocation().SourceSpan.End End If End If End If Return -1 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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(OverrideCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(CompletionListTagCompletionProvider))> <[Shared]> Friend Class OverrideCompletionProvider Inherits AbstractOverrideCompletionProvider Private _isFunction As Boolean Private _isSub As Boolean Private _isProperty As Boolean <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetSyntax(commonSyntaxToken As SyntaxToken) As SyntaxNode Dim token = CType(commonSyntaxToken, SyntaxToken) Dim propertyBlock = token.GetAncestor(Of PropertyBlockSyntax)() If propertyBlock IsNot Nothing Then Return propertyBlock End If Dim methodBlock = token.GetAncestor(Of MethodBlockBaseSyntax)() If methodBlock IsNot Nothing Then Return methodBlock End If Return token.GetAncestor(Of MethodStatementSyntax)() End Function Protected Overrides Function GetToken(completionItem As CompletionItem, syntaxTree As SyntaxTree, cancellationToken As CancellationToken) As SyntaxToken Dim tokenSpanEnd = MemberInsertionCompletionItem.GetTokenSpanEnd(completionItem) Return syntaxTree.FindTokenOnLeftOfPosition(tokenSpanEnd, cancellationToken) End Function Public Overrides Function FindStartingToken(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxToken Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) Return token.GetPreviousTokenIfTouchingWord(position) End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options) End Function Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.SpaceTriggerChar Public Overrides Function TryDetermineModifiers(startToken As SyntaxToken, text As SourceText, startLine As Integer, ByRef seenAccessibility As Accessibility, ByRef modifiers As DeclarationModifiers) As Boolean Dim token = CType(startToken, SyntaxToken) modifiers = New DeclarationModifiers() seenAccessibility = Accessibility.NotApplicable Dim overridesToken = New SyntaxToken() Dim isMustOverride = False Dim isNotOverridable = False Me._isSub = False Me._isFunction = False Me._isProperty = False Do While IsOnStartLine(token.SpanStart, text, startLine) Select Case token.Kind Case SyntaxKind.OverridesKeyword overridesToken = token Case SyntaxKind.MustOverrideKeyword isMustOverride = True Case SyntaxKind.NotOverridableKeyword isNotOverridable = True Case SyntaxKind.FunctionKeyword _isFunction = True Case SyntaxKind.PropertyKeyword _isProperty = True Case SyntaxKind.SubKeyword _isSub = True ' Filter on accessibility by keeping the first one that we see Case SyntaxKind.PublicKeyword If seenAccessibility = Accessibility.NotApplicable Then seenAccessibility = Accessibility.Public End If Case SyntaxKind.FriendKeyword If seenAccessibility = Accessibility.NotApplicable Then seenAccessibility = Accessibility.Internal End If ' If we see Friend AND Protected, assume Friend Protected If seenAccessibility = Accessibility.Protected Then seenAccessibility = Accessibility.ProtectedOrInternal End If Case SyntaxKind.ProtectedKeyword If seenAccessibility = Accessibility.NotApplicable Then seenAccessibility = Accessibility.Protected End If ' If we see Protected and Friend, assume Protected Friend If seenAccessibility = Accessibility.Internal Then seenAccessibility = Accessibility.ProtectedOrInternal End If Case Else ' If we see anything else, give up Return False End Select Dim previousToken = token.GetPreviousToken() ' Consume only modifiers on the same line If previousToken.Kind = SyntaxKind.None OrElse Not IsOnStartLine(previousToken.SpanStart, text, startLine) Then Exit Do End If token = previousToken Loop modifiers = New DeclarationModifiers(isAbstract:=isMustOverride, isOverride:=True, isSealed:=isNotOverridable) Return overridesToken.Kind = SyntaxKind.OverridesKeyword AndAlso IsOnStartLine(overridesToken.Parent.SpanStart, text, startLine) End Function Public Overrides Function TryDetermineReturnType(startToken As SyntaxToken, semanticModel As SemanticModel, cancellationToken As CancellationToken, ByRef returnType As ITypeSymbol, ByRef nextToken As SyntaxToken) As Boolean nextToken = startToken returnType = Nothing Return True End Function Public Overrides Function FilterOverrides(members As ImmutableArray(Of ISymbol), returnType As ITypeSymbol) As ImmutableArray(Of ISymbol) ' Start by removing Finalize(), which we never want to show. Dim finalizeMethod = members.OfType(Of IMethodSymbol)().Where(Function(x) x.Name = "Finalize" AndAlso OverridesObjectMethod(x)).SingleOrDefault() If finalizeMethod IsNot Nothing Then members = members.Remove(finalizeMethod) End If If Me._isFunction Then ' Function: look for non-void return types Dim filteredMembers = members.OfType(Of IMethodSymbol)().Where(Function(m) Not m.ReturnsVoid) If filteredMembers.Any Then Return ImmutableArray(Of ISymbol).CastUp(filteredMembers.ToImmutableArray()) End If ElseIf Me._isProperty Then ' Property: return properties Dim filteredMembers = members.Where(Function(m) m.Kind = SymbolKind.Property) If filteredMembers.Any Then Return filteredMembers.ToImmutableArray() End If ElseIf Me._isSub Then ' Sub: look for void return types Dim filteredMembers = members.OfType(Of IMethodSymbol)().Where(Function(m) m.ReturnsVoid) If filteredMembers.Any Then Return ImmutableArray(Of ISymbol).CastUp(filteredMembers.ToImmutableArray()) End If End If Return members.WhereAsArray(Function(m) Not m.IsKind(SymbolKind.Event)) End Function Private Shared Function OverridesObjectMethod(method As IMethodSymbol) As Boolean Dim overriddenMember = method Do While overriddenMember.OverriddenMethod IsNot Nothing overriddenMember = overriddenMember.OverriddenMethod Loop If overriddenMember.ContainingType.SpecialType = SpecialType.System_Object Then Return True End If Return False End Function Protected Overrides Function GetTargetCaretPosition(caretTarget As SyntaxNode) As Integer Dim node = DirectCast(caretTarget, SyntaxNode) ' MustOverride Sub | MustOverride Function: move to end of line Dim methodStatement = TryCast(node, MethodStatementSyntax) If methodStatement IsNot Nothing Then Return methodStatement.GetLocation().SourceSpan.End End If Dim methodBlock = TryCast(node, MethodBlockBaseSyntax) If methodBlock IsNot Nothing Then Dim lastStatement = methodBlock.Statements.LastOrDefault() If lastStatement IsNot Nothing Then Return lastStatement.GetLocation().SourceSpan.End End If End If Dim propertyBlock = TryCast(node, PropertyBlockSyntax) If propertyBlock IsNot Nothing Then Dim firstAccessor = propertyBlock.Accessors.FirstOrDefault() If firstAccessor IsNot Nothing Then Dim lastAccessorStatement = firstAccessor.Statements.LastOrDefault() If lastAccessorStatement IsNot Nothing Then Return lastAccessorStatement.GetLocation().SourceSpan.End End If End If End If Return -1 End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Test/Progression/ProgressionTestHelpers.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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.CSharp.Progression Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression Imports <xmlns="http://schemas.microsoft.com/vs/2009/dgml"> Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Friend Module ProgressionTestHelpers <Extension> Public Function ToSimplifiedXDocument(graph As Graph) As XDocument Dim document = XDocument.Parse(graph.ToXml(graphNodeIdAliasThreshold:=1000000)) document.Root.<Categories>.Remove() document.Root.<Properties>.Remove() document.Root.<QualifiedNames>.Remove() For Each node In document.Descendants(XName.Get("Node", "http://schemas.microsoft.com/vs/2009/dgml")) Dim attribute = node.Attribute("SourceLocation") If attribute IsNot Nothing Then attribute.Remove() End If Next Return document End Function Public Sub AssertSimplifiedGraphIs(graph As Graph, xml As XElement) Dim graphXml = graph.ToSimplifiedXDocument() If Not XNode.DeepEquals(graphXml.Root, xml) Then ' They aren't equal, so therefore the text representations definitely aren't equal. ' We'll Assert.Equal those, so that way xunit will show nice before/after text 'Assert.Equal(xml.ToString(), graphXml.ToString()) ' In an attempt to diagnose some flaky tests, the whole contents of both objects will be output Throw New Exception($"Graph XML was not equal, check for out-of-order elements. Expected: {xml.ToString()} Actual: {graphXml.ToString()} ") End If End Sub 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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.CSharp.Progression Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression Imports <xmlns="http://schemas.microsoft.com/vs/2009/dgml"> Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Friend Module ProgressionTestHelpers <Extension> Public Function ToSimplifiedXDocument(graph As Graph) As XDocument Dim document = XDocument.Parse(graph.ToXml(graphNodeIdAliasThreshold:=1000000)) document.Root.<Categories>.Remove() document.Root.<Properties>.Remove() document.Root.<QualifiedNames>.Remove() For Each node In document.Descendants(XName.Get("Node", "http://schemas.microsoft.com/vs/2009/dgml")) Dim attribute = node.Attribute("SourceLocation") If attribute IsNot Nothing Then attribute.Remove() End If Next Return document End Function Public Sub AssertSimplifiedGraphIs(graph As Graph, xml As XElement) Dim graphXml = graph.ToSimplifiedXDocument() If Not XNode.DeepEquals(graphXml.Root, xml) Then ' They aren't equal, so therefore the text representations definitely aren't equal. ' We'll Assert.Equal those, so that way xunit will show nice before/after text 'Assert.Equal(xml.ToString(), graphXml.ToString()) ' In an attempt to diagnose some flaky tests, the whole contents of both objects will be output Throw New Exception($"Graph XML was not equal, check for out-of-order elements. Expected: {xml.ToString()} Actual: {graphXml.ToString()} ") End If End Sub End Module End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Workspaces/Core/Portable/Shared/Utilities/StreamingProgressTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// </summary> internal sealed class StreamingProgressTracker : IStreamingProgressTracker { private int _completedItems; private int _totalItems; private readonly Func<int, int, CancellationToken, ValueTask>? _updateAction; public StreamingProgressTracker(Func<int, int, CancellationToken, ValueTask>? updateAction = null) => _updateAction = updateAction; public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) { Interlocked.Add(ref _totalItems, count); return UpdateAsync(cancellationToken); } public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) { Interlocked.Increment(ref _completedItems); return UpdateAsync(cancellationToken); } private ValueTask UpdateAsync(CancellationToken cancellationToken) { if (_updateAction == null) { return default; } return _updateAction(_completedItems, _totalItems, 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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// </summary> internal sealed class StreamingProgressTracker : IStreamingProgressTracker { private int _completedItems; private int _totalItems; private readonly Func<int, int, CancellationToken, ValueTask>? _updateAction; public StreamingProgressTracker(Func<int, int, CancellationToken, ValueTask>? updateAction = null) => _updateAction = updateAction; public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) { Interlocked.Add(ref _totalItems, count); return UpdateAsync(cancellationToken); } public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) { Interlocked.Increment(ref _completedItems); return UpdateAsync(cancellationToken); } private ValueTask UpdateAsync(CancellationToken cancellationToken) { if (_updateAction == null) { return default; } return _updateAction(_completedItems, _totalItems, cancellationToken); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioNavigationOptions.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.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal static class VisualStudioNavigationOptions { public static readonly PerLanguageOption2<bool> NavigateToObjectBrowser = new(nameof(VisualStudioNavigationOptions), nameof(NavigateToObjectBrowser), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.NavigateToObjectBrowser")); } }
// Licensed to the .NET Foundation under one or more 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.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal static class VisualStudioNavigationOptions { public static readonly PerLanguageOption2<bool> NavigateToObjectBrowser = new(nameof(VisualStudioNavigationOptions), nameof(NavigateToObjectBrowser), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.NavigateToObjectBrowser")); } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller_NavigationKeys.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.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal bool TryHandleUpKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectPreviousItem()); } internal bool TryHandleDownKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectNextItem()); } private bool ChangeSelection(Action computationAction) { AssertIsForeground(); if (!IsSessionActive) { // No computation running, so just let the editor handle this. return false; } // If we haven't started our editor session yet, just abort. // The user hasn't seen a SigHelp presentation yet, so they're // probably not trying to change the currently visible overload. if (!sessionOpt.PresenterSession.EditorSessionIsActive) { DismissSessionIfActive(); return false; } // If we've finished computing the items then use the navigation commands to change the // selected item. Otherwise, the user was just typing and is now moving through the // file. In this case stop everything we're doing. var model = sessionOpt.InitialUnfilteredModel != null ? WaitForController() : null; // Check if completion is still active. Then update the computation appropriately. // // Also, if we only computed one item, then the user doesn't want to select anything // else. Just stop and let the editor handle the nav character. if (model != null && model.Items.Count > 1) { computationAction(); return true; } else { // Dismiss ourselves and actually allow the editor to navigate. DismissSessionIfActive(); 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; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal bool TryHandleUpKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectPreviousItem()); } internal bool TryHandleDownKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectNextItem()); } private bool ChangeSelection(Action computationAction) { AssertIsForeground(); if (!IsSessionActive) { // No computation running, so just let the editor handle this. return false; } // If we haven't started our editor session yet, just abort. // The user hasn't seen a SigHelp presentation yet, so they're // probably not trying to change the currently visible overload. if (!sessionOpt.PresenterSession.EditorSessionIsActive) { DismissSessionIfActive(); return false; } // If we've finished computing the items then use the navigation commands to change the // selected item. Otherwise, the user was just typing and is now moving through the // file. In this case stop everything we're doing. var model = sessionOpt.InitialUnfilteredModel != null ? WaitForController() : null; // Check if completion is still active. Then update the computation appropriately. // // Also, if we only computed one item, then the user doesn't want to select anything // else. Just stop and let the editor handle the nav character. if (model != null && model.Items.Count > 1) { computationAction(); return true; } else { // Dismiss ourselves and actually allow the editor to navigate. DismissSessionIfActive(); return false; } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/Portable/Text/LinePositionSpan.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.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Immutable span represented by a pair of line number and index within the line. /// </summary> [DataContract] public readonly struct LinePositionSpan : IEquatable<LinePositionSpan> { [DataMember(Order = 0)] private readonly LinePosition _start; [DataMember(Order = 1)] private readonly LinePosition _end; /// <summary> /// Creates <see cref="LinePositionSpan"/>. /// </summary> /// <param name="start">Start position.</param> /// <param name="end">End position.</param> /// <exception cref="ArgumentException"><paramref name="end"/> precedes <paramref name="start"/>.</exception> public LinePositionSpan(LinePosition start, LinePosition end) { if (end < start) { throw new ArgumentException(CodeAnalysisResources.EndMustNotBeLessThanStart, nameof(end)); } _start = start; _end = end; } /// <summary> /// Gets the start position of the span. /// </summary> public LinePosition Start { get { return _start; } } /// <summary> /// Gets the end position of the span. /// </summary> public LinePosition End { get { return _end; } } public override bool Equals(object? obj) { return obj is LinePositionSpan && Equals((LinePositionSpan)obj); } public bool Equals(LinePositionSpan other) { return _start.Equals(other._start) && _end.Equals(other._end); } public override int GetHashCode() { return Hash.Combine(_start.GetHashCode(), _end.GetHashCode()); } public static bool operator ==(LinePositionSpan left, LinePositionSpan right) { return left.Equals(right); } public static bool operator !=(LinePositionSpan left, LinePositionSpan right) { return !left.Equals(right); } /// <summary> /// Provides a string representation for <see cref="LinePositionSpan"/>. /// </summary> /// <example>(0,0)-(5,6)</example> public override string ToString() { return string.Format("({0})-({1})", _start, _end); } } }
// Licensed to the .NET Foundation under one or more 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.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Immutable span represented by a pair of line number and index within the line. /// </summary> [DataContract] public readonly struct LinePositionSpan : IEquatable<LinePositionSpan> { [DataMember(Order = 0)] private readonly LinePosition _start; [DataMember(Order = 1)] private readonly LinePosition _end; /// <summary> /// Creates <see cref="LinePositionSpan"/>. /// </summary> /// <param name="start">Start position.</param> /// <param name="end">End position.</param> /// <exception cref="ArgumentException"><paramref name="end"/> precedes <paramref name="start"/>.</exception> public LinePositionSpan(LinePosition start, LinePosition end) { if (end < start) { throw new ArgumentException(CodeAnalysisResources.EndMustNotBeLessThanStart, nameof(end)); } _start = start; _end = end; } /// <summary> /// Gets the start position of the span. /// </summary> public LinePosition Start { get { return _start; } } /// <summary> /// Gets the end position of the span. /// </summary> public LinePosition End { get { return _end; } } public override bool Equals(object? obj) { return obj is LinePositionSpan && Equals((LinePositionSpan)obj); } public bool Equals(LinePositionSpan other) { return _start.Equals(other._start) && _end.Equals(other._end); } public override int GetHashCode() { return Hash.Combine(_start.GetHashCode(), _end.GetHashCode()); } public static bool operator ==(LinePositionSpan left, LinePositionSpan right) { return left.Equals(right); } public static bool operator !=(LinePositionSpan left, LinePositionSpan right) { return !left.Equals(right); } /// <summary> /// Provides a string representation for <see cref="LinePositionSpan"/>. /// </summary> /// <example>(0,0)-(5,6)</example> public override string ToString() { return string.Format("({0})-({1})", _start, _end); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/VisualBasic/Portable/Syntax/InternalSyntax/StructuredTriviaSyntax.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 Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend MustInherit Class StructuredTriviaSyntax Friend Sub New(reader As ObjectReader) MyBase.New(reader) Initialize() End Sub Friend Sub New(ByVal kind As SyntaxKind) MyBase.New(kind) Initialize() End Sub Friend Sub New(ByVal kind As SyntaxKind, context As ISyntaxFactoryContext) MyBase.New(kind) Initialize() Me.SetFactoryContext(context) End Sub Friend Sub New(ByVal kind As SyntaxKind, ByVal errors As DiagnosticInfo(), ByVal annotations As SyntaxAnnotation()) MyBase.New(kind, errors, annotations) Initialize() End Sub Private Sub Initialize() Me.SetFlags(NodeFlags.ContainsStructuredTrivia) If Kind = SyntaxKind.SkippedTokensTrivia Then Me.SetFlags(NodeFlags.ContainsSkippedText) 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 Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend MustInherit Class StructuredTriviaSyntax Friend Sub New(reader As ObjectReader) MyBase.New(reader) Initialize() End Sub Friend Sub New(ByVal kind As SyntaxKind) MyBase.New(kind) Initialize() End Sub Friend Sub New(ByVal kind As SyntaxKind, context As ISyntaxFactoryContext) MyBase.New(kind) Initialize() Me.SetFactoryContext(context) End Sub Friend Sub New(ByVal kind As SyntaxKind, ByVal errors As DiagnosticInfo(), ByVal annotations As SyntaxAnnotation()) MyBase.New(kind, errors, annotations) Initialize() End Sub Private Sub Initialize() Me.SetFlags(NodeFlags.ContainsStructuredTrivia) If Kind = SyntaxKind.SkippedTokensTrivia Then Me.SetFlags(NodeFlags.ContainsSkippedText) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./docs/wiki/Getting-Started-VB-Syntax-Analysis.md
## Prerequisites * [Visual Studio 2015](https://www.visualstudio.com/downloads) * [.NET Compiler Platform SDK](https://aka.ms/roslynsdktemplates) ## Introduction Today, the Visual Basic and C# compilers are black boxes - text goes in and bytes come out - with no transparency into the intermediate phases of the compilation pipeline. With the **.NET Compiler Platform** (formerly known as "Roslyn"), tools and developers can leverage the exact same data structures and algorithms the compiler uses to analyze and understand code with confidence that that information is accurate and complete. In this walkthrough we'll explore the **Syntax API**. The **Syntax API** exposes the parsers, the syntax trees themselves, and utilities for reasoning about and constructing them. ## Understanding Syntax Trees The **Syntax API** exposes the syntax trees the compilers use to understand Visual Basic and C# programs. They are produced by the same parser that runs when a project is built or a developer hits F5. The syntax trees have full-fidelity with the language; every bit of information in a code file is represented in the tree, including things like comments or whitespace. Writing a syntax tree to text will reproduce the exact original text that was parsed. The syntax trees are also immutable; once created a syntax tree can never be changed. This means consumers of the trees can analyze the trees on multiple threads, without locks or other concurrency measures, with the security that the data will never change. The four primary building blocks of syntax trees are: * The **SyntaxTree** class, an instance of which represents an entire parse tree. **SyntaxTree** is an abstract class which has language-specific derivatives. To parse syntax in a particular language you will need to use the parse methods on the **VisualBasicSyntaxTree** (or **CSharpSyntaxTree**) class. * The **SyntaxNode** class, instances of which represent syntactic constructs such as declarations, statements, clauses, and expressions. * The **SyntaxToken** structure, which represents an individual keyword, identifier, operator, or punctuation. * And lastly the **SyntaxTrivia** structure, which represents syntactically insignificant bits of information such as the whitespace between tokens, preprocessing directives, and comments. **SyntaxNodes** are composed hierarchically to form a tree that completely represents everything in a fragment of Visual Basic or C# code. For example, were you to examine the following Visual Basic source file using the Syntax Visualizer (In Visual Studio, choose **View -> Other Windows -> Syntax Visualizer**) it tree view would look like this: **SyntaxNode**: Blue | **SyntaxToken**: Green | **SyntaxTrivia**: Red ![Visual Basic Code File](images/walkthrough-vb-syntax-figure1.png) By navigating this tree structure you can find any statement, expression, token, or bit of whitespace in a code file! ## Traversing Trees ### Manual Traversal The following steps use **Edit and Continue** to demonstrate how to parse VB source text and find a parameter declaration contained in the source. #### Example - Manually traversing the tree 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project. * In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog. * Under **Visual Basic -> Extensibility**, choose **Stand-Alone Code Analysis Tool**. * Name your project "**GettingStartedVB**" and click OK. 2) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` * Some readers may run with **Option Strict** turned **On** by default at the project level. Turning **Option Strict** **Off** in this walkthrough simplifies many of the examples by removing much of the casting required. 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Move your cursor to the line containing the **End Sub** of your **Main** method and set a breakpoint there. * In Visual Studio, choose **Debug -> Toggle Breakpoint**. 5) Run the program. * In Visual Studio, choose **Debug -> Start Debugging**. 6) Inspect the root variable in the debugger by hovering over it and expanding the datatip. * Note that its **Imports** property is a collection with four elements; one for each Import statement in the parsed text. * Note that the **KindText** of the root node is **CompilationUnit**. * Note that the **Members** collection of the **CompilationUnitSyntax** node has one element. 7) Insert the following statement at the end of the Main method to store the first member of the root **CompilationUnitSyntax** variable into a new variable: ```VB.NET Dim firstMember = root.Members(0) ``` 8) Set this statement as the next statement to be executed and execute it. * Right-click this line and choose **Set Next Statement**. * In Visual Studio, choose **Debug -> Step Over**, to execute this statement and initialize the new variable. * You will need to repeat this process for each of the following steps as we introduce new variables and inspect them with the debugger. 9) Hover over the **firstMember** variable and expand the datatips to inspect it. * Note that its **KindText** is **NamespaceBlock**. * Note that its run-time type is actually **NamespaceBlockSyntax**. 10) Cast this node to **NamespaceBlockSyntax** and store it in a new variable: ```VB.NET Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember ``` 11) Execute this statement and examine the **helloWorldDeclaration** variable. * Note that like the **CompilationUnitSyntax**, **NamespaceBlockSyntax** also has a **Members** collection. 12) Examine the **Members** collection. * Note that it contains a single member. Examine it. * Note that its **KindText** is **ModuleBlock.** * Note that its run-time type is **ModuleBlockSyntax**. 13) Cast this node to **ModuleBlockSyntax** and store it in a new variable: ```VB.NET Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) ``` 14) Execute this statement. 15) Locate the **Main** declaration in the **programDeclaration.Members** collection and store it in a new variable: ```VB.NET Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) ``` 16) Execute this statement and examine the members of the **MethodBlockSyntax** object. * Examine the **BlockStatement** property. * Note the **AsClause**, and **Identifier** properties. * Note the **ParameterList** property; examine it. * Note that it contains both the open and close parentheses of the parameter list in addition to the list of parameters themselves. * Note that the parameters are stored as a **SeparatedSyntaxList**(**Of** **ParameterSyntax**). * Note the **Statements** property. 17) Store the first parameter of the **Main** declaration in a variable. ```VB.NET Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) ``` 18) Execute this statement and examine the **argsParameter** variable. * Examine the **Identifier** property; note that it is of type **ModifiedIdentifierSyntax**. This type represents a normal identifier with an optional nullable modifier (**x?**) and/or array rank specifier (**arr(,)**). * Note that a **ModifiedIdentifierSyntax** has an **Identifier** property of the structure type **SyntaxToken**. * Examine the properties of the **Identifier** **SyntaxToken**; note that the text of the identifier can be found in the **ValueText** property. 19) Stop the program. * In Visual Studio, choose **Debug -> Stop Debugging**. 20) Your program should look like this now: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim firstMember = root.Members(0) Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) End Sub End Module ``` ### Query Methods In addition to traversing trees using the properties of the **SyntaxNode** derived classes you can also explore the syntax tree using the query methods defined on **SyntaxNode**. These methods should be immediately familiar to anyone familiar with XPath. You can use these methods with LINQ to quickly find things in a tree. #### Example - Using query methods 1) Using IntelliSense, examine the members of the **SyntaxNode** class through the root variable. * Note query methods such as **DescendantNodes**, **AncestorsAndSelf**, and **ChildNodes**. 2) Add the following statements to the end of the **Main** method. The first statement uses a LINQ expression and the **DescendantNodes** method to locate the same parameter as in the previous example: ```VB.NET Dim firstParameters = From methodStatement In root.DescendantNodes(). OfType(Of Syntax.MethodStatementSyntax)() Where methodStatement.Identifier.ValueText = "Main" Select methodStatement.ParameterList.Parameters.First() Dim argsParameter2 = firstParameters.First() ``` 3) Start debugging the program. 4) Open the Immediate Window. * In Visual Studio, choose **Debug -> Windows -> Immediate**. 5) Using the Immediate window, type the expression **? argsParameter Is argsParameter2** and press enter to evaluate it. * Note that the LINQ expression found the same parameter as manually navigating the tree. 6) Stop the program. ### SyntaxWalkers Often you'll want to find all nodes of a specific type in a syntax tree, for example, every property declaration in a file. By extending the **VisualBasicSyntaxWalker** class and overriding the **VisitPropertyStatement** method, you can process every property declaration in a syntax tree without knowing its structure beforehand. **VisualBasicSyntaxWalker** is a specific kind of **SyntaxVisitor** which recursively visits a node and each of its children. #### Example - Implementing a VisualBasicSyntaxWalker This example shows how to implement a **VisualBasicSyntaxWalker** which examines an entire syntax tree and collects any **Imports** statements it finds which aren't importing a **System** namespace. 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project; name it "**ImportsCollectorVB**". 3) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Note that this source text contains a long list of **Imports** statements. 5) Add a new class file to the project. * In Visual Studio, choose **Project -> Add Class...** * In the "Add New Item" dialog type **ImportsCollector.vb** as the filename. 6) Enter the following lines at the top of your **ImportsCollector.vb** file: ```VB.NET Option Strict Off ``` 7) Make the new **ImportsCollector** class in this file extend the **VisualBasicSyntaxWalker** class: ```VB.NET Public Class ImportsCollector Inherits VisualBasicSyntaxWalker ``` 8) Declare a public read-only field in the **ImportsCollector** class; we'll use this variable to store the **ImportsStatementSyntax** nodes we find: ```VB.NET Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() ``` 9) Override the **VisitSimpleImportsClause** method: ```VB.NET Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) End Sub ``` 10) Using IntelliSense, examine the **SimpleImportsClauseSyntax** class through the **node** parameter of this method. * Note the **Name** property of type **NameSyntax**; this stores the name of the namespace being imported. 11) Replace the code in the **VisitSimpleImportsClause** method with the following to conditionally add the found **node** to the **[Imports]** collection if **Name** doesn't refer to the **System** namespace or any of its descendant namespaces: ```VB.NET If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) ``` 12) The **ImportsCollector.vb** file should now look like this: ```VB.NET Option Strict Off Public Class ImportsCollector Inherits VisualBasicSyntaxWalker Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) End Sub End Class ``` 13) Return to the **Module1.vb** file. 14) Add the following code to the end of the **Main** method to create an instance of the **ImportsCollector**, use that instance to visit the root of the parsed tree, and iterate over the **ImportsStatementSyntax** nodes collected and print their names to the **Console**: ```VB.NET Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next ``` 15) Your **Module1.vb** file should now look like this: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next End Sub End Module ``` 16) Press **Ctrl+F5** to run the program without debugging it. You should see the following output: ``` Imports Microsoft.VisualBasic Imports Microsoft.Win32 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Press any key to continue . . . ``` 17) Observe that the walker has located all four non-**System** namespace **Imports** statements. 18) Congratulations! You've just used the **Syntax API** to locate specific kinds of VB statements and declarations in VB source code.
## Prerequisites * [Visual Studio 2015](https://www.visualstudio.com/downloads) * [.NET Compiler Platform SDK](https://aka.ms/roslynsdktemplates) ## Introduction Today, the Visual Basic and C# compilers are black boxes - text goes in and bytes come out - with no transparency into the intermediate phases of the compilation pipeline. With the **.NET Compiler Platform** (formerly known as "Roslyn"), tools and developers can leverage the exact same data structures and algorithms the compiler uses to analyze and understand code with confidence that that information is accurate and complete. In this walkthrough we'll explore the **Syntax API**. The **Syntax API** exposes the parsers, the syntax trees themselves, and utilities for reasoning about and constructing them. ## Understanding Syntax Trees The **Syntax API** exposes the syntax trees the compilers use to understand Visual Basic and C# programs. They are produced by the same parser that runs when a project is built or a developer hits F5. The syntax trees have full-fidelity with the language; every bit of information in a code file is represented in the tree, including things like comments or whitespace. Writing a syntax tree to text will reproduce the exact original text that was parsed. The syntax trees are also immutable; once created a syntax tree can never be changed. This means consumers of the trees can analyze the trees on multiple threads, without locks or other concurrency measures, with the security that the data will never change. The four primary building blocks of syntax trees are: * The **SyntaxTree** class, an instance of which represents an entire parse tree. **SyntaxTree** is an abstract class which has language-specific derivatives. To parse syntax in a particular language you will need to use the parse methods on the **VisualBasicSyntaxTree** (or **CSharpSyntaxTree**) class. * The **SyntaxNode** class, instances of which represent syntactic constructs such as declarations, statements, clauses, and expressions. * The **SyntaxToken** structure, which represents an individual keyword, identifier, operator, or punctuation. * And lastly the **SyntaxTrivia** structure, which represents syntactically insignificant bits of information such as the whitespace between tokens, preprocessing directives, and comments. **SyntaxNodes** are composed hierarchically to form a tree that completely represents everything in a fragment of Visual Basic or C# code. For example, were you to examine the following Visual Basic source file using the Syntax Visualizer (In Visual Studio, choose **View -> Other Windows -> Syntax Visualizer**) it tree view would look like this: **SyntaxNode**: Blue | **SyntaxToken**: Green | **SyntaxTrivia**: Red ![Visual Basic Code File](images/walkthrough-vb-syntax-figure1.png) By navigating this tree structure you can find any statement, expression, token, or bit of whitespace in a code file! ## Traversing Trees ### Manual Traversal The following steps use **Edit and Continue** to demonstrate how to parse VB source text and find a parameter declaration contained in the source. #### Example - Manually traversing the tree 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project. * In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog. * Under **Visual Basic -> Extensibility**, choose **Stand-Alone Code Analysis Tool**. * Name your project "**GettingStartedVB**" and click OK. 2) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` * Some readers may run with **Option Strict** turned **On** by default at the project level. Turning **Option Strict** **Off** in this walkthrough simplifies many of the examples by removing much of the casting required. 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Move your cursor to the line containing the **End Sub** of your **Main** method and set a breakpoint there. * In Visual Studio, choose **Debug -> Toggle Breakpoint**. 5) Run the program. * In Visual Studio, choose **Debug -> Start Debugging**. 6) Inspect the root variable in the debugger by hovering over it and expanding the datatip. * Note that its **Imports** property is a collection with four elements; one for each Import statement in the parsed text. * Note that the **KindText** of the root node is **CompilationUnit**. * Note that the **Members** collection of the **CompilationUnitSyntax** node has one element. 7) Insert the following statement at the end of the Main method to store the first member of the root **CompilationUnitSyntax** variable into a new variable: ```VB.NET Dim firstMember = root.Members(0) ``` 8) Set this statement as the next statement to be executed and execute it. * Right-click this line and choose **Set Next Statement**. * In Visual Studio, choose **Debug -> Step Over**, to execute this statement and initialize the new variable. * You will need to repeat this process for each of the following steps as we introduce new variables and inspect them with the debugger. 9) Hover over the **firstMember** variable and expand the datatips to inspect it. * Note that its **KindText** is **NamespaceBlock**. * Note that its run-time type is actually **NamespaceBlockSyntax**. 10) Cast this node to **NamespaceBlockSyntax** and store it in a new variable: ```VB.NET Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember ``` 11) Execute this statement and examine the **helloWorldDeclaration** variable. * Note that like the **CompilationUnitSyntax**, **NamespaceBlockSyntax** also has a **Members** collection. 12) Examine the **Members** collection. * Note that it contains a single member. Examine it. * Note that its **KindText** is **ModuleBlock.** * Note that its run-time type is **ModuleBlockSyntax**. 13) Cast this node to **ModuleBlockSyntax** and store it in a new variable: ```VB.NET Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) ``` 14) Execute this statement. 15) Locate the **Main** declaration in the **programDeclaration.Members** collection and store it in a new variable: ```VB.NET Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) ``` 16) Execute this statement and examine the members of the **MethodBlockSyntax** object. * Examine the **BlockStatement** property. * Note the **AsClause**, and **Identifier** properties. * Note the **ParameterList** property; examine it. * Note that it contains both the open and close parentheses of the parameter list in addition to the list of parameters themselves. * Note that the parameters are stored as a **SeparatedSyntaxList**(**Of** **ParameterSyntax**). * Note the **Statements** property. 17) Store the first parameter of the **Main** declaration in a variable. ```VB.NET Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) ``` 18) Execute this statement and examine the **argsParameter** variable. * Examine the **Identifier** property; note that it is of type **ModifiedIdentifierSyntax**. This type represents a normal identifier with an optional nullable modifier (**x?**) and/or array rank specifier (**arr(,)**). * Note that a **ModifiedIdentifierSyntax** has an **Identifier** property of the structure type **SyntaxToken**. * Examine the properties of the **Identifier** **SyntaxToken**; note that the text of the identifier can be found in the **ValueText** property. 19) Stop the program. * In Visual Studio, choose **Debug -> Stop Debugging**. 20) Your program should look like this now: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim firstMember = root.Members(0) Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) End Sub End Module ``` ### Query Methods In addition to traversing trees using the properties of the **SyntaxNode** derived classes you can also explore the syntax tree using the query methods defined on **SyntaxNode**. These methods should be immediately familiar to anyone familiar with XPath. You can use these methods with LINQ to quickly find things in a tree. #### Example - Using query methods 1) Using IntelliSense, examine the members of the **SyntaxNode** class through the root variable. * Note query methods such as **DescendantNodes**, **AncestorsAndSelf**, and **ChildNodes**. 2) Add the following statements to the end of the **Main** method. The first statement uses a LINQ expression and the **DescendantNodes** method to locate the same parameter as in the previous example: ```VB.NET Dim firstParameters = From methodStatement In root.DescendantNodes(). OfType(Of Syntax.MethodStatementSyntax)() Where methodStatement.Identifier.ValueText = "Main" Select methodStatement.ParameterList.Parameters.First() Dim argsParameter2 = firstParameters.First() ``` 3) Start debugging the program. 4) Open the Immediate Window. * In Visual Studio, choose **Debug -> Windows -> Immediate**. 5) Using the Immediate window, type the expression **? argsParameter Is argsParameter2** and press enter to evaluate it. * Note that the LINQ expression found the same parameter as manually navigating the tree. 6) Stop the program. ### SyntaxWalkers Often you'll want to find all nodes of a specific type in a syntax tree, for example, every property declaration in a file. By extending the **VisualBasicSyntaxWalker** class and overriding the **VisitPropertyStatement** method, you can process every property declaration in a syntax tree without knowing its structure beforehand. **VisualBasicSyntaxWalker** is a specific kind of **SyntaxVisitor** which recursively visits a node and each of its children. #### Example - Implementing a VisualBasicSyntaxWalker This example shows how to implement a **VisualBasicSyntaxWalker** which examines an entire syntax tree and collects any **Imports** statements it finds which aren't importing a **System** namespace. 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project; name it "**ImportsCollectorVB**". 3) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Note that this source text contains a long list of **Imports** statements. 5) Add a new class file to the project. * In Visual Studio, choose **Project -> Add Class...** * In the "Add New Item" dialog type **ImportsCollector.vb** as the filename. 6) Enter the following lines at the top of your **ImportsCollector.vb** file: ```VB.NET Option Strict Off ``` 7) Make the new **ImportsCollector** class in this file extend the **VisualBasicSyntaxWalker** class: ```VB.NET Public Class ImportsCollector Inherits VisualBasicSyntaxWalker ``` 8) Declare a public read-only field in the **ImportsCollector** class; we'll use this variable to store the **ImportsStatementSyntax** nodes we find: ```VB.NET Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() ``` 9) Override the **VisitSimpleImportsClause** method: ```VB.NET Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) End Sub ``` 10) Using IntelliSense, examine the **SimpleImportsClauseSyntax** class through the **node** parameter of this method. * Note the **Name** property of type **NameSyntax**; this stores the name of the namespace being imported. 11) Replace the code in the **VisitSimpleImportsClause** method with the following to conditionally add the found **node** to the **[Imports]** collection if **Name** doesn't refer to the **System** namespace or any of its descendant namespaces: ```VB.NET If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) ``` 12) The **ImportsCollector.vb** file should now look like this: ```VB.NET Option Strict Off Public Class ImportsCollector Inherits VisualBasicSyntaxWalker Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) End Sub End Class ``` 13) Return to the **Module1.vb** file. 14) Add the following code to the end of the **Main** method to create an instance of the **ImportsCollector**, use that instance to visit the root of the parsed tree, and iterate over the **ImportsStatementSyntax** nodes collected and print their names to the **Console**: ```VB.NET Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next ``` 15) Your **Module1.vb** file should now look like this: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next End Sub End Module ``` 16) Press **Ctrl+F5** to run the program without debugging it. You should see the following output: ``` Imports Microsoft.VisualBasic Imports Microsoft.Win32 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Press any key to continue . . . ``` 17) Observe that the walker has located all four non-**System** namespace **Imports** statements. 18) Congratulations! You've just used the **Syntax API** to locate specific kinds of VB statements and declarations in VB source code.
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/VisualBasicTest/CodeActions/ConvertIfToSwitch/ConvertIfToSwitchTests.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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.ConvertIfToSwitch Public Class ConvertIfToSwitchTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertIfToSwitchCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMultipleCases() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i = 1 OrElse 2 = i OrElse i = 3 Then M(0) ElseIf i = 4 OrElse 5 = i OrElse i = 6 Then M(1) Else M(2) End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case 1, 2, 3 M(0) Case 4, 5, 6 M(1) Case Else M(2) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMultipleCaseLineContinuation() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i = 1 OrElse 2 = i OrElse i = 3 _ Then M(0) ElseIf i = 4 OrElse 5 = i OrElse i = 6 Then M(1) Else M(2) End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case 1, 2, 3 _ M(0) Case 4, 5, 6 M(1) Case Else M(2) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestConstantExpression() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) Const A = 1, B = 2, C = 3 [||]If i = A OrElse B = i OrElse i = C Then M(0) End If End Sub End Class", "Class C Sub M(i As Integer) Const A = 1, B = 2, C = 3 Select i Case A, B, C M(0) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMissingOnNonConstantExpression() As Task Await TestMissingInRegularAndScriptAsync( "Class C Sub M(i As Integer) Dim A = 1, B = 2, C = 3 [||]If A = 1 OrElse 2 = B OrElse C = 3 Then M(0) End If End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMissingOnDifferentOperands() As Task Await TestMissingInRegularAndScriptAsync( "Class C Sub M(i As Integer, j As Integer) [||]If i = 5 OrElse 6 = j Then M(0) End If End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMissingForSingleCase() As Task Await TestMissingAsync( "Class C Sub M(i As Integer) [||]If i = 5 Then End If End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestRange() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If 5 >= i AndAlso 1 <= i Then Else If 7 >= i AndAlso 6 <= i End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case 1 To 5 Case 6 To 7 End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestComparison() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i <= 5 OrElse i >= 1 Then End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case Is <= 5, Is >= 1 End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestComplexIf() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i < 10 OrElse 20 < i OrElse (i >= 30 AndAlso 40 >= i) OrElse i = 50 Then End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case Is < 10, Is > 20, 30 To 40, 50 End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSingleLineIf() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i = 10 Then M(5) Else M(6) End Sub End Class", "Class C Sub M(i As Integer) Select i Case 10 M(5) Case Else M(6) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_01() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 Case Else Return 7 End Select End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_02() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 Else Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 Case Else Return 7 End Select End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_03() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then M(6) If i = 30 Then Return 6 Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 M(6) End Select If i = 30 Then Return 6 Return 7 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_04() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 If i = i Then Return 0 Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 End Select If i = i Then Return 0 Return 7 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_05() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 ElseIf i = 30 Then Return 7 End If If i = i Then Return 0 Return 8 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 Case 30 Return 7 End Select If i = i Then Return 0 Return 8 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_06() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 Else Return 4 If i = 20 Then Return 6 ElseIf i = i Then Return 7 End If If i = 5 Then Return 0 Return 8 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case Else Return 4 End Select If i = 20 Then Return 6 ElseIf i = i Then Return 7 End If If i = 5 Then Return 0 Return 8 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestExitWhile() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) While i = i [||]If i = 10 Then Exit While Else If i = 1 Then End If End While End Sub End Class", "Class C Sub M(i As Integer) While i = i Select i Case 10 Exit While Case 1 End Select End While End Sub End Class") End Function <WorkItem(21103, "https://github.com/dotnet/roslyn/issues/21103")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestTrivia1() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) #if true Console.WriteLine() #end if [||]If i = 1 OrElse 2 = i OrElse i = 3 Then M(0) ElseIf i = 4 OrElse 5 = i OrElse i = 6 Then M(1) Else M(2) End If End Sub End Class", "Class C Sub M(i As Integer) #if true Console.WriteLine() #end if Select i Case 1, 2, 3 M(0) Case 4, 5, 6 M(1) Case Else M(2) End Select End Sub End Class") 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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.ConvertIfToSwitch Public Class ConvertIfToSwitchTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertIfToSwitchCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMultipleCases() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i = 1 OrElse 2 = i OrElse i = 3 Then M(0) ElseIf i = 4 OrElse 5 = i OrElse i = 6 Then M(1) Else M(2) End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case 1, 2, 3 M(0) Case 4, 5, 6 M(1) Case Else M(2) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMultipleCaseLineContinuation() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i = 1 OrElse 2 = i OrElse i = 3 _ Then M(0) ElseIf i = 4 OrElse 5 = i OrElse i = 6 Then M(1) Else M(2) End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case 1, 2, 3 _ M(0) Case 4, 5, 6 M(1) Case Else M(2) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestConstantExpression() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) Const A = 1, B = 2, C = 3 [||]If i = A OrElse B = i OrElse i = C Then M(0) End If End Sub End Class", "Class C Sub M(i As Integer) Const A = 1, B = 2, C = 3 Select i Case A, B, C M(0) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMissingOnNonConstantExpression() As Task Await TestMissingInRegularAndScriptAsync( "Class C Sub M(i As Integer) Dim A = 1, B = 2, C = 3 [||]If A = 1 OrElse 2 = B OrElse C = 3 Then M(0) End If End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMissingOnDifferentOperands() As Task Await TestMissingInRegularAndScriptAsync( "Class C Sub M(i As Integer, j As Integer) [||]If i = 5 OrElse 6 = j Then M(0) End If End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestMissingForSingleCase() As Task Await TestMissingAsync( "Class C Sub M(i As Integer) [||]If i = 5 Then End If End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestRange() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If 5 >= i AndAlso 1 <= i Then Else If 7 >= i AndAlso 6 <= i End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case 1 To 5 Case 6 To 7 End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestComparison() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i <= 5 OrElse i >= 1 Then End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case Is <= 5, Is >= 1 End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestComplexIf() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i < 10 OrElse 20 < i OrElse (i >= 30 AndAlso 40 >= i) OrElse i = 50 Then End If End Sub End Class", "Class C Sub M(i As Integer) Select i Case Is < 10, Is > 20, 30 To 40, 50 End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSingleLineIf() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) [||]If i = 10 Then M(5) Else M(6) End Sub End Class", "Class C Sub M(i As Integer) Select i Case 10 M(5) Case Else M(6) End Select End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_01() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 Case Else Return 7 End Select End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_02() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 Else Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 Case Else Return 7 End Select End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_03() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then M(6) If i = 30 Then Return 6 Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 M(6) End Select If i = 30 Then Return 6 Return 7 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_04() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 If i = i Then Return 0 Return 7 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 End Select If i = i Then Return 0 Return 7 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_05() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 If i = 20 Then Return 6 ElseIf i = 30 Then Return 7 End If If i = i Then Return 0 Return 8 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case 20 Return 6 Case 30 Return 7 End Select If i = i Then Return 0 Return 8 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestSubsequentIfStatements_06() As Task Await TestInRegularAndScriptAsync( "Class C Function M(i As Integer) As Integer [||]If i = 10 Then Return 5 Else Return 4 If i = 20 Then Return 6 ElseIf i = i Then Return 7 End If If i = 5 Then Return 0 Return 8 End Function End Class", "Class C Function M(i As Integer) As Integer Select i Case 10 Return 5 Case Else Return 4 End Select If i = 20 Then Return 6 ElseIf i = i Then Return 7 End If If i = 5 Then Return 0 Return 8 End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestExitWhile() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) While i = i [||]If i = 10 Then Exit While Else If i = 1 Then End If End While End Sub End Class", "Class C Sub M(i As Integer) While i = i Select i Case 10 Exit While Case 1 End Select End While End Sub End Class") End Function <WorkItem(21103, "https://github.com/dotnet/roslyn/issues/21103")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertIfToSwitch)> Public Async Function TestTrivia1() As Task Await TestInRegularAndScriptAsync( "Class C Sub M(i As Integer) #if true Console.WriteLine() #end if [||]If i = 1 OrElse 2 = i OrElse i = 3 Then M(0) ElseIf i = 4 OrElse 5 = i OrElse i = 6 Then M(1) Else M(2) End If End Sub End Class", "Class C Sub M(i As Integer) #if true Console.WriteLine() #end if Select i Case 1, 2, 3 M(0) Case 4, 5, 6 M(1) Case Else M(2) End Select End Sub End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Scripting/Core/ScriptRunner.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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A delegate that will run a script when invoked. /// </summary> /// <param name="globals">An object instance whose members can be accessed by the script as global variables.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match the corresponding <see cref="Script.GlobalsType"/>.</exception> public delegate Task<T> ScriptRunner<T>(object globals = null, CancellationToken cancellationToken = default(CancellationToken)); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A delegate that will run a script when invoked. /// </summary> /// <param name="globals">An object instance whose members can be accessed by the script as global variables.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match the corresponding <see cref="Script.GlobalsType"/>.</exception> public delegate Task<T> ScriptRunner<T>(object globals = null, CancellationToken cancellationToken = default(CancellationToken)); }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/VisualStudio/CSharp/Impl/CodeModel/EndRegionFormattingRule.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; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Formatting.Rules; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal sealed class EndRegionFormattingRule : AbstractFormattingRule { public static readonly EndRegionFormattingRule Instance = new(); private EndRegionFormattingRule() { } private bool IsAfterEndRegionBeforeMethodDeclaration(SyntaxToken previousToken) { if (previousToken.Kind() == SyntaxKind.EndOfDirectiveToken) { var previousPreviousToken = previousToken.GetPreviousToken(); return previousPreviousToken.Kind() == SyntaxKind.EndRegionKeyword; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (IsAfterEndRegionBeforeMethodDeclaration(previousToken)) { return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines); } return nextOperation.Invoke(in previousToken, in currentToken); } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Formatting.Rules; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal sealed class EndRegionFormattingRule : AbstractFormattingRule { public static readonly EndRegionFormattingRule Instance = new(); private EndRegionFormattingRule() { } private bool IsAfterEndRegionBeforeMethodDeclaration(SyntaxToken previousToken) { if (previousToken.Kind() == SyntaxKind.EndOfDirectiveToken) { var previousPreviousToken = previousToken.GetPreviousToken(); return previousPreviousToken.Kind() == SyntaxKind.EndRegionKeyword; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (IsAfterEndRegionBeforeMethodDeclaration(previousToken)) { return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines); } return nextOperation.Invoke(in previousToken, in currentToken); } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/Core/Rebuild/xlf/RebuildResources.fr.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="fr" original="../RebuildResources.resx"> <body> <trans-unit id="0_exists_1_times_in_compilation_options"> <source>'{0}' exists '{1}' times in compilation options.</source> <target state="new">'{0}' exists '{1}' times in compilation options.</target> <note /> </trans-unit> <trans-unit id="A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB"> <source>A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</source> <target state="new">A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Cannot_create_compilation_options_0"> <source>Cannot create compilation options: {0}</source> <target state="new">Cannot create compilation options: {0}</target> <note /> </trans-unit> <trans-unit id="Could_not_get_PDB_file_path"> <source>Could not get PDB file path.</source> <target state="new">Could not get PDB file path.</target> <note /> </trans-unit> <trans-unit id="Does_not_contain_metadata_compilation_options"> <source>Does not contain metadata compilation options.</source> <target state="new">Does not contain metadata compilation options.</target> <note /> </trans-unit> <trans-unit id="Encountered_null_or_empty_key_for_compilation_options_pairs"> <source>Encountered null or empty key for compilation options pairs.</source> <target state="new">Encountered null or empty key for compilation options pairs.</target> <note /> </trans-unit> <trans-unit id="Encountered_unexpected_byte_0_when_expecting_a_null_terminator"> <source>Encountered unexpected byte '{0}' when expecting a null terminator.</source> <target state="new">Encountered unexpected byte '{0}' when expecting a null terminator.</target> <note /> </trans-unit> <trans-unit id="Invalid_language_name"> <source>Invalid language name.</source> <target state="new">Invalid language name.</target> <note /> </trans-unit> <trans-unit id="PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB"> <source>PDB stream must be null because the compilation has an embedded PDB.</source> <target state="new">PDB stream must be null because the compilation has an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Unexpected_value_for_EmbedInteropTypes_MetadataImageKind_0"> <source>Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</source> <target state="new">Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</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="fr" original="../RebuildResources.resx"> <body> <trans-unit id="0_exists_1_times_in_compilation_options"> <source>'{0}' exists '{1}' times in compilation options.</source> <target state="new">'{0}' exists '{1}' times in compilation options.</target> <note /> </trans-unit> <trans-unit id="A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB"> <source>A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</source> <target state="new">A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Cannot_create_compilation_options_0"> <source>Cannot create compilation options: {0}</source> <target state="new">Cannot create compilation options: {0}</target> <note /> </trans-unit> <trans-unit id="Could_not_get_PDB_file_path"> <source>Could not get PDB file path.</source> <target state="new">Could not get PDB file path.</target> <note /> </trans-unit> <trans-unit id="Does_not_contain_metadata_compilation_options"> <source>Does not contain metadata compilation options.</source> <target state="new">Does not contain metadata compilation options.</target> <note /> </trans-unit> <trans-unit id="Encountered_null_or_empty_key_for_compilation_options_pairs"> <source>Encountered null or empty key for compilation options pairs.</source> <target state="new">Encountered null or empty key for compilation options pairs.</target> <note /> </trans-unit> <trans-unit id="Encountered_unexpected_byte_0_when_expecting_a_null_terminator"> <source>Encountered unexpected byte '{0}' when expecting a null terminator.</source> <target state="new">Encountered unexpected byte '{0}' when expecting a null terminator.</target> <note /> </trans-unit> <trans-unit id="Invalid_language_name"> <source>Invalid language name.</source> <target state="new">Invalid language name.</target> <note /> </trans-unit> <trans-unit id="PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB"> <source>PDB stream must be null because the compilation has an embedded PDB.</source> <target state="new">PDB stream must be null because the compilation has an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Unexpected_value_for_EmbedInteropTypes_MetadataImageKind_0"> <source>Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</source> <target state="new">Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.Tree.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.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class ClosureConversion { internal sealed partial class Analysis : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// This is the core node for a Scope tree, which stores all semantically meaningful /// information about declared variables, closures, and environments in each scope. /// It can be thought of as the essence of the bound tree -- stripping away many of /// the unnecessary details stored in the bound tree and just leaving the pieces that /// are important for closure conversion. The root scope is the method scope for the /// method being analyzed and has a null <see cref="Parent" />. /// </summary> [DebuggerDisplay("{ToString(), nq}")] public sealed class Scope { public readonly Scope Parent; public readonly ArrayBuilder<Scope> NestedScopes = ArrayBuilder<Scope>.GetInstance(); /// <summary> /// A list of all nested functions (all lambdas and local functions) declared in this scope. /// </summary> public readonly ArrayBuilder<NestedFunction> NestedFunctions = ArrayBuilder<NestedFunction>.GetInstance(); /// <summary> /// A list of all locals or parameters that were declared in this scope and captured /// in this scope or nested scopes. "Declared" refers to the start of the variable /// lifetime (which, at this point in lowering, should be equivalent to lexical scope). /// </summary> /// <remarks> /// It's important that this is a set and that enumeration order is deterministic. We loop /// over this list to generate proxies and if we loop out of order this will cause /// non-deterministic compilation, and if we generate duplicate proxies we'll generate /// wasteful code in the best case and incorrect code in the worst. /// </remarks> public readonly SetWithInsertionOrder<Symbol> DeclaredVariables = new SetWithInsertionOrder<Symbol>(); /// <summary> /// The bound node representing this scope. This roughly corresponds to the bound /// node for the block declaring locals for this scope, although parameters of /// methods/functions are introduced into their Body's scope and do not get their /// own scope. /// </summary> public readonly BoundNode BoundNode; /// <summary> /// The nested function that this scope is nested inside. Null if this scope is not nested /// inside a nested function. /// </summary> public readonly NestedFunction ContainingFunctionOpt; #nullable enable /// <summary> /// Environment created in this scope to hold <see cref="DeclaredVariables"/>. /// At the moment, all variables declared in the same scope /// always get assigned to the same environment. /// </summary> public ClosureEnvironment? DeclaredEnvironment = null; #nullable disable public Scope(Scope parent, BoundNode boundNode, NestedFunction containingFunction) { Debug.Assert(boundNode != null); Parent = parent; BoundNode = boundNode; ContainingFunctionOpt = containingFunction; } /// <summary> /// Is it safe to move any of the variables declared in this scope to the parent scope, /// or would doing so change the meaning of the program? /// </summary> public bool CanMergeWithParent { get; internal set; } = true; public void Free() { foreach (var scope in NestedScopes) { scope.Free(); } NestedScopes.Free(); foreach (var function in NestedFunctions) { function.Free(); } NestedFunctions.Free(); } public override string ToString() => BoundNode.Syntax.GetText().ToString(); } /// <summary> /// The NestedFunction type represents a lambda or local function and stores /// information related to that function. After initially building the /// <see cref="Scope"/> tree the only information available is /// <see cref="OriginalMethodSymbol"/> and <see cref="CapturedVariables"/>. /// Subsequent passes are responsible for translating captured /// variables into captured environments and for calculating /// the rewritten signature of the method. /// </summary> public sealed class NestedFunction { /// <summary> /// The method symbol for the original lambda or local function. /// </summary> public readonly MethodSymbol OriginalMethodSymbol; /// <summary> /// Syntax for the block of the nested function. /// </summary> public readonly SyntaxReference BlockSyntax; public readonly PooledHashSet<Symbol> CapturedVariables = PooledHashSet<Symbol>.GetInstance(); public readonly ArrayBuilder<ClosureEnvironment> CapturedEnvironments = ArrayBuilder<ClosureEnvironment>.GetInstance(); public ClosureEnvironment ContainingEnvironmentOpt; private bool _capturesThis; /// <summary> /// True if this function directly or transitively captures 'this' (captures /// a local function which directly or indirectly captures 'this'). /// Calculated in <see cref="MakeAndAssignEnvironments"/>. /// </summary> public bool CapturesThis { get => _capturesThis; set { Debug.Assert(value); _capturesThis = value; } } public SynthesizedClosureMethod SynthesizedLoweredMethod; public NestedFunction(MethodSymbol symbol, SyntaxReference blockSyntax) { Debug.Assert(symbol != null); OriginalMethodSymbol = symbol; BlockSyntax = blockSyntax; } public void Free() { CapturedVariables.Free(); CapturedEnvironments.Free(); } } public sealed class ClosureEnvironment { public readonly SetWithInsertionOrder<Symbol> CapturedVariables; /// <summary> /// True if this environment captures a reference to a class environment /// declared in a higher scope. Assigned by /// <see cref="ComputeLambdaScopesAndFrameCaptures()"/> /// </summary> public bool CapturesParent; public readonly bool IsStruct; internal SynthesizedClosureEnvironment SynthesizedEnvironment; public ClosureEnvironment(IEnumerable<Symbol> capturedVariables, bool isStruct) { CapturedVariables = new SetWithInsertionOrder<Symbol>(); foreach (var item in capturedVariables) { CapturedVariables.Add(item); } IsStruct = isStruct; } } /// <summary> /// Visit all nested functions in all nested scopes and run the <paramref name="action"/>. /// </summary> public static void VisitNestedFunctions(Scope scope, Action<Scope, NestedFunction> action) { foreach (var function in scope.NestedFunctions) { action(scope, function); } foreach (var nested in scope.NestedScopes) { VisitNestedFunctions(nested, action); } } /// <summary> /// Visit all the functions and return true when the <paramref name="func"/> returns /// true. Otherwise, returns false. /// </summary> public static bool CheckNestedFunctions(Scope scope, Func<Scope, NestedFunction, bool> func) { foreach (var function in scope.NestedFunctions) { if (func(scope, function)) { return true; } } foreach (var nested in scope.NestedScopes) { if (CheckNestedFunctions(nested, func)) { return true; } } return false; } /// <summary> /// Visit the tree with the given root and run the <paramref name="action"/> /// </summary> public static void VisitScopeTree(Scope treeRoot, Action<Scope> action) { action(treeRoot); foreach (var nested in treeRoot.NestedScopes) { VisitScopeTree(nested, action); } } /// <summary> /// Builds a tree of <see cref="Scope"/> nodes corresponding to a given method. /// <see cref="Build(BoundNode, MethodSymbol, HashSet{MethodSymbol}, DiagnosticBag)"/> /// visits the bound tree and translates information from the bound tree about /// variable scope, declared variables, and variable captures into the resulting /// <see cref="Scope"/> tree. /// /// At the same time it sets <see cref="Scope.CanMergeWithParent"/> /// for each Scope. This is done by looking for <see cref="BoundGotoStatement"/>s /// and <see cref="BoundConditionalGoto"/>s that jump from a point /// after the beginning of a <see cref="Scope"/>, to a <see cref="BoundLabelStatement"/> /// before the start of the scope, but after the start of <see cref="Scope.Parent"/>. /// /// All loops have been converted to gotos and labels by this stage, /// so we do not have to visit them to do so. Similarly all <see cref="BoundLabeledStatement"/>s /// have been converted to <see cref="BoundLabelStatement"/>s, so we do not have to /// visit them. /// </summary> private class ScopeTreeBuilder : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Do not set this directly, except when setting the root scope. /// Instead use <see cref="PopScope"/> or <see cref="CreateAndPushScope"/>. /// </summary> private Scope _currentScope; /// <summary> /// Null if we're not inside a nested function, otherwise the nearest nested function. /// </summary> private NestedFunction _currentFunction = null; private bool _inExpressionTree = false; /// <summary> /// A mapping from all captured vars to the scope they were declared in. This /// is used when recording captured variables as we must know what the lifetime /// of a captured variable is to determine the lifetime of its capture environment. /// </summary> private readonly SmallDictionary<Symbol, Scope> _localToScope = new SmallDictionary<Symbol, Scope>(); #if DEBUG /// <summary> /// Free variables are variables declared in expression statements that can then /// be captured in nested lambdas. Normally, captured variables must lowered as /// part of closure conversion, but expression tree variables are handled separately /// by the expression tree rewriter and are considered free for the purposes of /// closure conversion. For instance, an expression with a nested lambda, e.g. /// x => y => x + y /// contains an expression variable, x, that should not be treated as a captured /// variable to be replaced by closure conversion. Instead, it should be left for /// expression tree conversion. /// </summary> private readonly HashSet<Symbol> _freeVariables = new HashSet<Symbol>(); #endif private readonly MethodSymbol _topLevelMethod; /// <summary> /// If a local function is in the set, at some point in the code it is converted /// to a delegate and should then not be optimized to a struct closure. /// Also contains all lambdas (as they are converted to delegates implicitly). /// </summary> private readonly HashSet<MethodSymbol> _methodsConvertedToDelegates; private readonly DiagnosticBag _diagnostics; /// <summary> /// For every label visited so far, this dictionary maps to a list of all scopes either visited so far, or currently being visited, /// that are both after the label, and are on the same level of the scope tree as the label. /// </summary> private readonly PooledDictionary<LabelSymbol, ArrayBuilder<Scope>> _scopesAfterLabel = PooledDictionary<LabelSymbol, ArrayBuilder<Scope>>.GetInstance(); /// <summary> /// Contains a list of the labels visited so far for each scope. /// The outer ArrayBuilder is a stack representing the chain of scopes from the root scope to the current scope, /// and for each item on the stack, the ArrayBuilder is the list of the labels visited so far for the scope. /// /// Used by <see cref="CreateAndPushScope"/> to determine which labels a new child scope appears after. /// </summary> private readonly ArrayBuilder<ArrayBuilder<LabelSymbol>> _labelsInScope = ArrayBuilder<ArrayBuilder<LabelSymbol>>.GetInstance(); private ScopeTreeBuilder( Scope rootScope, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { Debug.Assert(rootScope != null); Debug.Assert(topLevelMethod != null); Debug.Assert(methodsConvertedToDelegates != null); Debug.Assert(diagnostics != null); _currentScope = rootScope; _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _topLevelMethod = topLevelMethod; _methodsConvertedToDelegates = methodsConvertedToDelegates; _diagnostics = diagnostics; } public static Scope Build( BoundNode node, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { // This should be the top-level node Debug.Assert(node == FindNodeToAnalyze(node)); Debug.Assert(topLevelMethod != null); var rootScope = new Scope(parent: null, boundNode: node, containingFunction: null); var builder = new ScopeTreeBuilder( rootScope, topLevelMethod, methodsConvertedToDelegates, diagnostics); builder.Build(); return rootScope; } private void Build() { // Set up the current method locals DeclareLocals(_currentScope, _topLevelMethod.Parameters); // Treat 'this' as a formal parameter of the top-level method if (_topLevelMethod.TryGetThisParameter(out var thisParam) && (object)thisParam != null) { DeclareLocals(_currentScope, ImmutableArray.Create<Symbol>(thisParam)); } Visit(_currentScope.BoundNode); // Clean Up Resources foreach (var scopes in _scopesAfterLabel.Values) { scopes.Free(); } _scopesAfterLabel.Free(); Debug.Assert(_labelsInScope.Count == 1); var labels = _labelsInScope.Pop(); labels.Free(); _labelsInScope.Free(); } public override BoundNode VisitMethodGroup(BoundMethodGroup node) => throw ExceptionUtilities.Unreachable; public override BoundNode VisitBlock(BoundBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitCatchBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitSequence(BoundSequence node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitSequence(node); PopScope(oldScope); return result; } public override BoundNode VisitLambda(BoundLambda node) { var oldInExpressionTree = _inExpressionTree; _inExpressionTree |= node.Type.IsExpressionTree(); _methodsConvertedToDelegates.Add(node.Symbol.OriginalDefinition); var result = VisitNestedFunction(node.Symbol, node.Body); _inExpressionTree = oldInExpressionTree; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) => VisitNestedFunction(node.Symbol.OriginalDefinition, node.Body); public override BoundNode VisitCall(BoundCall node) { if (node.Method.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters AddIfCaptured(node.Method.OriginalDefinition, node.Syntax); } return base.VisitCall(node); } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters var method = node.MethodOpt.OriginalDefinition; AddIfCaptured(method, node.Syntax); _methodsConvertedToDelegates.Add(method); } return base.VisitDelegateCreationExpression(node); } public override BoundNode VisitParameter(BoundParameter node) { AddIfCaptured(node.ParameterSymbol, node.Syntax); return base.VisitParameter(node); } public override BoundNode VisitLocal(BoundLocal node) { AddIfCaptured(node.LocalSymbol, node.Syntax); return base.VisitLocal(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { AddIfCaptured(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitThisReference(BoundThisReference node) { var thisParam = _topLevelMethod.ThisParameter; if (thisParam != null) { AddIfCaptured(thisParam, node.Syntax); } else { // This can occur in a delegate creation expression because the method group // in the argument can have a "this" receiver even when "this" // is not captured because a static method is selected. But we do preserve // the method group and its receiver in the bound tree. // No need to capture "this" in such case. // TODO: Why don't we drop "this" while lowering if method is static? // Actually, considering that method group expression does not evaluate to a particular value // why do we have it in the lowered tree at all? } return base.VisitThisReference(node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { _labelsInScope.Peek().Add(node.Label); _scopesAfterLabel.Add(node.Label, ArrayBuilder<Scope>.GetInstance()); return base.VisitLabelStatement(node); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { CheckCanMergeWithParent(node.Label); return base.VisitGotoStatement(node); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { CheckCanMergeWithParent(node.Label); return base.VisitConditionalGoto(node); } /// <summary> /// This is where we calculate <see cref="Scope.CanMergeWithParent"/>. /// <see cref="Scope.CanMergeWithParent"/> is always true unless we jump from after /// the beginning of a scope, to a point in between the beginning of the parent scope, and the beginning of the scope /// </summary> /// <param name="jumpTarget"></param> private void CheckCanMergeWithParent(LabelSymbol jumpTarget) { // since forward jumps can never effect Scope.SemanticallySafeToMergeIntoParent // if we have not yet seen the jumpTarget, this is a forward jump, and can be ignored if (_scopesAfterLabel.TryGetValue(jumpTarget, out var scopesAfterLabel)) { foreach (var scope in scopesAfterLabel) { // this jump goes from a point after the beginning of the scope (as we have already visited or started visiting the scope), // to a point in between the beginning of the parent scope, and the beginning of the scope, so it is not safe to move // variables in the scope to the parent scope. scope.CanMergeWithParent = false; } // Prevent us repeating this process for all scopes if another jumps goes to the same label scopesAfterLabel.Clear(); } } #nullable enable private BoundNode? VisitNestedFunction(MethodSymbol functionSymbol, BoundBlock? body) { RoslynDebug.Assert(functionSymbol is object); if (body is null) { // extern closure _currentScope.NestedFunctions.Add(new NestedFunction(functionSymbol, blockSyntax: null)); return null; } // Nested function is declared (lives) in the parent scope, but its // variables are in a nested scope var function = new NestedFunction(functionSymbol, body.Syntax.GetReference()); _currentScope.NestedFunctions.Add(function); var oldFunction = _currentFunction; _currentFunction = function; var oldScope = _currentScope; CreateAndPushScope(body); // For the purposes of scoping, parameters live in the same scope as the // nested function block. Expression tree variables are free variables for the // purposes of closure conversion DeclareLocals(_currentScope, functionSymbol.Parameters, _inExpressionTree); var result = _inExpressionTree ? base.VisitBlock(body) : VisitBlock(body); PopScope(oldScope); _currentFunction = oldFunction; return result; } #nullable disable private void AddIfCaptured(Symbol symbol, SyntaxNode syntax) { Debug.Assert( symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol.Kind == SymbolKind.Method); if (_currentFunction == null) { // Can't be captured if we're not in a nested function return; } if (symbol is LocalSymbol local && local.IsConst) { // consts aren't captured since they're inlined return; } if (symbol is MethodSymbol method && _currentFunction.OriginalMethodSymbol == method) { // Is this recursion? If so there's no capturing return; } Debug.Assert(symbol.ContainingSymbol != null); if (symbol.ContainingSymbol != _currentFunction.OriginalMethodSymbol) { // Restricted types can't be hoisted, so they are not permitted to be captured AddDiagnosticIfRestrictedType(symbol, syntax); // Record the captured variable where it's captured var scope = _currentScope; var function = _currentFunction; while (function != null && symbol.ContainingSymbol != function.OriginalMethodSymbol) { function.CapturedVariables.Add(symbol); // Also mark captured in enclosing scopes while (scope.ContainingFunctionOpt == function) { scope = scope.Parent; } function = scope.ContainingFunctionOpt; } // Also record where the captured variable lives // No need to record where local functions live: that was recorded // in the NestedFunctions list in each scope if (symbol.Kind == SymbolKind.Method) { return; } if (_localToScope.TryGetValue(symbol, out var declScope)) { declScope.DeclaredVariables.Add(symbol); } else { #if DEBUG // Parameters and locals from expression tree lambdas // are free variables Debug.Assert(_freeVariables.Contains(symbol)); #endif } } } /// <summary> /// Add a diagnostic if the type of a captured variable is a restricted type /// </summary> private void AddDiagnosticIfRestrictedType(Symbol capturedVariable, SyntaxNode syntax) { TypeSymbol type; switch (capturedVariable.Kind) { case SymbolKind.Local: type = ((LocalSymbol)capturedVariable).Type; break; case SymbolKind.Parameter: type = ((ParameterSymbol)capturedVariable).Type; break; default: // This should only be called for captured variables, and captured // variables must be a method, parameter, or local symbol Debug.Assert(capturedVariable.Kind == SymbolKind.Method); return; } if (type.IsRestrictedType() == true) { _diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, type); } } /// <summary> /// Create a new nested scope under the current scope, and replace <see cref="_currentScope"/> with the new scope, /// or reuse the current scope if there's no change in the bound node for the nested scope. /// Records the given locals as declared in the aforementioned scope. /// </summary> private void PushOrReuseScope<TSymbol>(BoundNode node, ImmutableArray<TSymbol> locals) where TSymbol : Symbol { // We should never create a new scope with the same bound node. We can get into // this situation for methods and nested functions where a new scope is created // to add parameters and a new scope would be created for the method block, // despite the fact that they should be the same scope. if (!locals.IsEmpty && _currentScope.BoundNode != node) { CreateAndPushScope(node); } DeclareLocals(_currentScope, locals); } /// <summary> /// Creates a new nested scope which is a child of <see cref="_currentScope"/>, /// and replaces <see cref="_currentScope"/> with the new scope /// </summary> /// <param name="node"></param> private void CreateAndPushScope(BoundNode node) { var scope = CreateNestedScope(_currentScope, _currentFunction); foreach (var label in _labelsInScope.Peek()) { _scopesAfterLabel[label].Add(scope); } _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _currentScope = scope; Scope CreateNestedScope(Scope parentScope, NestedFunction currentFunction) { Debug.Assert(parentScope.BoundNode != node); var newScope = new Scope(parentScope, node, currentFunction); parentScope.NestedScopes.Add(newScope); return newScope; } } /// <summary> /// Requires that scope is either the same as <see cref="_currentScope"/>, /// or is the <see cref="Scope.Parent"/> of <see cref="_currentScope"/>. /// Returns immediately in the first case, /// Replaces <see cref="_currentScope"/> with scope in the second. /// </summary> /// <param name="scope"></param> private void PopScope(Scope scope) { if (scope == _currentScope) { return; } Debug.Assert(scope == _currentScope.Parent, $"{nameof(scope)} must be {nameof(_currentScope)} or {nameof(_currentScope)}.{nameof(_currentScope.Parent)}"); // Since it is forbidden to jump into a scope, // we can forget all information we have about labels in the child scope var labels = _labelsInScope.Pop(); foreach (var label in labels) { var scopes = _scopesAfterLabel[label]; scopes.Free(); _scopesAfterLabel.Remove(label); } labels.Free(); _currentScope = _currentScope.Parent; } private void DeclareLocals<TSymbol>(Scope scope, ImmutableArray<TSymbol> locals, bool declareAsFree = false) where TSymbol : Symbol { foreach (var local in locals) { Debug.Assert(!_localToScope.ContainsKey(local)); if (declareAsFree) { #if DEBUG Debug.Assert(_freeVariables.Add(local)); #endif } else { _localToScope.Add(local, scope); } } } } } } }
// Licensed to the .NET Foundation under one or more 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.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class ClosureConversion { internal sealed partial class Analysis : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// This is the core node for a Scope tree, which stores all semantically meaningful /// information about declared variables, closures, and environments in each scope. /// It can be thought of as the essence of the bound tree -- stripping away many of /// the unnecessary details stored in the bound tree and just leaving the pieces that /// are important for closure conversion. The root scope is the method scope for the /// method being analyzed and has a null <see cref="Parent" />. /// </summary> [DebuggerDisplay("{ToString(), nq}")] public sealed class Scope { public readonly Scope Parent; public readonly ArrayBuilder<Scope> NestedScopes = ArrayBuilder<Scope>.GetInstance(); /// <summary> /// A list of all nested functions (all lambdas and local functions) declared in this scope. /// </summary> public readonly ArrayBuilder<NestedFunction> NestedFunctions = ArrayBuilder<NestedFunction>.GetInstance(); /// <summary> /// A list of all locals or parameters that were declared in this scope and captured /// in this scope or nested scopes. "Declared" refers to the start of the variable /// lifetime (which, at this point in lowering, should be equivalent to lexical scope). /// </summary> /// <remarks> /// It's important that this is a set and that enumeration order is deterministic. We loop /// over this list to generate proxies and if we loop out of order this will cause /// non-deterministic compilation, and if we generate duplicate proxies we'll generate /// wasteful code in the best case and incorrect code in the worst. /// </remarks> public readonly SetWithInsertionOrder<Symbol> DeclaredVariables = new SetWithInsertionOrder<Symbol>(); /// <summary> /// The bound node representing this scope. This roughly corresponds to the bound /// node for the block declaring locals for this scope, although parameters of /// methods/functions are introduced into their Body's scope and do not get their /// own scope. /// </summary> public readonly BoundNode BoundNode; /// <summary> /// The nested function that this scope is nested inside. Null if this scope is not nested /// inside a nested function. /// </summary> public readonly NestedFunction ContainingFunctionOpt; #nullable enable /// <summary> /// Environment created in this scope to hold <see cref="DeclaredVariables"/>. /// At the moment, all variables declared in the same scope /// always get assigned to the same environment. /// </summary> public ClosureEnvironment? DeclaredEnvironment = null; #nullable disable public Scope(Scope parent, BoundNode boundNode, NestedFunction containingFunction) { Debug.Assert(boundNode != null); Parent = parent; BoundNode = boundNode; ContainingFunctionOpt = containingFunction; } /// <summary> /// Is it safe to move any of the variables declared in this scope to the parent scope, /// or would doing so change the meaning of the program? /// </summary> public bool CanMergeWithParent { get; internal set; } = true; public void Free() { foreach (var scope in NestedScopes) { scope.Free(); } NestedScopes.Free(); foreach (var function in NestedFunctions) { function.Free(); } NestedFunctions.Free(); } public override string ToString() => BoundNode.Syntax.GetText().ToString(); } /// <summary> /// The NestedFunction type represents a lambda or local function and stores /// information related to that function. After initially building the /// <see cref="Scope"/> tree the only information available is /// <see cref="OriginalMethodSymbol"/> and <see cref="CapturedVariables"/>. /// Subsequent passes are responsible for translating captured /// variables into captured environments and for calculating /// the rewritten signature of the method. /// </summary> public sealed class NestedFunction { /// <summary> /// The method symbol for the original lambda or local function. /// </summary> public readonly MethodSymbol OriginalMethodSymbol; /// <summary> /// Syntax for the block of the nested function. /// </summary> public readonly SyntaxReference BlockSyntax; public readonly PooledHashSet<Symbol> CapturedVariables = PooledHashSet<Symbol>.GetInstance(); public readonly ArrayBuilder<ClosureEnvironment> CapturedEnvironments = ArrayBuilder<ClosureEnvironment>.GetInstance(); public ClosureEnvironment ContainingEnvironmentOpt; private bool _capturesThis; /// <summary> /// True if this function directly or transitively captures 'this' (captures /// a local function which directly or indirectly captures 'this'). /// Calculated in <see cref="MakeAndAssignEnvironments"/>. /// </summary> public bool CapturesThis { get => _capturesThis; set { Debug.Assert(value); _capturesThis = value; } } public SynthesizedClosureMethod SynthesizedLoweredMethod; public NestedFunction(MethodSymbol symbol, SyntaxReference blockSyntax) { Debug.Assert(symbol != null); OriginalMethodSymbol = symbol; BlockSyntax = blockSyntax; } public void Free() { CapturedVariables.Free(); CapturedEnvironments.Free(); } } public sealed class ClosureEnvironment { public readonly SetWithInsertionOrder<Symbol> CapturedVariables; /// <summary> /// True if this environment captures a reference to a class environment /// declared in a higher scope. Assigned by /// <see cref="ComputeLambdaScopesAndFrameCaptures()"/> /// </summary> public bool CapturesParent; public readonly bool IsStruct; internal SynthesizedClosureEnvironment SynthesizedEnvironment; public ClosureEnvironment(IEnumerable<Symbol> capturedVariables, bool isStruct) { CapturedVariables = new SetWithInsertionOrder<Symbol>(); foreach (var item in capturedVariables) { CapturedVariables.Add(item); } IsStruct = isStruct; } } /// <summary> /// Visit all nested functions in all nested scopes and run the <paramref name="action"/>. /// </summary> public static void VisitNestedFunctions(Scope scope, Action<Scope, NestedFunction> action) { foreach (var function in scope.NestedFunctions) { action(scope, function); } foreach (var nested in scope.NestedScopes) { VisitNestedFunctions(nested, action); } } /// <summary> /// Visit all the functions and return true when the <paramref name="func"/> returns /// true. Otherwise, returns false. /// </summary> public static bool CheckNestedFunctions(Scope scope, Func<Scope, NestedFunction, bool> func) { foreach (var function in scope.NestedFunctions) { if (func(scope, function)) { return true; } } foreach (var nested in scope.NestedScopes) { if (CheckNestedFunctions(nested, func)) { return true; } } return false; } /// <summary> /// Visit the tree with the given root and run the <paramref name="action"/> /// </summary> public static void VisitScopeTree(Scope treeRoot, Action<Scope> action) { action(treeRoot); foreach (var nested in treeRoot.NestedScopes) { VisitScopeTree(nested, action); } } /// <summary> /// Builds a tree of <see cref="Scope"/> nodes corresponding to a given method. /// <see cref="Build(BoundNode, MethodSymbol, HashSet{MethodSymbol}, DiagnosticBag)"/> /// visits the bound tree and translates information from the bound tree about /// variable scope, declared variables, and variable captures into the resulting /// <see cref="Scope"/> tree. /// /// At the same time it sets <see cref="Scope.CanMergeWithParent"/> /// for each Scope. This is done by looking for <see cref="BoundGotoStatement"/>s /// and <see cref="BoundConditionalGoto"/>s that jump from a point /// after the beginning of a <see cref="Scope"/>, to a <see cref="BoundLabelStatement"/> /// before the start of the scope, but after the start of <see cref="Scope.Parent"/>. /// /// All loops have been converted to gotos and labels by this stage, /// so we do not have to visit them to do so. Similarly all <see cref="BoundLabeledStatement"/>s /// have been converted to <see cref="BoundLabelStatement"/>s, so we do not have to /// visit them. /// </summary> private class ScopeTreeBuilder : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Do not set this directly, except when setting the root scope. /// Instead use <see cref="PopScope"/> or <see cref="CreateAndPushScope"/>. /// </summary> private Scope _currentScope; /// <summary> /// Null if we're not inside a nested function, otherwise the nearest nested function. /// </summary> private NestedFunction _currentFunction = null; private bool _inExpressionTree = false; /// <summary> /// A mapping from all captured vars to the scope they were declared in. This /// is used when recording captured variables as we must know what the lifetime /// of a captured variable is to determine the lifetime of its capture environment. /// </summary> private readonly SmallDictionary<Symbol, Scope> _localToScope = new SmallDictionary<Symbol, Scope>(); #if DEBUG /// <summary> /// Free variables are variables declared in expression statements that can then /// be captured in nested lambdas. Normally, captured variables must lowered as /// part of closure conversion, but expression tree variables are handled separately /// by the expression tree rewriter and are considered free for the purposes of /// closure conversion. For instance, an expression with a nested lambda, e.g. /// x => y => x + y /// contains an expression variable, x, that should not be treated as a captured /// variable to be replaced by closure conversion. Instead, it should be left for /// expression tree conversion. /// </summary> private readonly HashSet<Symbol> _freeVariables = new HashSet<Symbol>(); #endif private readonly MethodSymbol _topLevelMethod; /// <summary> /// If a local function is in the set, at some point in the code it is converted /// to a delegate and should then not be optimized to a struct closure. /// Also contains all lambdas (as they are converted to delegates implicitly). /// </summary> private readonly HashSet<MethodSymbol> _methodsConvertedToDelegates; private readonly DiagnosticBag _diagnostics; /// <summary> /// For every label visited so far, this dictionary maps to a list of all scopes either visited so far, or currently being visited, /// that are both after the label, and are on the same level of the scope tree as the label. /// </summary> private readonly PooledDictionary<LabelSymbol, ArrayBuilder<Scope>> _scopesAfterLabel = PooledDictionary<LabelSymbol, ArrayBuilder<Scope>>.GetInstance(); /// <summary> /// Contains a list of the labels visited so far for each scope. /// The outer ArrayBuilder is a stack representing the chain of scopes from the root scope to the current scope, /// and for each item on the stack, the ArrayBuilder is the list of the labels visited so far for the scope. /// /// Used by <see cref="CreateAndPushScope"/> to determine which labels a new child scope appears after. /// </summary> private readonly ArrayBuilder<ArrayBuilder<LabelSymbol>> _labelsInScope = ArrayBuilder<ArrayBuilder<LabelSymbol>>.GetInstance(); private ScopeTreeBuilder( Scope rootScope, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { Debug.Assert(rootScope != null); Debug.Assert(topLevelMethod != null); Debug.Assert(methodsConvertedToDelegates != null); Debug.Assert(diagnostics != null); _currentScope = rootScope; _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _topLevelMethod = topLevelMethod; _methodsConvertedToDelegates = methodsConvertedToDelegates; _diagnostics = diagnostics; } public static Scope Build( BoundNode node, MethodSymbol topLevelMethod, HashSet<MethodSymbol> methodsConvertedToDelegates, DiagnosticBag diagnostics) { // This should be the top-level node Debug.Assert(node == FindNodeToAnalyze(node)); Debug.Assert(topLevelMethod != null); var rootScope = new Scope(parent: null, boundNode: node, containingFunction: null); var builder = new ScopeTreeBuilder( rootScope, topLevelMethod, methodsConvertedToDelegates, diagnostics); builder.Build(); return rootScope; } private void Build() { // Set up the current method locals DeclareLocals(_currentScope, _topLevelMethod.Parameters); // Treat 'this' as a formal parameter of the top-level method if (_topLevelMethod.TryGetThisParameter(out var thisParam) && (object)thisParam != null) { DeclareLocals(_currentScope, ImmutableArray.Create<Symbol>(thisParam)); } Visit(_currentScope.BoundNode); // Clean Up Resources foreach (var scopes in _scopesAfterLabel.Values) { scopes.Free(); } _scopesAfterLabel.Free(); Debug.Assert(_labelsInScope.Count == 1); var labels = _labelsInScope.Pop(); labels.Free(); _labelsInScope.Free(); } public override BoundNode VisitMethodGroup(BoundMethodGroup node) => throw ExceptionUtilities.Unreachable; public override BoundNode VisitBlock(BoundBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitCatchBlock(node); PopScope(oldScope); return result; } public override BoundNode VisitSequence(BoundSequence node) { var oldScope = _currentScope; PushOrReuseScope(node, node.Locals); var result = base.VisitSequence(node); PopScope(oldScope); return result; } public override BoundNode VisitLambda(BoundLambda node) { var oldInExpressionTree = _inExpressionTree; _inExpressionTree |= node.Type.IsExpressionTree(); _methodsConvertedToDelegates.Add(node.Symbol.OriginalDefinition); var result = VisitNestedFunction(node.Symbol, node.Body); _inExpressionTree = oldInExpressionTree; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) => VisitNestedFunction(node.Symbol.OriginalDefinition, node.Body); public override BoundNode VisitCall(BoundCall node) { if (node.Method.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters AddIfCaptured(node.Method.OriginalDefinition, node.Syntax); } return base.VisitCall(node); } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction) { // Use OriginalDefinition to strip generic type parameters var method = node.MethodOpt.OriginalDefinition; AddIfCaptured(method, node.Syntax); _methodsConvertedToDelegates.Add(method); } return base.VisitDelegateCreationExpression(node); } public override BoundNode VisitParameter(BoundParameter node) { AddIfCaptured(node.ParameterSymbol, node.Syntax); return base.VisitParameter(node); } public override BoundNode VisitLocal(BoundLocal node) { AddIfCaptured(node.LocalSymbol, node.Syntax); return base.VisitLocal(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { AddIfCaptured(_topLevelMethod.ThisParameter, node.Syntax); return base.VisitBaseReference(node); } public override BoundNode VisitThisReference(BoundThisReference node) { var thisParam = _topLevelMethod.ThisParameter; if (thisParam != null) { AddIfCaptured(thisParam, node.Syntax); } else { // This can occur in a delegate creation expression because the method group // in the argument can have a "this" receiver even when "this" // is not captured because a static method is selected. But we do preserve // the method group and its receiver in the bound tree. // No need to capture "this" in such case. // TODO: Why don't we drop "this" while lowering if method is static? // Actually, considering that method group expression does not evaluate to a particular value // why do we have it in the lowered tree at all? } return base.VisitThisReference(node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { _labelsInScope.Peek().Add(node.Label); _scopesAfterLabel.Add(node.Label, ArrayBuilder<Scope>.GetInstance()); return base.VisitLabelStatement(node); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { CheckCanMergeWithParent(node.Label); return base.VisitGotoStatement(node); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { CheckCanMergeWithParent(node.Label); return base.VisitConditionalGoto(node); } /// <summary> /// This is where we calculate <see cref="Scope.CanMergeWithParent"/>. /// <see cref="Scope.CanMergeWithParent"/> is always true unless we jump from after /// the beginning of a scope, to a point in between the beginning of the parent scope, and the beginning of the scope /// </summary> /// <param name="jumpTarget"></param> private void CheckCanMergeWithParent(LabelSymbol jumpTarget) { // since forward jumps can never effect Scope.SemanticallySafeToMergeIntoParent // if we have not yet seen the jumpTarget, this is a forward jump, and can be ignored if (_scopesAfterLabel.TryGetValue(jumpTarget, out var scopesAfterLabel)) { foreach (var scope in scopesAfterLabel) { // this jump goes from a point after the beginning of the scope (as we have already visited or started visiting the scope), // to a point in between the beginning of the parent scope, and the beginning of the scope, so it is not safe to move // variables in the scope to the parent scope. scope.CanMergeWithParent = false; } // Prevent us repeating this process for all scopes if another jumps goes to the same label scopesAfterLabel.Clear(); } } #nullable enable private BoundNode? VisitNestedFunction(MethodSymbol functionSymbol, BoundBlock? body) { RoslynDebug.Assert(functionSymbol is object); if (body is null) { // extern closure _currentScope.NestedFunctions.Add(new NestedFunction(functionSymbol, blockSyntax: null)); return null; } // Nested function is declared (lives) in the parent scope, but its // variables are in a nested scope var function = new NestedFunction(functionSymbol, body.Syntax.GetReference()); _currentScope.NestedFunctions.Add(function); var oldFunction = _currentFunction; _currentFunction = function; var oldScope = _currentScope; CreateAndPushScope(body); // For the purposes of scoping, parameters live in the same scope as the // nested function block. Expression tree variables are free variables for the // purposes of closure conversion DeclareLocals(_currentScope, functionSymbol.Parameters, _inExpressionTree); var result = _inExpressionTree ? base.VisitBlock(body) : VisitBlock(body); PopScope(oldScope); _currentFunction = oldFunction; return result; } #nullable disable private void AddIfCaptured(Symbol symbol, SyntaxNode syntax) { Debug.Assert( symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol.Kind == SymbolKind.Method); if (_currentFunction == null) { // Can't be captured if we're not in a nested function return; } if (symbol is LocalSymbol local && local.IsConst) { // consts aren't captured since they're inlined return; } if (symbol is MethodSymbol method && _currentFunction.OriginalMethodSymbol == method) { // Is this recursion? If so there's no capturing return; } Debug.Assert(symbol.ContainingSymbol != null); if (symbol.ContainingSymbol != _currentFunction.OriginalMethodSymbol) { // Restricted types can't be hoisted, so they are not permitted to be captured AddDiagnosticIfRestrictedType(symbol, syntax); // Record the captured variable where it's captured var scope = _currentScope; var function = _currentFunction; while (function != null && symbol.ContainingSymbol != function.OriginalMethodSymbol) { function.CapturedVariables.Add(symbol); // Also mark captured in enclosing scopes while (scope.ContainingFunctionOpt == function) { scope = scope.Parent; } function = scope.ContainingFunctionOpt; } // Also record where the captured variable lives // No need to record where local functions live: that was recorded // in the NestedFunctions list in each scope if (symbol.Kind == SymbolKind.Method) { return; } if (_localToScope.TryGetValue(symbol, out var declScope)) { declScope.DeclaredVariables.Add(symbol); } else { #if DEBUG // Parameters and locals from expression tree lambdas // are free variables Debug.Assert(_freeVariables.Contains(symbol)); #endif } } } /// <summary> /// Add a diagnostic if the type of a captured variable is a restricted type /// </summary> private void AddDiagnosticIfRestrictedType(Symbol capturedVariable, SyntaxNode syntax) { TypeSymbol type; switch (capturedVariable.Kind) { case SymbolKind.Local: type = ((LocalSymbol)capturedVariable).Type; break; case SymbolKind.Parameter: type = ((ParameterSymbol)capturedVariable).Type; break; default: // This should only be called for captured variables, and captured // variables must be a method, parameter, or local symbol Debug.Assert(capturedVariable.Kind == SymbolKind.Method); return; } if (type.IsRestrictedType() == true) { _diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, type); } } /// <summary> /// Create a new nested scope under the current scope, and replace <see cref="_currentScope"/> with the new scope, /// or reuse the current scope if there's no change in the bound node for the nested scope. /// Records the given locals as declared in the aforementioned scope. /// </summary> private void PushOrReuseScope<TSymbol>(BoundNode node, ImmutableArray<TSymbol> locals) where TSymbol : Symbol { // We should never create a new scope with the same bound node. We can get into // this situation for methods and nested functions where a new scope is created // to add parameters and a new scope would be created for the method block, // despite the fact that they should be the same scope. if (!locals.IsEmpty && _currentScope.BoundNode != node) { CreateAndPushScope(node); } DeclareLocals(_currentScope, locals); } /// <summary> /// Creates a new nested scope which is a child of <see cref="_currentScope"/>, /// and replaces <see cref="_currentScope"/> with the new scope /// </summary> /// <param name="node"></param> private void CreateAndPushScope(BoundNode node) { var scope = CreateNestedScope(_currentScope, _currentFunction); foreach (var label in _labelsInScope.Peek()) { _scopesAfterLabel[label].Add(scope); } _labelsInScope.Push(ArrayBuilder<LabelSymbol>.GetInstance()); _currentScope = scope; Scope CreateNestedScope(Scope parentScope, NestedFunction currentFunction) { Debug.Assert(parentScope.BoundNode != node); var newScope = new Scope(parentScope, node, currentFunction); parentScope.NestedScopes.Add(newScope); return newScope; } } /// <summary> /// Requires that scope is either the same as <see cref="_currentScope"/>, /// or is the <see cref="Scope.Parent"/> of <see cref="_currentScope"/>. /// Returns immediately in the first case, /// Replaces <see cref="_currentScope"/> with scope in the second. /// </summary> /// <param name="scope"></param> private void PopScope(Scope scope) { if (scope == _currentScope) { return; } Debug.Assert(scope == _currentScope.Parent, $"{nameof(scope)} must be {nameof(_currentScope)} or {nameof(_currentScope)}.{nameof(_currentScope.Parent)}"); // Since it is forbidden to jump into a scope, // we can forget all information we have about labels in the child scope var labels = _labelsInScope.Pop(); foreach (var label in labels) { var scopes = _scopesAfterLabel[label]; scopes.Free(); _scopesAfterLabel.Remove(label); } labels.Free(); _currentScope = _currentScope.Parent; } private void DeclareLocals<TSymbol>(Scope scope, ImmutableArray<TSymbol> locals, bool declareAsFree = false) where TSymbol : Symbol { foreach (var local in locals) { Debug.Assert(!_localToScope.ContainsKey(local)); if (declareAsFree) { #if DEBUG Debug.Assert(_freeVariables.Add(local)); #endif } else { _localToScope.Add(local, scope); } } } } } } }
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/WithKeywordRecommenderTests.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.UnitTests.Recommendations.Statements Public Class WithKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Exit | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Continue | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Continue | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Exit | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitInsideLambdaInsideWithBlockTest() VerifyRecommendationsMissing(<MethodBody> While Dim x = Sub() Exit | End Sub Loop </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterExitInsideWhileLoopInsideLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() With x Exit | Loop End Sub </MethodBody>, "With") 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class WithKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Exit | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Continue | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Continue | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Exit | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitInsideLambdaInsideWithBlockTest() VerifyRecommendationsMissing(<MethodBody> While Dim x = Sub() Exit | End Sub Loop </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterExitInsideWhileLoopInsideLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() With x Exit | Loop End Sub </MethodBody>, "With") End Sub End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Tools/BuildValidator/BuildValidator.sln
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30905.15 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuildValidator", "BuildValidator.csproj", "{F3EDD192-7E74-441D-B096-16C0FE2731E3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild", "..\..\Compilers\Core\Rebuild\Microsoft.CodeAnalysis.Rebuild.csproj", "{04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild.UnitTests", "..\..\Compilers\Core\RebuildTest\Microsoft.CodeAnalysis.Rebuild.UnitTests.csproj", "{48B87FA3-669F-48D2-A23A-50E43D875C61}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Debug|Any CPU.Build.0 = Debug|Any CPU {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Release|Any CPU.ActiveCfg = Release|Any CPU {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Release|Any CPU.Build.0 = Release|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Debug|Any CPU.Build.0 = Debug|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Release|Any CPU.ActiveCfg = Release|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Release|Any CPU.Build.0 = Release|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Debug|Any CPU.Build.0 = Debug|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Release|Any CPU.ActiveCfg = Release|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B7279C10-0E1A-43B3-B6E8-DB13A0795EDE} EndGlobalSection EndGlobal
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30905.15 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuildValidator", "BuildValidator.csproj", "{F3EDD192-7E74-441D-B096-16C0FE2731E3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild", "..\..\Compilers\Core\Rebuild\Microsoft.CodeAnalysis.Rebuild.csproj", "{04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild.UnitTests", "..\..\Compilers\Core\RebuildTest\Microsoft.CodeAnalysis.Rebuild.UnitTests.csproj", "{48B87FA3-669F-48D2-A23A-50E43D875C61}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Debug|Any CPU.Build.0 = Debug|Any CPU {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Release|Any CPU.ActiveCfg = Release|Any CPU {F3EDD192-7E74-441D-B096-16C0FE2731E3}.Release|Any CPU.Build.0 = Release|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Debug|Any CPU.Build.0 = Debug|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Release|Any CPU.ActiveCfg = Release|Any CPU {04CCBB7F-B1E3-4E76-A4A7-C648EBE77CBB}.Release|Any CPU.Build.0 = Release|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Debug|Any CPU.Build.0 = Debug|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Release|Any CPU.ActiveCfg = Release|Any CPU {48B87FA3-669F-48D2-A23A-50E43D875C61}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B7279C10-0E1A-43B3-B6E8-DB13A0795EDE} EndGlobalSection EndGlobal
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/EditorFeatures/Test/ServicesCoreTest.Debug.xunit
<xunit> <assemblies> <assembly filename="..\..\..\..\Binaries\Debug\Roslyn.Services.Editor.UnitTests.dll" shadow-copy="false"/> </assemblies> </xunit>
<xunit> <assemblies> <assembly filename="..\..\..\..\Binaries\Debug\Roslyn.Services.Editor.UnitTests.dll" shadow-copy="false"/> </assemblies> </xunit>
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/VisualBasic/Portable/MakeMethodSynchronous/VisualBasicMakeMethodSynchronousCodeFixProvider.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 Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.MakeMethodAsynchronous.AbstractMakeMethodAsynchronousCodeFixProvider Imports Microsoft.CodeAnalysis.MakeMethodSynchronous Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.MakeMethodSynchronous <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.MakeMethodSynchronous), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.AddImport)> Friend Class VisualBasicMakeMethodSynchronousCodeFixProvider Inherits AbstractMakeMethodSynchronousCodeFixProvider Private Const BC42356 As String = NameOf(BC42356) ' This async method lacks 'Await' operators and so will run synchronously. Private Shared ReadOnly s_diagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC42356) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return s_diagnosticIds End Get End Property Protected Overrides Function IsAsyncSupportingFunctionSyntax(node As SyntaxNode) As Boolean Return node.IsAsyncSupportedFunctionSyntax() End Function Protected Overrides Function RemoveAsyncTokenAndFixReturnType(methodSymbolOpt As IMethodSymbol, node As SyntaxNode, knownTypes As KnownTypes) As SyntaxNode If node.IsKind(SyntaxKind.SingleLineSubLambdaExpression) OrElse node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) Then Return RemoveAsyncModifierHelpers.FixSingleLineLambdaExpression(DirectCast(node, SingleLineLambdaExpressionSyntax)) ElseIf node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) OrElse node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) Then Return RemoveAsyncModifierHelpers.FixMultiLineLambdaExpression(DirectCast(node, MultiLineLambdaExpressionSyntax)) ElseIf node.IsKind(SyntaxKind.SubBlock) Then Return FixSubBlock(DirectCast(node, MethodBlockSyntax)) Else Return FixFunctionBlock(methodSymbolOpt, DirectCast(node, MethodBlockSyntax), knownTypes) End If End Function Private Shared Function FixFunctionBlock(methodSymbol As IMethodSymbol, node As MethodBlockSyntax, knownTypes As KnownTypes) As SyntaxNode Dim functionStatement = node.SubOrFunctionStatement ' if this returns Task(of T), then we want to convert this to a T returning function. ' if this returns Task, then we want to convert it to a Sub method. If methodSymbol.ReturnType.OriginalDefinition.Equals(knownTypes._taskOfTType) Then Dim newAsClause = functionStatement.AsClause.WithType(methodSymbol.ReturnType.GetTypeArguments()(0).GenerateTypeSyntax()) Dim newFunctionStatement = functionStatement.WithAsClause(newAsClause) newFunctionStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(newFunctionStatement) Return node.WithSubOrFunctionStatement(newFunctionStatement) ElseIf Equals(methodSymbol.ReturnType.OriginalDefinition, knownTypes._taskType) Then ' Convert this to a 'Sub' method. Dim subStatement = SyntaxFactory.SubStatement( functionStatement.AttributeLists, functionStatement.Modifiers, SyntaxFactory.Token(SyntaxKind.SubKeyword).WithTriviaFrom(functionStatement.SubOrFunctionKeyword), functionStatement.Identifier, functionStatement.TypeParameterList, functionStatement.ParameterList, functionStatement.AsClause, functionStatement.HandlesClause, functionStatement.ImplementsClause) subStatement = subStatement.RemoveNode(subStatement.AsClause, SyntaxRemoveOptions.KeepTrailingTrivia) subStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(subStatement) Dim endSubStatement = SyntaxFactory.EndSubStatement( node.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(SyntaxKind.SubKeyword).WithTriviaFrom(node.EndSubOrFunctionStatement.BlockKeyword)) Return SyntaxFactory.SubBlock(subStatement, node.Statements, endSubStatement) Else Dim newFunctionStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(functionStatement) Return node.WithSubOrFunctionStatement(newFunctionStatement) End If End Function Private Shared Function FixSubBlock(node As MethodBlockSyntax) As SyntaxNode Dim newSubStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(node.SubOrFunctionStatement) Return node.WithSubOrFunctionStatement(newSubStatement) 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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.MakeMethodAsynchronous.AbstractMakeMethodAsynchronousCodeFixProvider Imports Microsoft.CodeAnalysis.MakeMethodSynchronous Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.MakeMethodSynchronous <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.MakeMethodSynchronous), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.AddImport)> Friend Class VisualBasicMakeMethodSynchronousCodeFixProvider Inherits AbstractMakeMethodSynchronousCodeFixProvider Private Const BC42356 As String = NameOf(BC42356) ' This async method lacks 'Await' operators and so will run synchronously. Private Shared ReadOnly s_diagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC42356) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return s_diagnosticIds End Get End Property Protected Overrides Function IsAsyncSupportingFunctionSyntax(node As SyntaxNode) As Boolean Return node.IsAsyncSupportedFunctionSyntax() End Function Protected Overrides Function RemoveAsyncTokenAndFixReturnType(methodSymbolOpt As IMethodSymbol, node As SyntaxNode, knownTypes As KnownTypes) As SyntaxNode If node.IsKind(SyntaxKind.SingleLineSubLambdaExpression) OrElse node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) Then Return RemoveAsyncModifierHelpers.FixSingleLineLambdaExpression(DirectCast(node, SingleLineLambdaExpressionSyntax)) ElseIf node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) OrElse node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) Then Return RemoveAsyncModifierHelpers.FixMultiLineLambdaExpression(DirectCast(node, MultiLineLambdaExpressionSyntax)) ElseIf node.IsKind(SyntaxKind.SubBlock) Then Return FixSubBlock(DirectCast(node, MethodBlockSyntax)) Else Return FixFunctionBlock(methodSymbolOpt, DirectCast(node, MethodBlockSyntax), knownTypes) End If End Function Private Shared Function FixFunctionBlock(methodSymbol As IMethodSymbol, node As MethodBlockSyntax, knownTypes As KnownTypes) As SyntaxNode Dim functionStatement = node.SubOrFunctionStatement ' if this returns Task(of T), then we want to convert this to a T returning function. ' if this returns Task, then we want to convert it to a Sub method. If methodSymbol.ReturnType.OriginalDefinition.Equals(knownTypes._taskOfTType) Then Dim newAsClause = functionStatement.AsClause.WithType(methodSymbol.ReturnType.GetTypeArguments()(0).GenerateTypeSyntax()) Dim newFunctionStatement = functionStatement.WithAsClause(newAsClause) newFunctionStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(newFunctionStatement) Return node.WithSubOrFunctionStatement(newFunctionStatement) ElseIf Equals(methodSymbol.ReturnType.OriginalDefinition, knownTypes._taskType) Then ' Convert this to a 'Sub' method. Dim subStatement = SyntaxFactory.SubStatement( functionStatement.AttributeLists, functionStatement.Modifiers, SyntaxFactory.Token(SyntaxKind.SubKeyword).WithTriviaFrom(functionStatement.SubOrFunctionKeyword), functionStatement.Identifier, functionStatement.TypeParameterList, functionStatement.ParameterList, functionStatement.AsClause, functionStatement.HandlesClause, functionStatement.ImplementsClause) subStatement = subStatement.RemoveNode(subStatement.AsClause, SyntaxRemoveOptions.KeepTrailingTrivia) subStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(subStatement) Dim endSubStatement = SyntaxFactory.EndSubStatement( node.EndSubOrFunctionStatement.EndKeyword, SyntaxFactory.Token(SyntaxKind.SubKeyword).WithTriviaFrom(node.EndSubOrFunctionStatement.BlockKeyword)) Return SyntaxFactory.SubBlock(subStatement, node.Statements, endSubStatement) Else Dim newFunctionStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(functionStatement) Return node.WithSubOrFunctionStatement(newFunctionStatement) End If End Function Private Shared Function FixSubBlock(node As MethodBlockSyntax) As SyntaxNode Dim newSubStatement = RemoveAsyncModifierHelpers.RemoveAsyncKeyword(node.SubOrFunctionStatement) Return node.WithSubOrFunctionStatement(newSubStatement) End Function End Class End Namespace
-1
dotnet/roslyn
55,023
Add generator driver cache to VBCSCompiler
- Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
chsienki
2021-07-21T20:04:49Z
2021-08-31T17:58:33Z
94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
Add generator driver cache to VBCSCompiler. - Create a new cache type - Make the compiler optionally take it - Pass in the cache when running on the server - Check the cache (if there is one) for a generator driver before creating a new one This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators.
./src/Features/CSharp/Portable/MetadataAsSource/FormattingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.MetadataAsSource { internal partial class CSharpMetadataAsSourceService { private class FormattingRule : AbstractMetadataFormattingRule { protected override AdjustNewLinesOperation GetAdjustNewLinesOperationBetweenMembersAndUsings(SyntaxToken token1, SyntaxToken token2) { var previousToken = token1; var currentToken = token2; // We are not between members or usings if the last token wasn't the end of a statement or if the current token // is the end of a scope. if ((previousToken.Kind() != SyntaxKind.SemicolonToken && previousToken.Kind() != SyntaxKind.CloseBraceToken) || currentToken.Kind() == SyntaxKind.CloseBraceToken) { return null; } SyntaxNode previousMember = FormattingRangeHelper.GetEnclosingMember(previousToken); SyntaxNode nextMember = FormattingRangeHelper.GetEnclosingMember(currentToken); // Is the previous statement an using directive? If so, treat it like a member to add // the right number of lines. if (previousToken.Kind() == SyntaxKind.SemicolonToken && previousToken.Parent.Kind() == SyntaxKind.UsingDirective) { previousMember = previousToken.Parent; } if (previousMember == null || nextMember == null || previousMember == nextMember) { return null; } // If we have two members of the same kind, we won't insert a blank line if (previousMember.Kind() == nextMember.Kind()) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines); } // Force a blank line between the two nodes by counting the number of lines of // trivia and adding one to it. var triviaList = token1.TrailingTrivia.Concat(token2.LeadingTrivia); return FormattingOperations.CreateAdjustNewLinesOperation(GetNumberOfLines(triviaList) + 1, AdjustNewLinesOption.ForceLines); } public override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation) { return; } protected override bool IsNewLine(char c) => SyntaxFacts.IsNewLine(c); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.MetadataAsSource { internal partial class CSharpMetadataAsSourceService { private class FormattingRule : AbstractMetadataFormattingRule { protected override AdjustNewLinesOperation GetAdjustNewLinesOperationBetweenMembersAndUsings(SyntaxToken token1, SyntaxToken token2) { var previousToken = token1; var currentToken = token2; // We are not between members or usings if the last token wasn't the end of a statement or if the current token // is the end of a scope. if ((previousToken.Kind() != SyntaxKind.SemicolonToken && previousToken.Kind() != SyntaxKind.CloseBraceToken) || currentToken.Kind() == SyntaxKind.CloseBraceToken) { return null; } SyntaxNode previousMember = FormattingRangeHelper.GetEnclosingMember(previousToken); SyntaxNode nextMember = FormattingRangeHelper.GetEnclosingMember(currentToken); // Is the previous statement an using directive? If so, treat it like a member to add // the right number of lines. if (previousToken.Kind() == SyntaxKind.SemicolonToken && previousToken.Parent.Kind() == SyntaxKind.UsingDirective) { previousMember = previousToken.Parent; } if (previousMember == null || nextMember == null || previousMember == nextMember) { return null; } // If we have two members of the same kind, we won't insert a blank line if (previousMember.Kind() == nextMember.Kind()) { return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines); } // Force a blank line between the two nodes by counting the number of lines of // trivia and adding one to it. var triviaList = token1.TrailingTrivia.Concat(token2.LeadingTrivia); return FormattingOperations.CreateAdjustNewLinesOperation(GetNumberOfLines(triviaList) + 1, AdjustNewLinesOption.ForceLines); } public override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation) { return; } protected override bool IsNewLine(char c) => SyntaxFacts.IsNewLine(c); } } }
-1