{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n"},"after_content":{"kind":"string","value":"\n\n \n \n \n Namespace can not be added in this destination.\n Obor názvů nejde přidat do tohoto cílového umístění.\n \n \n \n Only attributes, expressions or statements can be made explicit\n Jako explicitní jde nastavit jenom atributy, výrazy nebo příkazy.\n \n \n \n R&amp;emove and Sort Imports\n &amp;Odebrat a seřadit importy\n \n \n \n &amp;Sort Imports\n &amp;Seřadit importy\n \n \n \n &lt;event&gt;\n &lt;událost&gt;\n \n \n \n &lt;handler&gt;\n &lt;obslužná_rutina&gt;\n \n \n \n The expression to be evaluated and converted.\n Výraz k vyhodnocení a převedení\n \n \n \n The name of the data type to which the value of expression will be converted.\n Název datového typu, na který se převede hodnota výrazu\n \n \n \n &lt;expression&gt;\n &lt;výraz&gt;\n \n \n \n &lt;typeName&gt;\n &lt;typeName&gt;\n \n \n \n Associates an event with an event handler, delegate or lambda expression at run time.\n Za běhu přidruží událost k obslužné rutině události, delegátu nebo lambda výrazu.\n \n \n \n The event to associate an event handler, delegate or lambda expression with.\n Událost, ke které se má přidružit obslužná rutina události, delegát nebo lambda výraz\n \n \n \n The event handler to associate with the event. This may take the form of { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; | &lt;lambdaExpression&gt; }.\n Obslužná rutina události, která se má přidružit k události. Může být ve tvaru { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; | &lt;lambdaExpression&gt; }.\n \n \n \n If &lt;expression&gt; evaluates to a reference or Nullable value that is not Nothing, the function returns that value. Otherwise, it calculates and returns &lt;expressionIfNothing&gt;.\n Pokud se &lt;výraz&gt; vyhodnotí jako odkaz nebo hodnota s možnou hodnotou null, která není Nothing, funkce vrátí tuto hodnotu. Jinak vypočítá a vrátí &lt;výraz_pokud_Nothing&gt;.\n \n \n \n Returned if it evaluates to a reference or nullable type that is not Nothing.\n Vrátí se, pokud se vyhodnotí na odkaz nebo typ s možnou hodnotou null, který není Nothing.\n \n \n \n Evaluated and returned if &lt;expression&gt; evaluates to Nothing.\n Vyhodnotí se a vrátí se, pokud se &lt;výraz&gt; vyhodnotí jako Nothing.\n \n \n \n &lt;expressionIfNothing&gt;\n &lt;expressionIfNothing&gt;\n \n \n \n Returns the result of explicitly converting an expression to a specified data type.\n Vrací výsledek explicitně převedeného výrazu na zadaný datový typ, objekt, strukturu, třídu nebo rozhraní.\n \n \n \n Introduces a type conversion operation similar to CType. The difference is that CType succeeds as long as there is a valid conversion, whereas DirectCast requires that one type inherit from or implement the other type.\n Zavádí operaci převodu typu podobnou k CType. Rozdíl je v tom, že CType uspěje, pokud existuje platný převod, zatímco DirectCast vyžaduje, aby jeden typ dědil z dalšího typu nebo implementoval další typ.\n \n \n \n The type name to return a System.Type object for.\n Název typu, pro který se má vrátit objekt System.Type\n \n \n \n Returns a System.Type object for the specified type name.\n Vrátí objekt System.Type pro zadaný název typu.\n \n \n \n The XML namespace prefix to return a System.Xml.Linq.XNamespace object for. If this is omitted, the object for the default XML namespace is returned.\n Předpona názvového prostoru XML, pro kterou se má vracet objekt System.Xml.Linq.XNamespace. Pokud není určená, vrátí se objekt pro výchozí názvový prostor XML.\n \n \n \n &lt;xmlNamespacePrefix&gt;\n &lt;předpona_názvového_prostoru_XML&gt;\n \n \n \n Returns the System.Xml.Linq.XNamespace object corresponding to the specified XML namespace prefix.\n Vrátí objekt System.Xml.XLinq.XNamespace odpovídající zadané předponě názvového prostoru XML.\n \n \n \n Replaces a specified number of characters in a String variable with characters from another string.\n Nahradí určitý počet znaků v proměnné typu Řetězec znaky z jiného řetězce.\n \n \n \n The name of the string variable to modify.\n Název proměnné řetězce k úpravě\n \n \n \n The one-based character position in the string where the replacement of text begins.\n Pozice znaku se základem 1 v řetězci, kde začne nahrazování textu\n \n \n \n The number of characters to replace. If omitted, the length of &lt;stringExpression&gt; is used.\n Počet znaků k nahrazení. Pokud není určený, použije se délka &lt;výraz_řetězce&gt;.\n \n \n \n &lt;stringName&gt;\n &lt;stringName&gt;\n \n \n \n &lt;startIndex&gt;\n &lt;startIndex&gt;\n \n \n \n &lt;length&gt;\n &lt;délka&gt;\n \n \n \n &lt;stringExpression&gt;\n &lt;výraz_řetězce&gt;\n \n \n \n Converts an expression to the {0} data type.\n Převede výraz na datový typ {0}.\n \n \n \n Removes the association between an event and an event handler or delegate at run time.\n Za běhu odebere přidružení mezi událostí a obslužnou rutinou události nebo delegátem.\n \n \n \n The event to disassociate an event handler or delegate from.\n Událost, u které se má zrušit přidružení obslužné rutiny události nebo delegáta\n \n \n \n The event handler to disassociate from the event. This may take the form of { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; }.\n Obslužná rutina události, jejíž přidružení k události se má zrušit. Může být ve tvaru { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; }.\n \n \n \n If &lt;condition&gt; returns True, the function calculates and returns &lt;expressionIfTrue&gt;. Otherwise, it returns &lt;expressionIfFalse&gt;.\n Pokud &lt;condition&gt; vrátí True, funkce vypočítá a vrátí &lt;expressionIfTrue&gt;. Jinak vrátí &lt;expressionIfFalse&gt;.\n \n \n \n The expression to evaluate.\n Výraz k vyhodnocení\n \n \n \n Evaluated and returned if &lt;condition&gt; evaluates to True.\n Vyhodnotí se a vrátí se, pokud se &lt;podmínka&gt; vyhodnotí jako True.\n \n \n \n Evaluated and returned if &lt;condition&gt; evaluates to False.\n Vyhodnotí se a vrátí se, pokud se &lt;podmínka&gt; vyhodnotí jako False.\n \n \n \n &lt;condition&gt;\n &lt;podmínka&gt;\n \n \n \n &lt;expressionIfTrue&gt;\n &lt;expressionIfTrue&gt;\n \n \n \n &lt;expressionIfFalse&gt;\n &lt;expressionIfFalse&gt;\n \n \n \n Introduces a type conversion operation that does not throw an exception. If an attempted conversion fails, TryCast returns Nothing, which your program can test for.\n Zavádí operaci převodu typu, která nevyvolá výjimku. Pokud se pokus o převod nezdaří, TryCast vrací hodnotu Nothing, kterou může váš program testovat.\n \n \n \n Node does not descend from root.\n Uzel nesestupuje z kořene.\n \n \n \n Node not in parent's child list\n Uzel není v seznamu podřízených položek u nadřazené položky.\n \n \n \n Trivia is not associated with token\n Triviální prvek není přidružený k tokenu.\n \n \n \n &lt;typeOrMember&gt;\n &lt;typeOrMember&gt;\n \n \n \n The type of member to return the name of.\n Typ člena, jehož název se má vrátit\n \n \n \n Produces a string for the name of the specified type or member.\n Vytvoří řetězec názvu určeného typu nebo člena.\n \n \n \n &lt;result&gt;\n &lt;výsledek&gt;\n \n \n \n \n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":405,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Analyzers/CSharp/Tests/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeFixes;\nusing Microsoft.CodeAnalysis.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.CSharp.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic\n{\n public partial class MakeLocalFunctionStaticTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest\n {\n public MakeLocalFunctionStaticTests(ITestOutputHelper logger)\n : base(logger)\n {\n }\n\n internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)\n => (new MakeLocalFunctionStaticDiagnosticAnalyzer(), GetMakeLocalFunctionStaticCodeFixProvider());\n\n private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2);\n private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8);\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestAboveCSharp8()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseSimpleUsingStatement)]\n public async Task TestWithOptionOff()\n {\n await TestMissingInRegularAndScriptAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nnew TestParameters(\n parseOptions: CSharp8ParseOptions,\n options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement)));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingIfAlreadyStatic()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n static int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingPriorToCSharp8()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp72ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingIfCapturesValue()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M(int i)\n {\n int [||]fibonacci(int n)\n {\n return i <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingIfCapturesThis()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n M();\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestAsyncFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n async Task [||]fibonacci(int n)\n {\n return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2);\n }\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n static async Task fibonacci(int n)\n {\n return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterSemicolon(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n int x;{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n int x;\n\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterOpenBrace(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterLocalFunction(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n bool otherFunction()\n {{\n return true;\n }}{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n bool otherFunction()\n {\n return true;\n }\n\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterExpressionBodyLocalFunction(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n bool otherFunction() => true;{leadingTrivia}\n int [||]fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n bool otherFunction() => true;\n\n static int fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterComment(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n //Local function comment{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n //Local function comment{leadingTrivia}\n static int fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaBeforeComment(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{{leadingTrivia}\n //Local function comment\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n$@\"using System;\n\nclass C\n{{\n void M()\n {{{leadingTrivia}\n //Local function comment\n static int fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [WorkItem(46858, \"https://github.com/dotnet/roslyn/issues/46858\")]\n public async Task TestMissingIfAnotherLocalFunctionCalled()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n void [||]A()\n {\n B();\n }\n\n void B()\n {\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallingStaticLocalFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n void [||]A()\n {\n B();\n }\n\n static void B()\n {\n }\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n static void A()\n {\n B();\n }\n\n static void B()\n {\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallingNestedLocalFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n void [||]A()\n {\n B();\n\n void B()\n {\n }\n }\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n static void A()\n {\n B();\n\n void B()\n {\n }\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeFixes;\nusing Microsoft.CodeAnalysis.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.CSharp.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic\n{\n public partial class MakeLocalFunctionStaticTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest\n {\n public MakeLocalFunctionStaticTests(ITestOutputHelper logger)\n : base(logger)\n {\n }\n\n internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)\n => (new MakeLocalFunctionStaticDiagnosticAnalyzer(), GetMakeLocalFunctionStaticCodeFixProvider());\n\n private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2);\n private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8);\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestAboveCSharp8()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseSimpleUsingStatement)]\n public async Task TestWithOptionOff()\n {\n await TestMissingInRegularAndScriptAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nnew TestParameters(\n parseOptions: CSharp8ParseOptions,\n options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement)));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingIfAlreadyStatic()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n static int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingPriorToCSharp8()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp72ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingIfCapturesValue()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M(int i)\n {\n int [||]fibonacci(int n)\n {\n return i <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMissingIfCapturesThis()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n int [||]fibonacci(int n)\n {\n M();\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestAsyncFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n async Task [||]fibonacci(int n)\n {\n return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2);\n }\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n static async Task fibonacci(int n)\n {\n return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterSemicolon(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n int x;{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n int x;\n\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterOpenBrace(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterLocalFunction(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n bool otherFunction()\n {{\n return true;\n }}{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n bool otherFunction()\n {\n return true;\n }\n\n static int fibonacci(int n)\n {\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterExpressionBodyLocalFunction(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n bool otherFunction() => true;{leadingTrivia}\n int [||]fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n}}\",\n@\"using System;\n\nclass C\n{\n void M()\n {\n bool otherFunction() => true;\n\n static int fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\")]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaAfterComment(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n //Local function comment{leadingTrivia}\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n$@\"using System;\n\nclass C\n{{\n void M()\n {{\n //Local function comment{leadingTrivia}\n static int fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [InlineData(\"\\r\\n\")]\n [InlineData(\"\\r\\n\\r\\n\")]\n public async Task TestLeadingTriviaBeforeComment(string leadingTrivia)\n {\n await TestInRegularAndScriptAsync(\n$@\"using System;\n\nclass C\n{{\n void M()\n {{{leadingTrivia}\n //Local function comment\n int [||]fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\n$@\"using System;\n\nclass C\n{{\n void M()\n {{{leadingTrivia}\n //Local function comment\n static int fibonacci(int n)\n {{\n return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);\n }}\n }}\n}}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [WorkItem(46858, \"https://github.com/dotnet/roslyn/issues/46858\")]\n public async Task TestMissingIfAnotherLocalFunctionCalled()\n {\n await TestMissingAsync(\n@\"using System;\n\nclass C\n{\n void M()\n {\n void [||]A()\n {\n B();\n }\n\n void B()\n {\n }\n }\n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallingStaticLocalFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n void [||]A()\n {\n B();\n }\n\n static void B()\n {\n }\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n static void A()\n {\n B();\n }\n\n static void B()\n {\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallingNestedLocalFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n void [||]A()\n {\n B();\n\n void B()\n {\n }\n }\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass C\n{\n void M()\n {\n static void A()\n {\n B();\n\n void B()\n {\n }\n }\n }\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [WorkItem(53179, \"https://github.com/dotnet/roslyn/issues/53179\")]\n public async Task TestLocalFunctionAsTopLevelStatement()\n {\n await TestAsync(@\"\nvoid [||]A()\n{\n}\", @\"\nstatic void A()\n{\n}\",\nparseOptions: CSharp8ParseOptions);\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":406,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/EditorFeatures/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticRefactoringTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeRefactorings;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic;\nusing Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic\n{\n public class MakeLocalFunctionStaticRefactoringTests : AbstractCSharpCodeActionTest\n {\n protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)\n => new MakeLocalFunctionStaticCodeRefactoringProvider();\n\n private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2);\n private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8);\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerForCSharp7()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp72ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfNoCaptures()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n int [||]AddLocal(int x)\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfAlreadyStatic()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n static int [||]AddLocal(int x)\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfAlreadyStaticWithError()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n static int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfCapturesThisParameter()\n {\n await TestMissingAsync(\n@\"class C\n{\n int x;\n\n int N()\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldTriggerIfExplicitlyPassedInThisParameter()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int x;\n\n int N()\n {\n int y;\n return AddLocal(this);\n\n int [||]AddLocal(C c)\n {\n return c.x + y;\n }\n } \n}\",\n@\"class C\n{\n int x;\n\n int N()\n {\n int y;\n return AddLocal(this, y);\n\n static int [||]AddLocal(C c, int y)\n {\n return c.x + y;\n }\n } \n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldTriggerForCSharp8()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\",\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n static int AddLocal(int x)\n {\n return x + 1;\n }\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMultipleVariables()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal();\n\n int[||] AddLocal()\n {\n return x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(x, y);\n\n static int AddLocal(int x, int y)\n {\n return x + y;\n }\n }\n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMultipleCalls()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal() + AddLocal();\n\n int[||] AddLocal()\n {\n return x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(x, y) + AddLocal(x, y);\n\n static int AddLocal(int x, int y)\n {\n return x + y;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMultipleCallsWithExistingParameters()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2);\n return AddLocal(m, m);\n\n int[||] AddLocal(int a, int b)\n {\n return a + b + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2, x, y);\n return AddLocal(m, m, x, y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return a + b + x + y;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestRecursiveCall()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2);\n return AddLocal(m, m);\n\n int[||] AddLocal(int a, int b)\n {\n return AddLocal(a, b) + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2, x, y);\n return AddLocal(m, m, x, y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return AddLocal(a, b, x, y) + x + y;\n }\n }\n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallInArgumentList()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(AddLocal(1, 2), AddLocal(3, 4));\n\n int[||] AddLocal(int a, int b)\n {\n return AddLocal(a, b) + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(AddLocal(1, 2, x, y), AddLocal(3, 4, x, y), x, y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return AddLocal(a, b, x, y) + x + y;\n }\n }\n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallsWithNamedArguments()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, b: 2);\n return AddLocal(b: m, a: m);\n\n int[||] AddLocal(int a, int b)\n {\n return a + b + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, b: 2, x: x, y: y);\n return AddLocal(b: m, a: m, x: x, y: y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return a + b + x + y;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallsWithDafaultValue()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n string y = \"\";\n var m = AddLocal(1);\n return AddLocal(b: m);\n\n int[||] AddLocal(int a = 0, int b = 0)\n {\n return a + b + x + y.Length;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n string y = \"\";\n var m = AddLocal(1, x: x, y: y);\n return AddLocal(b: m, x: x, y: y);\n\n static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null)\n {\n return a + b + x + y.Length;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestWarningAnnotation()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n void N(int x)\n {\n Func del = AddLocal;\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\",\n@\"class C\n{\n void N(int x)\n {\n Func del = AddLocal;\n\n {|Warning:static int AddLocal(int x)\n {\n return x + 1;\n }|}\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestNonCamelCaseCapture()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int Static = 0;\n return AddLocal();\n\n int [||]AddLocal()\n {\n return Static + 1;\n }\n } \n}\",\n@\"class C\n{\n int N(int x)\n {\n int Static = 0;\n return AddLocal(Static);\n\n static int AddLocal(int @static)\n {\n return @static + 1;\n }\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [WorkItem(46858, \"https://github.com/dotnet/roslyn/issues/46858\")]\n public async Task ShouldNotTriggerIfCallsOtherLocalFunction()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n B();\n return x + 1;\n }\n \n void B()\n {\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallingStaticLocationFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n B();\n return x + 1;\n }\n \n static void B()\n {\n }\n } \n}\",\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n static int [||]AddLocal(int x)\n {\n B();\n return x + 1;\n }\n \n static void B()\n {\n }\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n }\n}\n\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeRefactorings;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic;\nusing Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic\n{\n public class MakeLocalFunctionStaticRefactoringTests : AbstractCSharpCodeActionTest\n {\n protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)\n => new MakeLocalFunctionStaticCodeRefactoringProvider();\n\n private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2);\n private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8);\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerForCSharp7()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp72ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfNoCaptures()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n int [||]AddLocal(int x)\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfAlreadyStatic()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n static int [||]AddLocal(int x)\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfAlreadyStaticWithError()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n static int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldNotTriggerIfCapturesThisParameter()\n {\n await TestMissingAsync(\n@\"class C\n{\n int x;\n\n int N()\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldTriggerIfExplicitlyPassedInThisParameter()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int x;\n\n int N()\n {\n int y;\n return AddLocal(this);\n\n int [||]AddLocal(C c)\n {\n return c.x + y;\n }\n } \n}\",\n@\"class C\n{\n int x;\n\n int N()\n {\n int y;\n return AddLocal(this, y);\n\n static int [||]AddLocal(C c, int y)\n {\n return c.x + y;\n }\n } \n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task ShouldTriggerForCSharp8()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\",\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n static int AddLocal(int x)\n {\n return x + 1;\n }\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMultipleVariables()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal();\n\n int[||] AddLocal()\n {\n return x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(x, y);\n\n static int AddLocal(int x, int y)\n {\n return x + y;\n }\n }\n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMultipleCalls()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal() + AddLocal();\n\n int[||] AddLocal()\n {\n return x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(x, y) + AddLocal(x, y);\n\n static int AddLocal(int x, int y)\n {\n return x + y;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestMultipleCallsWithExistingParameters()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2);\n return AddLocal(m, m);\n\n int[||] AddLocal(int a, int b)\n {\n return a + b + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2, x, y);\n return AddLocal(m, m, x, y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return a + b + x + y;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestRecursiveCall()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2);\n return AddLocal(m, m);\n\n int[||] AddLocal(int a, int b)\n {\n return AddLocal(a, b) + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, 2, x, y);\n return AddLocal(m, m, x, y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return AddLocal(a, b, x, y) + x + y;\n }\n }\n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallInArgumentList()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(AddLocal(1, 2), AddLocal(3, 4));\n\n int[||] AddLocal(int a, int b)\n {\n return AddLocal(a, b) + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n return AddLocal(AddLocal(1, 2, x, y), AddLocal(3, 4, x, y), x, y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return AddLocal(a, b, x, y) + x + y;\n }\n }\n}\", parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallsWithNamedArguments()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, b: 2);\n return AddLocal(b: m, a: m);\n\n int[||] AddLocal(int a, int b)\n {\n return a + b + x + y;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n int y = 10;\n var m = AddLocal(1, b: 2, x: x, y: y);\n return AddLocal(b: m, a: m, x: x, y: y);\n\n static int AddLocal(int a, int b, int x, int y)\n {\n return a + b + x + y;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallsWithDafaultValue()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n string y = \"\";\n var m = AddLocal(1);\n return AddLocal(b: m);\n\n int[||] AddLocal(int a = 0, int b = 0)\n {\n return a + b + x + y.Length;\n }\n }\n}\",\n@\"class C\n{\n int N(int x)\n {\n string y = \"\";\n var m = AddLocal(1, x: x, y: y);\n return AddLocal(b: m, x: x, y: y);\n\n static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null)\n {\n return a + b + x + y.Length;\n }\n }\n}\"\n, parseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestWarningAnnotation()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n void N(int x)\n {\n Func del = AddLocal;\n\n int [||]AddLocal()\n {\n return x + 1;\n }\n } \n}\",\n@\"class C\n{\n void N(int x)\n {\n Func del = AddLocal;\n\n {|Warning:static int AddLocal(int x)\n {\n return x + 1;\n }|}\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestNonCamelCaseCapture()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n int Static = 0;\n return AddLocal();\n\n int [||]AddLocal()\n {\n return Static + 1;\n }\n } \n}\",\n@\"class C\n{\n int N(int x)\n {\n int Static = 0;\n return AddLocal(Static);\n\n static int AddLocal(int @static)\n {\n return @static + 1;\n }\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [WorkItem(46858, \"https://github.com/dotnet/roslyn/issues/46858\")]\n public async Task ShouldNotTriggerIfCallsOtherLocalFunction()\n {\n await TestMissingAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n B();\n return x + 1;\n }\n \n void B()\n {\n }\n } \n}\", parameters: new TestParameters(parseOptions: CSharp8ParseOptions));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n public async Task TestCallingStaticLocationFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"class C\n{\n int N(int x)\n {\n return AddLocal();\n\n int [||]AddLocal()\n {\n B();\n return x + 1;\n }\n \n static void B()\n {\n }\n } \n}\",\n@\"class C\n{\n int N(int x)\n {\n return AddLocal(x);\n\n static int [||]AddLocal(int x)\n {\n B();\n return x + 1;\n }\n \n static void B()\n {\n }\n } \n}\",\nparseOptions: CSharp8ParseOptions);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)]\n [WorkItem(53179, \"https://github.com/dotnet/roslyn/issues/53179\")]\n public async Task TestLocalFunctionAsTopLevelStatement()\n {\n await TestAsync(@\"\nint y = 10;\nreturn AddLocal();\n\nint[||] AddLocal()\n{\n return y;\n}\n\", @\"\nint y = 10;\nreturn AddLocal(y);\n\nstatic int AddLocal(int y)\n{\n return y;\n}\n\", parseOptions: CSharp8ParseOptions);\n }\n }\n}\n\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":407,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Features/CSharp/Portable/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Composition;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeActions;\nusing Microsoft.CodeAnalysis.CodeFixes;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\n\nnamespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic\n{\n [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared]\n internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider\n {\n [ImportingConstructor]\n [SuppressMessage(\"RoslynDiagnosticsReliability\", \"RS0033:Importing constructor should be [Obsolete]\", Justification = \"Used in test code: https://github.com/dotnet/roslyn/issues/42814\")]\n public MakeLocalFunctionStaticCodeFixProvider()\n {\n }\n\n public override ImmutableArray FixableDiagnosticIds { get; } =\n ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId);\n\n internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;\n\n public override Task RegisterCodeFixesAsync(CodeFixContext context)\n {\n context.RegisterCodeFix(new MyCodeAction(\n c => FixAsync(context.Document, context.Diagnostics[0], c)),\n context.Diagnostics);\n\n return Task.CompletedTask;\n }\n\n protected override Task FixAllAsync(\n Document document, ImmutableArray diagnostics,\n SyntaxEditor editor, CancellationToken cancellationToken)\n {\n var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(cancellationToken));\n foreach (var localFunction in localFunctions)\n {\n editor.ReplaceNode(\n localFunction,\n (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator));\n }\n\n return Task.CompletedTask;\n }\n\n private class MyCodeAction : CustomCodeActions.DocumentChangeAction\n {\n public MyCodeAction(Func> createChangedDocument)\n : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static)\n {\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Composition;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeActions;\nusing Microsoft.CodeAnalysis.CodeFixes;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\n\nnamespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic\n{\n [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared]\n internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider\n {\n [ImportingConstructor]\n [SuppressMessage(\"RoslynDiagnosticsReliability\", \"RS0033:Importing constructor should be [Obsolete]\", Justification = \"Used in test code: https://github.com/dotnet/roslyn/issues/42814\")]\n public MakeLocalFunctionStaticCodeFixProvider()\n {\n }\n\n public override ImmutableArray FixableDiagnosticIds { get; } =\n ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId);\n\n internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;\n\n public override Task RegisterCodeFixesAsync(CodeFixContext context)\n {\n context.RegisterCodeFix(new MyCodeAction(\n c => FixAsync(context.Document, context.Diagnostics[0], c)),\n context.Diagnostics);\n\n return Task.CompletedTask;\n }\n\n protected override Task FixAllAsync(\n Document document, ImmutableArray diagnostics,\n SyntaxEditor editor, CancellationToken cancellationToken)\n {\n var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken));\n foreach (var localFunction in localFunctions)\n {\n editor.ReplaceNode(\n localFunction,\n (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator));\n }\n\n return Task.CompletedTask;\n }\n\n private class MyCodeAction : CustomCodeActions.DocumentChangeAction\n {\n public MyCodeAction(Func> createChangedDocument)\n : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static)\n {\n }\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":408,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/Binder/WithTypeParametersBinder.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp\n{\n internal abstract class WithTypeParametersBinder : Binder\n {\n internal WithTypeParametersBinder(Binder next)\n : base(next)\n {\n }\n\n // TODO: Change this to a data structure that won't allocate enumerators\n protected abstract MultiDictionary TypeParameterMap { get; }\n\n // This is only overridden by WithMethodTypeParametersBinder.\n protected virtual LookupOptions LookupMask\n {\n get\n {\n return LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember;\n }\n }\n\n protected bool CanConsiderTypeParameters(LookupOptions options)\n {\n return (options & (LookupMask | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0;\n }\n\n internal override void LookupSymbolsInSingleBinder(\n LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo)\n {\n Debug.Assert(result.IsClear);\n\n if ((options & LookupMask) != 0)\n {\n return;\n }\n\n foreach (var typeParameter in TypeParameterMap[name])\n {\n result.MergeEqual(originalBinder.CheckViability(typeParameter, arity, options, null, diagnose, ref useSiteInfo));\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp\n{\n internal abstract class WithTypeParametersBinder : Binder\n {\n internal WithTypeParametersBinder(Binder next)\n : base(next)\n {\n }\n\n // TODO: Change this to a data structure that won't allocate enumerators\n protected abstract MultiDictionary TypeParameterMap { get; }\n\n // This is only overridden by WithMethodTypeParametersBinder.\n protected virtual LookupOptions LookupMask\n {\n get\n {\n return LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember;\n }\n }\n\n protected bool CanConsiderTypeParameters(LookupOptions options)\n {\n return (options & (LookupMask | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0;\n }\n\n internal override void LookupSymbolsInSingleBinder(\n LookupResult result, string name, int arity, ConsList basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo useSiteInfo)\n {\n Debug.Assert(result.IsClear);\n\n if ((options & LookupMask) != 0)\n {\n return;\n }\n\n foreach (var typeParameter in TypeParameterMap[name])\n {\n result.MergeEqual(originalBinder.CheckViability(typeParameter, arity, options, null, diagnose, ref useSiteInfo));\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":409,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection.Metadata;\nusing Microsoft.CodeAnalysis.Debugging;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Symbols;\nusing Microsoft.VisualStudio.Debugger;\nusing Microsoft.VisualStudio.Debugger.Clr;\nusing Microsoft.VisualStudio.Debugger.Clr.NativeCompilation;\nusing Microsoft.VisualStudio.Debugger.Evaluation;\nusing Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ExpressionEvaluator\n{\n internal static class DkmUtilities\n {\n internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize);\n\n // Return the set of managed module instances from the AppDomain.\n private static IEnumerable GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)\n {\n if (appDomain.IsUnloaded)\n {\n return SpecializedCollections.EmptyEnumerable();\n }\n\n var appDomainId = appDomain.Id;\n // GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance\n // which are containers of managed module instances (see GetEmbeddedModules())\n // but not managed modules themselves. Since GetModuleInstances() will include the\n // embedded modules, we can simply ignore DkmClrNcContainerModuleInstances.\n return runtime.GetModuleInstances().\n OfType().\n Where(module =>\n {\n var moduleAppDomain = module.AppDomain;\n return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId);\n });\n }\n\n internal static ImmutableArray GetMetadataBlocks(\n this DkmClrRuntimeInstance runtime,\n DkmClrAppDomain appDomain,\n ImmutableArray previousMetadataBlocks)\n {\n // Add a dummy data item to the appdomain to add it to the disposal queue when the debugged process is shutting down.\n // This should prevent from attempts to use the Metadata pointer for dead debugged processes.\n if (appDomain.GetDataItem() == null)\n {\n appDomain.SetDataItem(DkmDataCreationDisposition.CreateNew, new AppDomainLifetimeDataItem());\n }\n\n var builder = ArrayBuilder.GetInstance();\n IntPtr ptr;\n uint size;\n int index = 0;\n foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain))\n {\n MetadataBlock block;\n try\n {\n ptr = module.GetMetaDataBytesPtr(out size);\n Debug.Assert(size > 0);\n block = GetMetadataBlock(previousMetadataBlocks, index, ptr, size);\n }\n catch (NotImplementedException e) when (module is DkmClrNcModuleInstance)\n {\n // DkmClrNcModuleInstance.GetMetaDataBytesPtr not implemented in Dev14.\n throw new NotImplementedMetadataException(e);\n }\n catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))\n {\n continue;\n }\n Debug.Assert(block.ModuleVersionId == module.Mvid);\n builder.Add(block);\n index++;\n }\n // Include \"intrinsic method\" assembly.\n ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size);\n builder.Add(GetMetadataBlock(previousMetadataBlocks, index, ptr, size));\n return builder.ToImmutableAndFree();\n }\n\n internal static ImmutableArray GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray missingAssemblyIdentities)\n {\n ArrayBuilder? builder = null;\n foreach (var missingAssemblyIdentity in missingAssemblyIdentities)\n {\n MetadataBlock block;\n try\n {\n uint size;\n IntPtr ptr;\n ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size);\n Debug.Assert(size > 0);\n block = GetMetadataBlock(ptr, size);\n }\n catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))\n {\n continue;\n }\n if (builder == null)\n {\n builder = ArrayBuilder.GetInstance();\n }\n builder.Add(block);\n }\n return builder == null ? ImmutableArray.Empty : builder.ToImmutableAndFree();\n }\n\n internal static ImmutableArray MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress)\n {\n var builder = ArrayBuilder.GetInstance();\n foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain))\n {\n var symReader = module.GetSymReader();\n if (symReader == null)\n {\n continue;\n }\n MetadataReader reader;\n unsafe\n {\n try\n {\n uint size;\n IntPtr ptr;\n ptr = module.GetMetaDataBytesPtr(out size);\n Debug.Assert(size > 0);\n reader = new MetadataReader((byte*)ptr, (int)size);\n }\n catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))\n {\n continue;\n }\n }\n builder.Add(new AssemblyReaders(reader, symReader));\n }\n return builder.ToImmutableAndFree();\n }\n\n private static unsafe MetadataBlock GetMetadataBlock(IntPtr ptr, uint size)\n {\n var reader = new MetadataReader((byte*)ptr, (int)size);\n var moduleDef = reader.GetModuleDefinition();\n var moduleVersionId = reader.GetGuid(moduleDef.Mvid);\n var generationId = reader.GetGuid(moduleDef.GenerationId);\n return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size);\n }\n\n private static MetadataBlock GetMetadataBlock(ImmutableArray previousMetadataBlocks, int index, IntPtr ptr, uint size)\n {\n if (!previousMetadataBlocks.IsDefault && index < previousMetadataBlocks.Length)\n {\n var previousBlock = previousMetadataBlocks[index];\n if (previousBlock.Pointer == ptr && previousBlock.Size == size)\n {\n return previousBlock;\n }\n }\n\n return GetMetadataBlock(ptr, size);\n }\n\n internal static object? GetSymReader(this DkmClrModuleInstance clrModule)\n {\n var module = clrModule.Module; // Null if there are no symbols.\n if (module == null)\n {\n return null;\n }\n // Use DkmClrModuleInstance.GetSymUnmanagedReader()\n // rather than DkmModule.GetSymbolInterface() since the\n // latter does not handle .NET Native modules.\n return clrModule.GetSymUnmanagedReader();\n }\n\n internal static DkmCompiledClrInspectionQuery? ToQueryResult(\n this CompileResult? compResult,\n DkmCompilerId languageId,\n ResultProperties resultProperties,\n DkmClrRuntimeInstance runtimeInstance)\n {\n if (compResult == null)\n {\n return null;\n }\n\n Debug.Assert(compResult.Assembly != null);\n Debug.Assert(compResult.TypeName != null);\n Debug.Assert(compResult.MethodName != null);\n\n ReadOnlyCollection? customTypeInfo;\n Guid customTypeInfoId = compResult.GetCustomTypeInfo(out customTypeInfo);\n\n return DkmCompiledClrInspectionQuery.Create(\n runtimeInstance,\n Binary: new ReadOnlyCollection(compResult.Assembly),\n DataContainer: null,\n LanguageId: languageId,\n TypeName: compResult.TypeName,\n MethodName: compResult.MethodName,\n FormatSpecifiers: compResult.FormatSpecifiers,\n CompilationFlags: resultProperties.Flags,\n ResultCategory: resultProperties.Category,\n Access: resultProperties.AccessType,\n StorageType: resultProperties.StorageType,\n TypeModifierFlags: resultProperties.ModifierFlags,\n CustomTypeInfo: customTypeInfo.ToCustomTypeInfo(customTypeInfoId));\n }\n\n internal static DkmClrCustomTypeInfo? ToCustomTypeInfo(this ReadOnlyCollection? payload, Guid payloadTypeId)\n {\n return (payload == null) ? null : DkmClrCustomTypeInfo.Create(payloadTypeId, payload);\n }\n\n internal static ResultProperties GetResultProperties(this TSymbol? symbol, DkmClrCompilationResultFlags flags, bool isConstant)\n where TSymbol : class, ISymbolInternal\n {\n var category = (symbol != null) ? GetResultCategory(symbol.Kind)\n : DkmEvaluationResultCategory.Data;\n\n var accessType = (symbol != null) ? GetResultAccessType(symbol.DeclaredAccessibility)\n : DkmEvaluationResultAccessType.None;\n\n var storageType = (symbol != null) && symbol.IsStatic\n ? DkmEvaluationResultStorageType.Static\n : DkmEvaluationResultStorageType.None;\n\n var modifierFlags = DkmEvaluationResultTypeModifierFlags.None;\n if (isConstant)\n {\n modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant;\n }\n else if (symbol is null)\n {\n // No change.\n }\n else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride)\n {\n modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual;\n }\n else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbolInternal)symbol).IsVolatile)\n {\n modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile;\n }\n\n // CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)]\n // and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any\n // impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either.\n\n return new ResultProperties(flags, category, accessType, storageType, modifierFlags);\n }\n\n private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind)\n {\n switch (kind)\n {\n case SymbolKind.Method:\n return DkmEvaluationResultCategory.Method;\n case SymbolKind.Property:\n return DkmEvaluationResultCategory.Property;\n default:\n return DkmEvaluationResultCategory.Data;\n }\n }\n\n private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility)\n {\n switch (accessibility)\n {\n case Accessibility.Public:\n return DkmEvaluationResultAccessType.Public;\n case Accessibility.Protected:\n return DkmEvaluationResultAccessType.Protected;\n case Accessibility.Private:\n return DkmEvaluationResultAccessType.Private;\n case Accessibility.Internal:\n case Accessibility.ProtectedOrInternal: // Dev12 treats this as \"internal\"\n case Accessibility.ProtectedAndInternal: // Dev12 treats this as \"internal\"\n return DkmEvaluationResultAccessType.Internal;\n case Accessibility.NotApplicable:\n return DkmEvaluationResultAccessType.None;\n default:\n throw ExceptionUtilities.UnexpectedValue(accessibility);\n }\n }\n\n internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired)\n {\n return (flags & desired) == desired;\n }\n\n internal static MetadataContext GetMetadataContext(this DkmClrAppDomain appDomain)\n where TAssemblyContext : struct\n {\n var dataItem = appDomain.GetDataItem>>();\n return (dataItem == null) ? default : dataItem.MetadataContext;\n }\n\n internal static void SetMetadataContext(this DkmClrAppDomain appDomain, MetadataContext context, bool report)\n where TAssemblyContext : struct\n {\n if (report)\n {\n var process = appDomain.Process;\n var message = DkmUserMessage.Create(\n process.Connection,\n process,\n DkmUserMessageOutputKind.UnfilteredOutputWindowMessage,\n $\"EE: AppDomain {appDomain.Id}, blocks {context.MetadataBlocks.Length}, contexts {context.AssemblyContexts.Count}\" + Environment.NewLine,\n MessageBoxFlags.MB_OK,\n 0);\n message.Post();\n }\n appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem>(context));\n }\n\n internal static void RemoveMetadataContext(this DkmClrAppDomain appDomain)\n where TAssemblyContext : struct\n {\n appDomain.RemoveDataItem>();\n }\n\n private sealed class MetadataContextItem : DkmDataItem\n where TMetadataContext : struct\n {\n internal readonly TMetadataContext MetadataContext;\n\n internal MetadataContextItem(TMetadataContext metadataContext)\n {\n this.MetadataContext = metadataContext;\n }\n }\n\n private sealed class AppDomainLifetimeDataItem : DkmDataItem { }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection.Metadata;\nusing Microsoft.CodeAnalysis.Debugging;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Symbols;\nusing Microsoft.VisualStudio.Debugger;\nusing Microsoft.VisualStudio.Debugger.Clr;\nusing Microsoft.VisualStudio.Debugger.Clr.NativeCompilation;\nusing Microsoft.VisualStudio.Debugger.Evaluation;\nusing Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ExpressionEvaluator\n{\n internal static class DkmUtilities\n {\n internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize);\n\n // Return the set of managed module instances from the AppDomain.\n private static IEnumerable GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain)\n {\n if (appDomain.IsUnloaded)\n {\n return SpecializedCollections.EmptyEnumerable();\n }\n\n var appDomainId = appDomain.Id;\n // GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance\n // which are containers of managed module instances (see GetEmbeddedModules())\n // but not managed modules themselves. Since GetModuleInstances() will include the\n // embedded modules, we can simply ignore DkmClrNcContainerModuleInstances.\n return runtime.GetModuleInstances().\n OfType().\n Where(module =>\n {\n var moduleAppDomain = module.AppDomain;\n return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId);\n });\n }\n\n internal static ImmutableArray GetMetadataBlocks(\n this DkmClrRuntimeInstance runtime,\n DkmClrAppDomain appDomain,\n ImmutableArray previousMetadataBlocks)\n {\n // Add a dummy data item to the appdomain to add it to the disposal queue when the debugged process is shutting down.\n // This should prevent from attempts to use the Metadata pointer for dead debugged processes.\n if (appDomain.GetDataItem() == null)\n {\n appDomain.SetDataItem(DkmDataCreationDisposition.CreateNew, new AppDomainLifetimeDataItem());\n }\n\n var builder = ArrayBuilder.GetInstance();\n IntPtr ptr;\n uint size;\n int index = 0;\n foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain))\n {\n MetadataBlock block;\n try\n {\n ptr = module.GetMetaDataBytesPtr(out size);\n Debug.Assert(size > 0);\n block = GetMetadataBlock(previousMetadataBlocks, index, ptr, size);\n }\n catch (NotImplementedException e) when (module is DkmClrNcModuleInstance)\n {\n // DkmClrNcModuleInstance.GetMetaDataBytesPtr not implemented in Dev14.\n throw new NotImplementedMetadataException(e);\n }\n catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))\n {\n continue;\n }\n Debug.Assert(block.ModuleVersionId == module.Mvid);\n builder.Add(block);\n index++;\n }\n // Include \"intrinsic method\" assembly.\n ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size);\n builder.Add(GetMetadataBlock(previousMetadataBlocks, index, ptr, size));\n return builder.ToImmutableAndFree();\n }\n\n internal static ImmutableArray GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray missingAssemblyIdentities)\n {\n ArrayBuilder? builder = null;\n foreach (var missingAssemblyIdentity in missingAssemblyIdentities)\n {\n MetadataBlock block;\n try\n {\n uint size;\n IntPtr ptr;\n ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size);\n Debug.Assert(size > 0);\n block = GetMetadataBlock(ptr, size);\n }\n catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))\n {\n continue;\n }\n if (builder == null)\n {\n builder = ArrayBuilder.GetInstance();\n }\n builder.Add(block);\n }\n return builder == null ? ImmutableArray.Empty : builder.ToImmutableAndFree();\n }\n\n internal static ImmutableArray MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress)\n {\n var builder = ArrayBuilder.GetInstance();\n foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain))\n {\n var symReader = module.GetSymReader();\n if (symReader == null)\n {\n continue;\n }\n MetadataReader reader;\n unsafe\n {\n try\n {\n uint size;\n IntPtr ptr;\n ptr = module.GetMetaDataBytesPtr(out size);\n Debug.Assert(size > 0);\n reader = new MetadataReader((byte*)ptr, (int)size);\n }\n catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))\n {\n continue;\n }\n }\n builder.Add(new AssemblyReaders(reader, symReader));\n }\n return builder.ToImmutableAndFree();\n }\n\n private static unsafe MetadataBlock GetMetadataBlock(IntPtr ptr, uint size)\n {\n var reader = new MetadataReader((byte*)ptr, (int)size);\n var moduleDef = reader.GetModuleDefinition();\n var moduleVersionId = reader.GetGuid(moduleDef.Mvid);\n var generationId = reader.GetGuid(moduleDef.GenerationId);\n return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size);\n }\n\n private static MetadataBlock GetMetadataBlock(ImmutableArray previousMetadataBlocks, int index, IntPtr ptr, uint size)\n {\n if (!previousMetadataBlocks.IsDefault && index < previousMetadataBlocks.Length)\n {\n var previousBlock = previousMetadataBlocks[index];\n if (previousBlock.Pointer == ptr && previousBlock.Size == size)\n {\n return previousBlock;\n }\n }\n\n return GetMetadataBlock(ptr, size);\n }\n\n internal static object? GetSymReader(this DkmClrModuleInstance clrModule)\n {\n var module = clrModule.Module; // Null if there are no symbols.\n if (module == null)\n {\n return null;\n }\n // Use DkmClrModuleInstance.GetSymUnmanagedReader()\n // rather than DkmModule.GetSymbolInterface() since the\n // latter does not handle .NET Native modules.\n return clrModule.GetSymUnmanagedReader();\n }\n\n internal static DkmCompiledClrInspectionQuery? ToQueryResult(\n this CompileResult? compResult,\n DkmCompilerId languageId,\n ResultProperties resultProperties,\n DkmClrRuntimeInstance runtimeInstance)\n {\n if (compResult == null)\n {\n return null;\n }\n\n Debug.Assert(compResult.Assembly != null);\n Debug.Assert(compResult.TypeName != null);\n Debug.Assert(compResult.MethodName != null);\n\n ReadOnlyCollection? customTypeInfo;\n Guid customTypeInfoId = compResult.GetCustomTypeInfo(out customTypeInfo);\n\n return DkmCompiledClrInspectionQuery.Create(\n runtimeInstance,\n Binary: new ReadOnlyCollection(compResult.Assembly),\n DataContainer: null,\n LanguageId: languageId,\n TypeName: compResult.TypeName,\n MethodName: compResult.MethodName,\n FormatSpecifiers: compResult.FormatSpecifiers,\n CompilationFlags: resultProperties.Flags,\n ResultCategory: resultProperties.Category,\n Access: resultProperties.AccessType,\n StorageType: resultProperties.StorageType,\n TypeModifierFlags: resultProperties.ModifierFlags,\n CustomTypeInfo: customTypeInfo.ToCustomTypeInfo(customTypeInfoId));\n }\n\n internal static DkmClrCustomTypeInfo? ToCustomTypeInfo(this ReadOnlyCollection? payload, Guid payloadTypeId)\n {\n return (payload == null) ? null : DkmClrCustomTypeInfo.Create(payloadTypeId, payload);\n }\n\n internal static ResultProperties GetResultProperties(this TSymbol? symbol, DkmClrCompilationResultFlags flags, bool isConstant)\n where TSymbol : class, ISymbolInternal\n {\n var category = (symbol != null) ? GetResultCategory(symbol.Kind)\n : DkmEvaluationResultCategory.Data;\n\n var accessType = (symbol != null) ? GetResultAccessType(symbol.DeclaredAccessibility)\n : DkmEvaluationResultAccessType.None;\n\n var storageType = (symbol != null) && symbol.IsStatic\n ? DkmEvaluationResultStorageType.Static\n : DkmEvaluationResultStorageType.None;\n\n var modifierFlags = DkmEvaluationResultTypeModifierFlags.None;\n if (isConstant)\n {\n modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant;\n }\n else if (symbol is null)\n {\n // No change.\n }\n else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride)\n {\n modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual;\n }\n else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbolInternal)symbol).IsVolatile)\n {\n modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile;\n }\n\n // CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)]\n // and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any\n // impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either.\n\n return new ResultProperties(flags, category, accessType, storageType, modifierFlags);\n }\n\n private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind)\n {\n switch (kind)\n {\n case SymbolKind.Method:\n return DkmEvaluationResultCategory.Method;\n case SymbolKind.Property:\n return DkmEvaluationResultCategory.Property;\n default:\n return DkmEvaluationResultCategory.Data;\n }\n }\n\n private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility)\n {\n switch (accessibility)\n {\n case Accessibility.Public:\n return DkmEvaluationResultAccessType.Public;\n case Accessibility.Protected:\n return DkmEvaluationResultAccessType.Protected;\n case Accessibility.Private:\n return DkmEvaluationResultAccessType.Private;\n case Accessibility.Internal:\n case Accessibility.ProtectedOrInternal: // Dev12 treats this as \"internal\"\n case Accessibility.ProtectedAndInternal: // Dev12 treats this as \"internal\"\n return DkmEvaluationResultAccessType.Internal;\n case Accessibility.NotApplicable:\n return DkmEvaluationResultAccessType.None;\n default:\n throw ExceptionUtilities.UnexpectedValue(accessibility);\n }\n }\n\n internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired)\n {\n return (flags & desired) == desired;\n }\n\n internal static MetadataContext GetMetadataContext(this DkmClrAppDomain appDomain)\n where TAssemblyContext : struct\n {\n var dataItem = appDomain.GetDataItem>>();\n return (dataItem == null) ? default : dataItem.MetadataContext;\n }\n\n internal static void SetMetadataContext(this DkmClrAppDomain appDomain, MetadataContext context, bool report)\n where TAssemblyContext : struct\n {\n if (report)\n {\n var process = appDomain.Process;\n var message = DkmUserMessage.Create(\n process.Connection,\n process,\n DkmUserMessageOutputKind.UnfilteredOutputWindowMessage,\n $\"EE: AppDomain {appDomain.Id}, blocks {context.MetadataBlocks.Length}, contexts {context.AssemblyContexts.Count}\" + Environment.NewLine,\n MessageBoxFlags.MB_OK,\n 0);\n message.Post();\n }\n appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem>(context));\n }\n\n internal static void RemoveMetadataContext(this DkmClrAppDomain appDomain)\n where TAssemblyContext : struct\n {\n appDomain.RemoveDataItem>();\n }\n\n private sealed class MetadataContextItem : DkmDataItem\n where TMetadataContext : struct\n {\n internal readonly TMetadataContext MetadataContext;\n\n internal MetadataContextItem(TMetadataContext metadataContext)\n {\n this.MetadataContext = metadataContext;\n }\n }\n\n private sealed class AppDomainLifetimeDataItem : DkmDataItem { }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":410,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/Syntax/ArrayRankSpecifierSyntax.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nnamespace Microsoft.CodeAnalysis.CSharp.Syntax\n{\n public partial class ArrayRankSpecifierSyntax\n {\n public int Rank\n {\n get\n {\n return this.Sizes.Count;\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nnamespace Microsoft.CodeAnalysis.CSharp.Syntax\n{\n public partial class ArrayRankSpecifierSyntax\n {\n public int Rank\n {\n get\n {\n return this.Sizes.Count;\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":411,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/Serialization/SerializableSourceText.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Serialization\n{\n /// \n /// Represents a which can be serialized for sending to another process. The text is not\n /// required to be a live object in the current process, and can instead be held in temporary storage accessible by\n /// both processes.\n /// \n internal sealed class SerializableSourceText\n {\n /// \n /// The storage location for .\n /// \n /// \n /// Exactly one of or will be non-.\n /// \n public ITemporaryTextStorageWithName? Storage { get; }\n\n /// \n /// The in the current process.\n /// \n /// \n /// \n /// \n public SourceText? Text { get; }\n\n public SerializableSourceText(ITemporaryTextStorageWithName storage)\n : this(storage, text: null)\n {\n }\n\n public SerializableSourceText(SourceText text)\n : this(storage: null, text)\n {\n }\n\n private SerializableSourceText(ITemporaryTextStorageWithName? storage, SourceText? text)\n {\n Debug.Assert(storage is null != text is null);\n\n Storage = storage;\n Text = text;\n }\n\n public ImmutableArray GetChecksum()\n {\n return Text?.GetChecksum() ?? Storage!.GetChecksum();\n }\n\n public async ValueTask GetTextAsync(CancellationToken cancellationToken)\n {\n if (Text is not null)\n return Text;\n\n return await Storage!.ReadTextAsync(cancellationToken).ConfigureAwait(false);\n }\n\n public static ValueTask FromTextDocumentStateAsync(TextDocumentState state, CancellationToken cancellationToken)\n {\n if (state.Storage is ITemporaryTextStorageWithName storage)\n {\n return new ValueTask(new SerializableSourceText(storage));\n }\n else\n {\n return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(\n static (state, cancellationToken) => state.GetTextAsync(cancellationToken),\n static (text, _) => new SerializableSourceText(text),\n state,\n cancellationToken);\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Serialization\n{\n /// \n /// Represents a which can be serialized for sending to another process. The text is not\n /// required to be a live object in the current process, and can instead be held in temporary storage accessible by\n /// both processes.\n /// \n internal sealed class SerializableSourceText\n {\n /// \n /// The storage location for .\n /// \n /// \n /// Exactly one of or will be non-.\n /// \n public ITemporaryTextStorageWithName? Storage { get; }\n\n /// \n /// The in the current process.\n /// \n /// \n /// \n /// \n public SourceText? Text { get; }\n\n public SerializableSourceText(ITemporaryTextStorageWithName storage)\n : this(storage, text: null)\n {\n }\n\n public SerializableSourceText(SourceText text)\n : this(storage: null, text)\n {\n }\n\n private SerializableSourceText(ITemporaryTextStorageWithName? storage, SourceText? text)\n {\n Debug.Assert(storage is null != text is null);\n\n Storage = storage;\n Text = text;\n }\n\n public ImmutableArray GetChecksum()\n {\n return Text?.GetChecksum() ?? Storage!.GetChecksum();\n }\n\n public async ValueTask GetTextAsync(CancellationToken cancellationToken)\n {\n if (Text is not null)\n return Text;\n\n return await Storage!.ReadTextAsync(cancellationToken).ConfigureAwait(false);\n }\n\n public static ValueTask FromTextDocumentStateAsync(TextDocumentState state, CancellationToken cancellationToken)\n {\n if (state.Storage is ITemporaryTextStorageWithName storage)\n {\n return new ValueTask(new SerializableSourceText(storage));\n }\n else\n {\n return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(\n static (state, cancellationToken) => state.GetTextAsync(cancellationToken),\n static (text, _) => new SerializableSourceText(text),\n state,\n cancellationToken);\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":412,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/Test/Core/TempFiles/TempDirectory.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Diagnostics;\nusing System.IO;\n\nnamespace Microsoft.CodeAnalysis.Test.Utilities\n{\n public class TempDirectory\n {\n private readonly string _path;\n private readonly TempRoot _root;\n\n protected TempDirectory(TempRoot root)\n : this(CreateUniqueDirectory(TempRoot.Root), root)\n {\n }\n\n private TempDirectory(string path, TempRoot root)\n {\n Debug.Assert(path != null);\n Debug.Assert(root != null);\n\n _path = path;\n _root = root;\n }\n\n private static string CreateUniqueDirectory(string basePath)\n {\n while (true)\n {\n string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString());\n try\n {\n Directory.CreateDirectory(dir);\n return dir;\n }\n catch (IOException)\n {\n // retry\n }\n }\n }\n\n public string Path\n {\n get { return _path; }\n }\n\n /// \n /// Creates a file in this directory.\n /// \n /// File name.\n public TempFile CreateFile(string name)\n {\n string filePath = System.IO.Path.Combine(_path, name);\n TempRoot.CreateStream(filePath, FileMode.CreateNew);\n return _root.AddFile(new DisposableFile(filePath));\n }\n\n /// \n /// Creates a file or opens an existing file in this directory.\n /// \n public TempFile CreateOrOpenFile(string name)\n {\n string filePath = System.IO.Path.Combine(_path, name);\n TempRoot.CreateStream(filePath, FileMode.OpenOrCreate);\n return _root.AddFile(new DisposableFile(filePath));\n }\n\n /// \n /// Creates a file in this directory that is a copy of the specified file.\n /// \n public TempFile CopyFile(string originalPath, string name = null)\n {\n string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath));\n File.Copy(originalPath, filePath);\n return _root.AddFile(new DisposableFile(filePath));\n }\n\n /// \n /// Creates a subdirectory in this directory.\n /// \n /// Directory name or unrooted directory path.\n public TempDirectory CreateDirectory(string name)\n {\n string dirPath = System.IO.Path.Combine(_path, name);\n Directory.CreateDirectory(dirPath);\n return new TempDirectory(dirPath, _root);\n }\n\n public override string ToString()\n {\n return _path;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Diagnostics;\nusing System.IO;\n\nnamespace Microsoft.CodeAnalysis.Test.Utilities\n{\n public class TempDirectory\n {\n private readonly string _path;\n private readonly TempRoot _root;\n\n protected TempDirectory(TempRoot root)\n : this(CreateUniqueDirectory(TempRoot.Root), root)\n {\n }\n\n private TempDirectory(string path, TempRoot root)\n {\n Debug.Assert(path != null);\n Debug.Assert(root != null);\n\n _path = path;\n _root = root;\n }\n\n private static string CreateUniqueDirectory(string basePath)\n {\n while (true)\n {\n string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString());\n try\n {\n Directory.CreateDirectory(dir);\n return dir;\n }\n catch (IOException)\n {\n // retry\n }\n }\n }\n\n public string Path\n {\n get { return _path; }\n }\n\n /// \n /// Creates a file in this directory.\n /// \n /// File name.\n public TempFile CreateFile(string name)\n {\n string filePath = System.IO.Path.Combine(_path, name);\n TempRoot.CreateStream(filePath, FileMode.CreateNew);\n return _root.AddFile(new DisposableFile(filePath));\n }\n\n /// \n /// Creates a file or opens an existing file in this directory.\n /// \n public TempFile CreateOrOpenFile(string name)\n {\n string filePath = System.IO.Path.Combine(_path, name);\n TempRoot.CreateStream(filePath, FileMode.OpenOrCreate);\n return _root.AddFile(new DisposableFile(filePath));\n }\n\n /// \n /// Creates a file in this directory that is a copy of the specified file.\n /// \n public TempFile CopyFile(string originalPath, string name = null)\n {\n string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath));\n File.Copy(originalPath, filePath);\n return _root.AddFile(new DisposableFile(filePath));\n }\n\n /// \n /// Creates a subdirectory in this directory.\n /// \n /// Directory name or unrooted directory path.\n public TempDirectory CreateDirectory(string name)\n {\n string dirPath = System.IO.Path.Combine(_path, name);\n Directory.CreateDirectory(dirPath);\n return new TempDirectory(dirPath, _root);\n }\n\n public override string ToString()\n {\n return _path;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":413,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ReferenceKeywordRecommender.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders\n{\n internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender\n {\n public ReferenceKeywordRecommender()\n : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true)\n {\n }\n\n protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)\n {\n var syntaxTree = context.SyntaxTree;\n return\n context.IsPreProcessorKeywordContext &&\n syntaxTree.IsScript() &&\n syntaxTree.IsBeforeFirstToken(position, cancellationToken);\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders\n{\n internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender\n {\n public ReferenceKeywordRecommender()\n : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true)\n {\n }\n\n protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)\n {\n var syntaxTree = context.SyntaxTree;\n return\n context.IsPreProcessorKeywordContext &&\n syntaxTree.IsScript() &&\n syntaxTree.IsBeforeFirstToken(position, cancellationToken);\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":414,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/VisualStudio/CSharp/Impl/ObjectBrowser/ObjectBrowserLibraryManager.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.VisualStudio.ComponentModelHost;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser;\nusing Microsoft.VisualStudio.Shell.Interop;\n\nnamespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser\n{\n internal class ObjectBrowserLibraryManager : AbstractObjectBrowserLibraryManager\n {\n public ObjectBrowserLibraryManager(\n IServiceProvider serviceProvider,\n IComponentModel componentModel,\n VisualStudioWorkspace workspace)\n : base(LanguageNames.CSharp, Guids.CSharpLibraryId, serviceProvider, componentModel, workspace)\n {\n }\n\n internal override AbstractDescriptionBuilder CreateDescriptionBuilder(\n IVsObjectBrowserDescription3 description,\n ObjectListItem listItem,\n Project project)\n {\n return new DescriptionBuilder(description, this, listItem, project);\n }\n\n internal override AbstractListItemFactory CreateListItemFactory()\n => new ListItemFactory();\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.VisualStudio.ComponentModelHost;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser;\nusing Microsoft.VisualStudio.Shell.Interop;\n\nnamespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser\n{\n internal class ObjectBrowserLibraryManager : AbstractObjectBrowserLibraryManager\n {\n public ObjectBrowserLibraryManager(\n IServiceProvider serviceProvider,\n IComponentModel componentModel,\n VisualStudioWorkspace workspace)\n : base(LanguageNames.CSharp, Guids.CSharpLibraryId, serviceProvider, componentModel, workspace)\n {\n }\n\n internal override AbstractDescriptionBuilder CreateDescriptionBuilder(\n IVsObjectBrowserDescription3 description,\n ObjectListItem listItem,\n Project project)\n {\n return new DescriptionBuilder(description, this, listItem, project);\n }\n\n internal override AbstractListItemFactory CreateListItemFactory()\n => new ListItemFactory();\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":415,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/Shared/Utilities/BloomFilter.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace Microsoft.CodeAnalysis.Shared.Utilities\n{\n internal partial class BloomFilter\n {\n // From MurmurHash:\n // 'm' and 'r' are mixing constants generated off-line.\n // The values for m and r are chosen through experimentation and \n // supported by evidence that they work well.\n private const uint Compute_Hash_m = 0x5bd1e995;\n private const int Compute_Hash_r = 24;\n\n private readonly BitArray _bitArray;\n private readonly int _hashFunctionCount;\n private readonly bool _isCaseSensitive;\n\n /// \n public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive)\n {\n var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability));\n var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability));\n\n // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count.\n // The count is used by the hash functions.\n var sizeInEvenBytes = (m + 7) & ~7;\n\n _bitArray = new BitArray(length: sizeInEvenBytes);\n _hashFunctionCount = k;\n _isCaseSensitive = isCaseSensitive;\n }\n\n public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection values)\n : this(values.Count, falsePositiveProbability, isCaseSensitive)\n {\n AddRange(values);\n }\n\n public BloomFilter(\n double falsePositiveProbability,\n ICollection stringValues,\n ICollection longValues)\n : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false)\n {\n AddRange(stringValues);\n AddRange(longValues);\n }\n\n private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive)\n {\n _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray));\n _hashFunctionCount = hashFunctionCount;\n _isCaseSensitive = isCaseSensitive;\n }\n\n // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0)))))\n private static int ComputeM(int expectedCount, double falsePositiveProbability)\n {\n var p = falsePositiveProbability;\n double n = expectedCount;\n\n var numerator = n * Math.Log(p);\n var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0)));\n return unchecked((int)Math.Ceiling(numerator / denominator));\n }\n\n // k = round(log(2.0) * m / n)\n private static int ComputeK(int expectedCount, double falsePositiveProbability)\n {\n double n = expectedCount;\n double m = ComputeM(expectedCount, falsePositiveProbability);\n\n var temp = Math.Log(2.0) * m / n;\n return unchecked((int)Math.Round(temp));\n }\n\n /// \n /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over\n /// strings instead of byte arrays. Because each string character is two bytes, it is known\n /// that the input will be an even number of bytes (though not necessarily a multiple of 4).\n /// \n /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate\n /// 'k' different well distributed hashes for any given string s. Also, we want to be able to\n /// generate these hashes without allocating any memory. My ideal solution would be to use an\n /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can:\n /// \n /// a) feed it individual values instead of a byte[]\n /// \n /// b) have the hash computed into a byte[] you provide instead of a newly allocated one\n /// \n /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So,\n /// instead, we use murmur hash since it provides well distributed values, allows for a\n /// seed, and allocates no memory.\n /// \n /// Murmur hash is public domain. Actual code is included below as reference.\n /// \n private int ComputeHash(string key, int seed)\n {\n unchecked\n {\n // Initialize the hash to a 'random' value\n\n var numberOfCharsLeft = key.Length;\n var h = (uint)(seed ^ numberOfCharsLeft);\n\n // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate\n // through the string two chars at a time.\n var index = 0;\n while (numberOfCharsLeft >= 2)\n {\n var c1 = GetCharacter(key, index);\n var c2 = GetCharacter(key, index + 1);\n\n h = CombineTwoCharacters(h, c1, c2);\n\n index += 2;\n numberOfCharsLeft -= 2;\n }\n\n // Handle the last char (or 2 bytes) if they exist. This happens if the original string had\n // odd length.\n if (numberOfCharsLeft == 1)\n {\n var c = GetCharacter(key, index);\n h = CombineLastCharacter(h, c);\n }\n\n // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated.\n\n h = FinalMix(h);\n\n return (int)h;\n }\n }\n\n private static int ComputeHash(long key, int seed)\n {\n // This is a duplicate of ComputeHash(string key, int seed). However, because\n // we only have 64bits to encode we just unroll that function here. See\n // Other function for documentation on what's going on here.\n unchecked\n {\n // Initialize the hash to a 'random' value\n\n var numberOfCharsLeft = 4;\n var h = (uint)(seed ^ numberOfCharsLeft);\n\n // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate\n // through the long two chars at a time.\n var index = 0;\n while (numberOfCharsLeft >= 2)\n {\n var c1 = GetCharacter(key, index);\n var c2 = GetCharacter(key, index + 1);\n\n h = CombineTwoCharacters(h, c1, c2);\n\n index += 2;\n numberOfCharsLeft -= 2;\n }\n\n Debug.Assert(numberOfCharsLeft == 0);\n\n // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated.\n h = FinalMix(h);\n\n return (int)h;\n }\n }\n\n private static uint CombineLastCharacter(uint h, uint c)\n {\n unchecked\n {\n h ^= c;\n h *= Compute_Hash_m;\n return h;\n }\n }\n\n private static uint FinalMix(uint h)\n {\n unchecked\n {\n h ^= h >> 13;\n h *= Compute_Hash_m;\n h ^= h >> 15;\n return h;\n }\n }\n\n private static uint CombineTwoCharacters(uint h, uint c1, uint c2)\n {\n unchecked\n {\n var k = c1 | (c2 << 16);\n\n k *= Compute_Hash_m;\n k ^= k >> Compute_Hash_r;\n k *= Compute_Hash_m;\n\n h *= Compute_Hash_m;\n h ^= k;\n\n return h;\n }\n }\n\n private char GetCharacter(string key, int index)\n {\n var c = key[index];\n return _isCaseSensitive ? c : char.ToLowerInvariant(c);\n }\n\n private static char GetCharacter(long key, int index)\n {\n Debug.Assert(index <= 3);\n return (char)(key >> (16 * index));\n }\n\n#if false\n //-----------------------------------------------------------------------------\n // MurmurHash2, by Austin Appleby\n //\n // Note - This code makes a few assumptions about how your machine behaves -\n // 1. We can read a 4-byte value from any address without crashing\n // 2. sizeof(int) == 4\n //\n // And it has a few limitations -\n // 1. It will not work incrementally.\n // 2. It will not produce the same results on little-endian and big-endian\n // machines.\n unsigned int MurmurHash2(const void* key, int len, unsigned int seed)\n {\n // 'm' and 'r' are mixing constants generated offline.\n // The values for m and r are chosen through experimentation and \n // supported by evidence that they work well.\n \n const unsigned int m = 0x5bd1e995;\n const int r = 24;\n\n // Initialize the hash to a 'random' value\n unsigned int h = seed ^ len;\n\n // Mix 4 bytes at a time into the hash\n const unsigned char* data = (const unsigned char*)key;\n\n while(len >= 4)\n {\n unsigned int k = *(unsigned int*)data;\n\n k *= m; \n k ^= k >> r; \n k *= m; \n\n h *= m; \n h ^= k;\n\n data += 4;\n len -= 4;\n }\n \n // Handle the last few bytes of the input array\n switch(len)\n {\n case 3: h ^= data[2] << 16;\n case 2: h ^= data[1] << 8;\n case 1: h ^= data[0];\n h *= m;\n };\n\n // Do a few final mixes of the hash to ensure the last few\n // bytes are well-incorporated.\n\n h ^= h >> 13;\n h *= m;\n h ^= h >> 15;\n\n return h;\n } \n#endif\n\n public void AddRange(IEnumerable values)\n {\n foreach (var v in values)\n {\n Add(v);\n }\n }\n\n public void AddRange(IEnumerable values)\n {\n foreach (var v in values)\n {\n Add(v);\n }\n }\n\n public void Add(string value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n _bitArray[GetBitArrayIndex(value, i)] = true;\n }\n }\n\n private int GetBitArrayIndex(string value, int i)\n {\n var hash = ComputeHash(value, i);\n hash %= _bitArray.Length;\n return Math.Abs(hash);\n }\n\n public void Add(long value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n _bitArray[GetBitArrayIndex(value, i)] = true;\n }\n }\n\n private int GetBitArrayIndex(long value, int i)\n {\n var hash = ComputeHash(value, i);\n hash %= _bitArray.Length;\n return Math.Abs(hash);\n }\n\n public bool ProbablyContains(string value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n if (!_bitArray[GetBitArrayIndex(value, i)])\n {\n return false;\n }\n }\n\n return true;\n }\n\n public bool ProbablyContains(long value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n if (!_bitArray[GetBitArrayIndex(value, i)])\n {\n return false;\n }\n }\n\n return true;\n }\n\n public bool IsEquivalent(BloomFilter filter)\n {\n return IsEquivalent(_bitArray, filter._bitArray)\n && _hashFunctionCount == filter._hashFunctionCount\n && _isCaseSensitive == filter._isCaseSensitive;\n }\n\n private static bool IsEquivalent(BitArray array1, BitArray array2)\n {\n if (array1.Length != array2.Length)\n {\n return false;\n }\n\n for (var i = 0; i < array1.Length; i++)\n {\n if (array1[i] != array2[i])\n {\n return false;\n }\n }\n\n return true;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace Microsoft.CodeAnalysis.Shared.Utilities\n{\n internal partial class BloomFilter\n {\n // From MurmurHash:\n // 'm' and 'r' are mixing constants generated off-line.\n // The values for m and r are chosen through experimentation and \n // supported by evidence that they work well.\n private const uint Compute_Hash_m = 0x5bd1e995;\n private const int Compute_Hash_r = 24;\n\n private readonly BitArray _bitArray;\n private readonly int _hashFunctionCount;\n private readonly bool _isCaseSensitive;\n\n /// \n public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive)\n {\n var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability));\n var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability));\n\n // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count.\n // The count is used by the hash functions.\n var sizeInEvenBytes = (m + 7) & ~7;\n\n _bitArray = new BitArray(length: sizeInEvenBytes);\n _hashFunctionCount = k;\n _isCaseSensitive = isCaseSensitive;\n }\n\n public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection values)\n : this(values.Count, falsePositiveProbability, isCaseSensitive)\n {\n AddRange(values);\n }\n\n public BloomFilter(\n double falsePositiveProbability,\n ICollection stringValues,\n ICollection longValues)\n : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false)\n {\n AddRange(stringValues);\n AddRange(longValues);\n }\n\n private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive)\n {\n _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray));\n _hashFunctionCount = hashFunctionCount;\n _isCaseSensitive = isCaseSensitive;\n }\n\n // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0)))))\n private static int ComputeM(int expectedCount, double falsePositiveProbability)\n {\n var p = falsePositiveProbability;\n double n = expectedCount;\n\n var numerator = n * Math.Log(p);\n var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0)));\n return unchecked((int)Math.Ceiling(numerator / denominator));\n }\n\n // k = round(log(2.0) * m / n)\n private static int ComputeK(int expectedCount, double falsePositiveProbability)\n {\n double n = expectedCount;\n double m = ComputeM(expectedCount, falsePositiveProbability);\n\n var temp = Math.Log(2.0) * m / n;\n return unchecked((int)Math.Round(temp));\n }\n\n /// \n /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over\n /// strings instead of byte arrays. Because each string character is two bytes, it is known\n /// that the input will be an even number of bytes (though not necessarily a multiple of 4).\n /// \n /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate\n /// 'k' different well distributed hashes for any given string s. Also, we want to be able to\n /// generate these hashes without allocating any memory. My ideal solution would be to use an\n /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can:\n /// \n /// a) feed it individual values instead of a byte[]\n /// \n /// b) have the hash computed into a byte[] you provide instead of a newly allocated one\n /// \n /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So,\n /// instead, we use murmur hash since it provides well distributed values, allows for a\n /// seed, and allocates no memory.\n /// \n /// Murmur hash is public domain. Actual code is included below as reference.\n /// \n private int ComputeHash(string key, int seed)\n {\n unchecked\n {\n // Initialize the hash to a 'random' value\n\n var numberOfCharsLeft = key.Length;\n var h = (uint)(seed ^ numberOfCharsLeft);\n\n // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate\n // through the string two chars at a time.\n var index = 0;\n while (numberOfCharsLeft >= 2)\n {\n var c1 = GetCharacter(key, index);\n var c2 = GetCharacter(key, index + 1);\n\n h = CombineTwoCharacters(h, c1, c2);\n\n index += 2;\n numberOfCharsLeft -= 2;\n }\n\n // Handle the last char (or 2 bytes) if they exist. This happens if the original string had\n // odd length.\n if (numberOfCharsLeft == 1)\n {\n var c = GetCharacter(key, index);\n h = CombineLastCharacter(h, c);\n }\n\n // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated.\n\n h = FinalMix(h);\n\n return (int)h;\n }\n }\n\n private static int ComputeHash(long key, int seed)\n {\n // This is a duplicate of ComputeHash(string key, int seed). However, because\n // we only have 64bits to encode we just unroll that function here. See\n // Other function for documentation on what's going on here.\n unchecked\n {\n // Initialize the hash to a 'random' value\n\n var numberOfCharsLeft = 4;\n var h = (uint)(seed ^ numberOfCharsLeft);\n\n // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate\n // through the long two chars at a time.\n var index = 0;\n while (numberOfCharsLeft >= 2)\n {\n var c1 = GetCharacter(key, index);\n var c2 = GetCharacter(key, index + 1);\n\n h = CombineTwoCharacters(h, c1, c2);\n\n index += 2;\n numberOfCharsLeft -= 2;\n }\n\n Debug.Assert(numberOfCharsLeft == 0);\n\n // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated.\n h = FinalMix(h);\n\n return (int)h;\n }\n }\n\n private static uint CombineLastCharacter(uint h, uint c)\n {\n unchecked\n {\n h ^= c;\n h *= Compute_Hash_m;\n return h;\n }\n }\n\n private static uint FinalMix(uint h)\n {\n unchecked\n {\n h ^= h >> 13;\n h *= Compute_Hash_m;\n h ^= h >> 15;\n return h;\n }\n }\n\n private static uint CombineTwoCharacters(uint h, uint c1, uint c2)\n {\n unchecked\n {\n var k = c1 | (c2 << 16);\n\n k *= Compute_Hash_m;\n k ^= k >> Compute_Hash_r;\n k *= Compute_Hash_m;\n\n h *= Compute_Hash_m;\n h ^= k;\n\n return h;\n }\n }\n\n private char GetCharacter(string key, int index)\n {\n var c = key[index];\n return _isCaseSensitive ? c : char.ToLowerInvariant(c);\n }\n\n private static char GetCharacter(long key, int index)\n {\n Debug.Assert(index <= 3);\n return (char)(key >> (16 * index));\n }\n\n#if false\n //-----------------------------------------------------------------------------\n // MurmurHash2, by Austin Appleby\n //\n // Note - This code makes a few assumptions about how your machine behaves -\n // 1. We can read a 4-byte value from any address without crashing\n // 2. sizeof(int) == 4\n //\n // And it has a few limitations -\n // 1. It will not work incrementally.\n // 2. It will not produce the same results on little-endian and big-endian\n // machines.\n unsigned int MurmurHash2(const void* key, int len, unsigned int seed)\n {\n // 'm' and 'r' are mixing constants generated offline.\n // The values for m and r are chosen through experimentation and \n // supported by evidence that they work well.\n \n const unsigned int m = 0x5bd1e995;\n const int r = 24;\n\n // Initialize the hash to a 'random' value\n unsigned int h = seed ^ len;\n\n // Mix 4 bytes at a time into the hash\n const unsigned char* data = (const unsigned char*)key;\n\n while(len >= 4)\n {\n unsigned int k = *(unsigned int*)data;\n\n k *= m; \n k ^= k >> r; \n k *= m; \n\n h *= m; \n h ^= k;\n\n data += 4;\n len -= 4;\n }\n \n // Handle the last few bytes of the input array\n switch(len)\n {\n case 3: h ^= data[2] << 16;\n case 2: h ^= data[1] << 8;\n case 1: h ^= data[0];\n h *= m;\n };\n\n // Do a few final mixes of the hash to ensure the last few\n // bytes are well-incorporated.\n\n h ^= h >> 13;\n h *= m;\n h ^= h >> 15;\n\n return h;\n } \n#endif\n\n public void AddRange(IEnumerable values)\n {\n foreach (var v in values)\n {\n Add(v);\n }\n }\n\n public void AddRange(IEnumerable values)\n {\n foreach (var v in values)\n {\n Add(v);\n }\n }\n\n public void Add(string value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n _bitArray[GetBitArrayIndex(value, i)] = true;\n }\n }\n\n private int GetBitArrayIndex(string value, int i)\n {\n var hash = ComputeHash(value, i);\n hash %= _bitArray.Length;\n return Math.Abs(hash);\n }\n\n public void Add(long value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n _bitArray[GetBitArrayIndex(value, i)] = true;\n }\n }\n\n private int GetBitArrayIndex(long value, int i)\n {\n var hash = ComputeHash(value, i);\n hash %= _bitArray.Length;\n return Math.Abs(hash);\n }\n\n public bool ProbablyContains(string value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n if (!_bitArray[GetBitArrayIndex(value, i)])\n {\n return false;\n }\n }\n\n return true;\n }\n\n public bool ProbablyContains(long value)\n {\n for (var i = 0; i < _hashFunctionCount; i++)\n {\n if (!_bitArray[GetBitArrayIndex(value, i)])\n {\n return false;\n }\n }\n\n return true;\n }\n\n public bool IsEquivalent(BloomFilter filter)\n {\n return IsEquivalent(_bitArray, filter._bitArray)\n && _hashFunctionCount == filter._hashFunctionCount\n && _isCaseSensitive == filter._isCaseSensitive;\n }\n\n private static bool IsEquivalent(BitArray array1, BitArray array2)\n {\n if (array1.Length != array2.Length)\n {\n return false;\n }\n\n for (var i = 0; i < array1.Length; i++)\n {\n if (array1[i] != array2[i])\n {\n return false;\n }\n }\n\n return true;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":416,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/ContainsGraphQuery.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Text;\nusing Microsoft.VisualStudio.GraphModel;\nusing Microsoft.VisualStudio.GraphModel.Schemas;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression\n{\n internal sealed class ContainsGraphQuery : IGraphQuery\n {\n public async Task GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)\n {\n var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);\n var nodesToProcess = context.InputNodes;\n\n for (var depth = 0; depth < context.LinkDepth; depth++)\n {\n // This is the list of nodes we created and will process\n var newNodes = new HashSet();\n\n foreach (var node in nodesToProcess)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var symbol = graphBuilder.GetSymbol(node, cancellationToken);\n if (symbol != null)\n {\n foreach (var newSymbol in SymbolContainment.GetContainedSymbols(symbol))\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var newNode = await graphBuilder.AddNodeAsync(\n newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false);\n graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken);\n }\n }\n else if (node.HasCategory(CodeNodeCategories.File))\n {\n var document = graphBuilder.GetContextDocument(node, cancellationToken);\n if (document != null)\n {\n foreach (var newSymbol in await SymbolContainment.GetContainedSymbolsAsync(document, cancellationToken).ConfigureAwait(false))\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var newNode = await graphBuilder.AddNodeAsync(\n newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false);\n graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken);\n }\n }\n }\n }\n\n nodesToProcess = newNodes;\n }\n\n return graphBuilder;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Text;\nusing Microsoft.VisualStudio.GraphModel;\nusing Microsoft.VisualStudio.GraphModel.Schemas;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression\n{\n internal sealed class ContainsGraphQuery : IGraphQuery\n {\n public async Task GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)\n {\n var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);\n var nodesToProcess = context.InputNodes;\n\n for (var depth = 0; depth < context.LinkDepth; depth++)\n {\n // This is the list of nodes we created and will process\n var newNodes = new HashSet();\n\n foreach (var node in nodesToProcess)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var symbol = graphBuilder.GetSymbol(node, cancellationToken);\n if (symbol != null)\n {\n foreach (var newSymbol in SymbolContainment.GetContainedSymbols(symbol))\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var newNode = await graphBuilder.AddNodeAsync(\n newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false);\n graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken);\n }\n }\n else if (node.HasCategory(CodeNodeCategories.File))\n {\n var document = graphBuilder.GetContextDocument(node, cancellationToken);\n if (document != null)\n {\n foreach (var newSymbol in await SymbolContainment.GetContainedSymbolsAsync(document, cancellationToken).ConfigureAwait(false))\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var newNode = await graphBuilder.AddNodeAsync(\n newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false);\n graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken);\n }\n }\n }\n }\n\n nodesToProcess = newNodes;\n }\n\n return graphBuilder;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":417,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/NavigateTo/IRemoteNavigateToSearchService.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Composition;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Remote;\nusing Microsoft.CodeAnalysis.Storage;\n\nnamespace Microsoft.CodeAnalysis.NavigateTo\n{\n internal interface IRemoteNavigateToSearchService\n {\n ValueTask SearchFullyLoadedDocumentAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, string searchPattern, ImmutableArray kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);\n ValueTask SearchFullyLoadedProjectAsync(PinnedSolutionInfo solutionInfo, ProjectId projectId, ImmutableArray priorityDocumentIds, string searchPattern, ImmutableArray kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);\n ValueTask SearchCachedDocumentsAsync(ImmutableArray documentKeys, ImmutableArray priorityDocumentKeys, StorageDatabase database, string searchPattern, ImmutableArray kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);\n ValueTask HydrateAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken);\n\n public interface ICallback\n {\n ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result);\n }\n }\n\n [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteNavigateToSearchService)), Shared]\n internal sealed class NavigateToSearchServiceServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteNavigateToSearchService.ICallback\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public NavigateToSearchServiceServerCallbackDispatcher()\n {\n }\n\n private new NavigateToSearchServiceCallback GetCallback(RemoteServiceCallbackId callbackId)\n => (NavigateToSearchServiceCallback)base.GetCallback(callbackId);\n\n public ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result)\n => GetCallback(callbackId).OnResultFoundAsync(result);\n }\n\n internal sealed class NavigateToSearchServiceCallback\n {\n private readonly Func _onResultFound;\n\n public NavigateToSearchServiceCallback(Func onResultFound)\n {\n _onResultFound = onResultFound;\n }\n\n public async ValueTask OnResultFoundAsync(RoslynNavigateToItem result)\n => await _onResultFound(result).ConfigureAwait(false);\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Composition;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Remote;\nusing Microsoft.CodeAnalysis.Storage;\n\nnamespace Microsoft.CodeAnalysis.NavigateTo\n{\n internal interface IRemoteNavigateToSearchService\n {\n ValueTask SearchFullyLoadedDocumentAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, string searchPattern, ImmutableArray kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);\n ValueTask SearchFullyLoadedProjectAsync(PinnedSolutionInfo solutionInfo, ProjectId projectId, ImmutableArray priorityDocumentIds, string searchPattern, ImmutableArray kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);\n ValueTask SearchCachedDocumentsAsync(ImmutableArray documentKeys, ImmutableArray priorityDocumentKeys, StorageDatabase database, string searchPattern, ImmutableArray kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);\n ValueTask HydrateAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken);\n\n public interface ICallback\n {\n ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result);\n }\n }\n\n [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteNavigateToSearchService)), Shared]\n internal sealed class NavigateToSearchServiceServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteNavigateToSearchService.ICallback\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public NavigateToSearchServiceServerCallbackDispatcher()\n {\n }\n\n private new NavigateToSearchServiceCallback GetCallback(RemoteServiceCallbackId callbackId)\n => (NavigateToSearchServiceCallback)base.GetCallback(callbackId);\n\n public ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result)\n => GetCallback(callbackId).OnResultFoundAsync(result);\n }\n\n internal sealed class NavigateToSearchServiceCallback\n {\n private readonly Func _onResultFound;\n\n public NavigateToSearchServiceCallback(Func onResultFound)\n {\n _onResultFound = onResultFound;\n }\n\n public async ValueTask OnResultFoundAsync(RoslynNavigateToItem result)\n => await _onResultFound(result).ConfigureAwait(false);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":418,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/ProjectSystem/TextEditApplication.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Immutable;\nusing Microsoft.CodeAnalysis.Editor.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Editor.Undo;\nusing Microsoft.CodeAnalysis.Text;\nusing Microsoft.VisualStudio.Text;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem\n{\n internal static class TextEditApplication\n {\n internal static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options)\n {\n var oldSnapshot = buffer.CurrentSnapshot;\n var oldText = oldSnapshot.AsText();\n var changes = newText.GetTextChanges(oldText);\n UpdateText(changes.ToImmutableArray(), buffer, oldSnapshot, oldText, options);\n }\n\n public static void UpdateText(ImmutableArray textChanges, ITextBuffer buffer, EditOptions options)\n {\n var oldSnapshot = buffer.CurrentSnapshot;\n var oldText = oldSnapshot.AsText();\n\n UpdateText(textChanges, buffer, oldSnapshot, oldText, options);\n }\n\n private static void UpdateText(ImmutableArray textChanges, ITextBuffer buffer, ITextSnapshot oldSnapshot, SourceText oldText, EditOptions options)\n {\n using var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null);\n if (CodeAnalysis.Workspace.TryGetWorkspace(oldText.Container, out var workspace))\n {\n var undoService = workspace.Services.GetRequiredService();\n undoService.BeginUndoTransaction(oldSnapshot);\n }\n\n foreach (var change in textChanges)\n {\n edit.Replace(change.Span.Start, change.Span.Length, change.NewText);\n }\n\n edit.ApplyAndLogExceptions();\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Immutable;\nusing Microsoft.CodeAnalysis.Editor.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Editor.Undo;\nusing Microsoft.CodeAnalysis.Text;\nusing Microsoft.VisualStudio.Text;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem\n{\n internal static class TextEditApplication\n {\n internal static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options)\n {\n var oldSnapshot = buffer.CurrentSnapshot;\n var oldText = oldSnapshot.AsText();\n var changes = newText.GetTextChanges(oldText);\n UpdateText(changes.ToImmutableArray(), buffer, oldSnapshot, oldText, options);\n }\n\n public static void UpdateText(ImmutableArray textChanges, ITextBuffer buffer, EditOptions options)\n {\n var oldSnapshot = buffer.CurrentSnapshot;\n var oldText = oldSnapshot.AsText();\n\n UpdateText(textChanges, buffer, oldSnapshot, oldText, options);\n }\n\n private static void UpdateText(ImmutableArray textChanges, ITextBuffer buffer, ITextSnapshot oldSnapshot, SourceText oldText, EditOptions options)\n {\n using var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null);\n if (CodeAnalysis.Workspace.TryGetWorkspace(oldText.Container, out var workspace))\n {\n var undoService = workspace.Services.GetRequiredService();\n undoService.BeginUndoTransaction(oldSnapshot);\n }\n\n foreach (var change in textChanges)\n {\n edit.Replace(change.Span.Start, change.Span.Length, change.NewText);\n }\n\n edit.ApplyAndLogExceptions();\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":419,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Tools/IdeCoreBenchmarks/FormatterBenchmarks.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Immutable;\nusing System.IO;\nusing System.Threading;\nusing BenchmarkDotNet.Attributes;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp.Formatting;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Options;\n\nnamespace IdeCoreBenchmarks\n{\n [MemoryDiagnoser]\n public class FormatterBenchmarks\n {\n private readonly int _iterationCount = 5;\n\n private Document _document;\n private OptionSet _options;\n\n [GlobalSetup]\n public void GlobalSetup()\n {\n var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName);\n var csFilePath = Path.Combine(roslynRoot, @\"src\\Compilers\\CSharp\\Portable\\Generated\\Syntax.xml.Syntax.Generated.cs\");\n\n if (!File.Exists(csFilePath))\n {\n throw new ArgumentException();\n }\n\n // Remove some newlines\n var text = File.ReadAllText(csFilePath).Replace(\"\", \"\")\n .Replace($\"{{{Environment.NewLine}{Environment.NewLine}\", \"{\")\n .Replace($\"}}{Environment.NewLine}{Environment.NewLine}\", \"}\")\n .Replace($\"{{{Environment.NewLine}\", \"{\")\n .Replace($\"}}{Environment.NewLine}\", \"}\")\n .Replace($\";{Environment.NewLine}\", \";\");\n\n var projectId = ProjectId.CreateNewId();\n var documentId = DocumentId.CreateNewId(projectId);\n\n var solution = new AdhocWorkspace().CurrentSolution\n .AddProject(projectId, \"ProjectName\", \"AssemblyName\", LanguageNames.CSharp)\n .AddDocument(documentId, \"DocumentName\", text);\n\n var document = solution.GetDocument(documentId);\n var root = document.GetSyntaxRootAsync(CancellationToken.None).Result.WithAdditionalAnnotations(Formatter.Annotation);\n solution = solution.WithDocumentSyntaxRoot(documentId, root);\n\n _document = solution.GetDocument(documentId);\n _options = _document.GetOptionsAsync().Result\n .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, true)\n .WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false)\n .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false);\n }\n\n [Benchmark]\n public void FormatSyntaxNode()\n {\n for (int i = 0; i < _iterationCount; ++i)\n {\n var formattedDoc = Formatter.FormatAsync(_document, Formatter.Annotation, _options, CancellationToken.None).Result;\n var formattedRoot = formattedDoc.GetSyntaxRootAsync(CancellationToken.None).Result;\n _ = formattedRoot.DescendantNodesAndSelf().ToImmutableArray();\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Immutable;\nusing System.IO;\nusing System.Threading;\nusing BenchmarkDotNet.Attributes;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp.Formatting;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Options;\n\nnamespace IdeCoreBenchmarks\n{\n [MemoryDiagnoser]\n public class FormatterBenchmarks\n {\n private readonly int _iterationCount = 5;\n\n private Document _document;\n private OptionSet _options;\n\n [GlobalSetup]\n public void GlobalSetup()\n {\n var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName);\n var csFilePath = Path.Combine(roslynRoot, @\"src\\Compilers\\CSharp\\Portable\\Generated\\Syntax.xml.Syntax.Generated.cs\");\n\n if (!File.Exists(csFilePath))\n {\n throw new ArgumentException();\n }\n\n // Remove some newlines\n var text = File.ReadAllText(csFilePath).Replace(\"\", \"\")\n .Replace($\"{{{Environment.NewLine}{Environment.NewLine}\", \"{\")\n .Replace($\"}}{Environment.NewLine}{Environment.NewLine}\", \"}\")\n .Replace($\"{{{Environment.NewLine}\", \"{\")\n .Replace($\"}}{Environment.NewLine}\", \"}\")\n .Replace($\";{Environment.NewLine}\", \";\");\n\n var projectId = ProjectId.CreateNewId();\n var documentId = DocumentId.CreateNewId(projectId);\n\n var solution = new AdhocWorkspace().CurrentSolution\n .AddProject(projectId, \"ProjectName\", \"AssemblyName\", LanguageNames.CSharp)\n .AddDocument(documentId, \"DocumentName\", text);\n\n var document = solution.GetDocument(documentId);\n var root = document.GetSyntaxRootAsync(CancellationToken.None).Result.WithAdditionalAnnotations(Formatter.Annotation);\n solution = solution.WithDocumentSyntaxRoot(documentId, root);\n\n _document = solution.GetDocument(documentId);\n _options = _document.GetOptionsAsync().Result\n .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, true)\n .WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false)\n .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false);\n }\n\n [Benchmark]\n public void FormatSyntaxNode()\n {\n for (int i = 0; i < _iterationCount; ++i)\n {\n var formattedDoc = Formatter.FormatAsync(_document, Formatter.Annotation, _options, CancellationToken.None).Result;\n var formattedRoot = formattedDoc.GetSyntaxRootAsync(CancellationToken.None).Result;\n _ = formattedRoot.DescendantNodesAndSelf().ToImmutableArray();\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":420,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/Errors/XmlSyntaxDiagnosticInfo.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Globalization;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp\n{\n internal sealed class XmlSyntaxDiagnosticInfo : SyntaxDiagnosticInfo\n {\n static XmlSyntaxDiagnosticInfo()\n {\n ObjectBinder.RegisterTypeReader(typeof(XmlSyntaxDiagnosticInfo), r => new XmlSyntaxDiagnosticInfo(r));\n }\n\n private readonly XmlParseErrorCode _xmlErrorCode;\n\n internal XmlSyntaxDiagnosticInfo(XmlParseErrorCode code, params object[] args)\n : this(0, 0, code, args)\n {\n }\n\n internal XmlSyntaxDiagnosticInfo(int offset, int width, XmlParseErrorCode code, params object[] args)\n : base(offset, width, ErrorCode.WRN_XMLParseError, args)\n {\n _xmlErrorCode = code;\n }\n\n #region Serialization\n\n protected override void WriteTo(ObjectWriter writer)\n {\n base.WriteTo(writer);\n writer.WriteUInt32((uint)_xmlErrorCode);\n }\n\n private XmlSyntaxDiagnosticInfo(ObjectReader reader)\n : base(reader)\n {\n _xmlErrorCode = (XmlParseErrorCode)reader.ReadUInt32();\n }\n\n #endregion\n\n public override string GetMessage(IFormatProvider formatProvider = null)\n {\n var culture = formatProvider as CultureInfo;\n\n string messagePrefix = this.MessageProvider.LoadMessage(this.Code, culture);\n string message = ErrorFacts.GetMessage(_xmlErrorCode, culture);\n\n System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(message));\n\n if (this.Arguments == null || this.Arguments.Length == 0)\n {\n return String.Format(formatProvider, messagePrefix, message);\n }\n\n return String.Format(formatProvider, String.Format(formatProvider, messagePrefix, message), GetArgumentsToUse(formatProvider));\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Globalization;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp\n{\n internal sealed class XmlSyntaxDiagnosticInfo : SyntaxDiagnosticInfo\n {\n static XmlSyntaxDiagnosticInfo()\n {\n ObjectBinder.RegisterTypeReader(typeof(XmlSyntaxDiagnosticInfo), r => new XmlSyntaxDiagnosticInfo(r));\n }\n\n private readonly XmlParseErrorCode _xmlErrorCode;\n\n internal XmlSyntaxDiagnosticInfo(XmlParseErrorCode code, params object[] args)\n : this(0, 0, code, args)\n {\n }\n\n internal XmlSyntaxDiagnosticInfo(int offset, int width, XmlParseErrorCode code, params object[] args)\n : base(offset, width, ErrorCode.WRN_XMLParseError, args)\n {\n _xmlErrorCode = code;\n }\n\n #region Serialization\n\n protected override void WriteTo(ObjectWriter writer)\n {\n base.WriteTo(writer);\n writer.WriteUInt32((uint)_xmlErrorCode);\n }\n\n private XmlSyntaxDiagnosticInfo(ObjectReader reader)\n : base(reader)\n {\n _xmlErrorCode = (XmlParseErrorCode)reader.ReadUInt32();\n }\n\n #endregion\n\n public override string GetMessage(IFormatProvider formatProvider = null)\n {\n var culture = formatProvider as CultureInfo;\n\n string messagePrefix = this.MessageProvider.LoadMessage(this.Code, culture);\n string message = ErrorFacts.GetMessage(_xmlErrorCode, culture);\n\n System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(message));\n\n if (this.Arguments == null || this.Arguments.Length == 0)\n {\n return String.Format(formatProvider, messagePrefix, message);\n }\n\n return String.Format(formatProvider, String.Format(formatProvider, messagePrefix, message), GetArgumentsToUse(formatProvider));\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":421,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.GetHashCodeVisitor.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Linq;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Shared.Utilities\n{\n internal partial class SymbolEquivalenceComparer\n {\n private class GetHashCodeVisitor\n {\n private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer;\n private readonly bool _compareMethodTypeParametersByIndex;\n private readonly bool _objectAndDynamicCompareEqually;\n private readonly Func _parameterAggregator;\n private readonly Func _symbolAggregator;\n\n public GetHashCodeVisitor(\n SymbolEquivalenceComparer symbolEquivalenceComparer,\n bool compareMethodTypeParametersByIndex,\n bool objectAndDynamicCompareEqually)\n {\n _symbolEquivalenceComparer = symbolEquivalenceComparer;\n _compareMethodTypeParametersByIndex = compareMethodTypeParametersByIndex;\n _objectAndDynamicCompareEqually = objectAndDynamicCompareEqually;\n _parameterAggregator = (acc, sym) => Hash.Combine(symbolEquivalenceComparer.ParameterEquivalenceComparer.GetHashCode(sym), acc);\n _symbolAggregator = (acc, sym) => GetHashCode(sym, acc);\n }\n\n public int GetHashCode(ISymbol? x, int currentHash)\n {\n if (x == null)\n return 0;\n\n x = UnwrapAlias(x);\n\n // Special case. If we're comparing signatures then we want to compare 'object'\n // and 'dynamic' as the same. However, since they're different types, we don't\n // want to bail out using the above check.\n\n if (x.Kind == SymbolKind.DynamicType ||\n (_objectAndDynamicCompareEqually && IsObjectType(x)))\n {\n return Hash.Combine(GetNullableAnnotationsHashCode((ITypeSymbol)x), Hash.Combine(typeof(IDynamicTypeSymbol), currentHash));\n }\n\n return GetHashCodeWorker(x, currentHash);\n }\n\n private int GetNullableAnnotationsHashCode(ITypeSymbol type)\n => _symbolEquivalenceComparer._ignoreNullableAnnotations ? 0 : type.NullableAnnotation.GetHashCode();\n\n private int GetHashCodeWorker(ISymbol x, int currentHash)\n => x.Kind switch\n {\n SymbolKind.ArrayType => CombineHashCodes((IArrayTypeSymbol)x, currentHash),\n SymbolKind.Assembly => CombineHashCodes((IAssemblySymbol)x, currentHash),\n SymbolKind.Event => CombineHashCodes((IEventSymbol)x, currentHash),\n SymbolKind.Field => CombineHashCodes((IFieldSymbol)x, currentHash),\n SymbolKind.Label => CombineHashCodes((ILabelSymbol)x, currentHash),\n SymbolKind.Local => CombineHashCodes((ILocalSymbol)x, currentHash),\n SymbolKind.Method => CombineHashCodes((IMethodSymbol)x, currentHash),\n SymbolKind.NetModule => CombineHashCodes((IModuleSymbol)x, currentHash),\n SymbolKind.NamedType => CombineHashCodes((INamedTypeSymbol)x, currentHash),\n SymbolKind.Namespace => CombineHashCodes((INamespaceSymbol)x, currentHash),\n SymbolKind.Parameter => CombineHashCodes((IParameterSymbol)x, currentHash),\n SymbolKind.PointerType => CombineHashCodes((IPointerTypeSymbol)x, currentHash),\n SymbolKind.Property => CombineHashCodes((IPropertySymbol)x, currentHash),\n SymbolKind.RangeVariable => CombineHashCodes((IRangeVariableSymbol)x, currentHash),\n SymbolKind.TypeParameter => CombineHashCodes((ITypeParameterSymbol)x, currentHash),\n SymbolKind.Preprocessing => CombineHashCodes((IPreprocessingSymbol)x, currentHash),\n _ => -1,\n };\n\n private int CombineHashCodes(IArrayTypeSymbol x, int currentHash)\n {\n return\n Hash.Combine(GetNullableAnnotationsHashCode(x),\n Hash.Combine(x.Rank,\n GetHashCode(x.ElementType, currentHash)));\n }\n\n private int CombineHashCodes(IAssemblySymbol x, int currentHash)\n => Hash.Combine(_symbolEquivalenceComparer._assemblyComparerOpt?.GetHashCode(x) ?? 0, currentHash);\n\n private int CombineHashCodes(IFieldSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.Name,\n GetHashCode(x.ContainingSymbol, currentHash));\n }\n\n private static int CombineHashCodes(ILabelSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.Name,\n Hash.Combine(x.Locations.FirstOrDefault(), currentHash));\n }\n\n private static int CombineHashCodes(ILocalSymbol x, int currentHash)\n => Hash.Combine(x.Locations.FirstOrDefault(), currentHash);\n\n private static int CombineHashCodes(ImmutableArray array, int currentHash, Func func)\n => array.Aggregate(currentHash, func);\n\n private int CombineHashCodes(IMethodSymbol x, int currentHash)\n {\n currentHash = Hash.Combine(x.MetadataName, currentHash);\n if (x.MethodKind == MethodKind.AnonymousFunction)\n {\n return Hash.Combine(x.Locations.FirstOrDefault(), currentHash);\n }\n\n currentHash =\n Hash.Combine(IsPartialMethodImplementationPart(x),\n Hash.Combine(IsPartialMethodDefinitionPart(x),\n Hash.Combine(x.IsDefinition,\n Hash.Combine(IsConstructedFromSelf(x),\n Hash.Combine(x.Arity,\n Hash.Combine(x.Parameters.Length,\n Hash.Combine(x.Name, currentHash)))))));\n\n var checkContainingType = CheckContainingType(x);\n if (checkContainingType)\n {\n currentHash = GetHashCode(x.ContainingSymbol, currentHash);\n }\n\n currentHash =\n CombineHashCodes(x.Parameters, currentHash, _parameterAggregator);\n\n return IsConstructedFromSelf(x)\n ? currentHash\n : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator);\n }\n\n private int CombineHashCodes(IModuleSymbol x, int currentHash)\n => CombineHashCodes(x.ContainingAssembly, Hash.Combine(x.Name, currentHash));\n\n private int CombineHashCodes(INamedTypeSymbol x, int currentHash)\n {\n currentHash = CombineNamedTypeHashCode(x, currentHash);\n\n if (x is IErrorTypeSymbol errorType)\n {\n foreach (var candidate in errorType.CandidateSymbols)\n {\n if (candidate is INamedTypeSymbol candidateNamedType)\n {\n currentHash = CombineNamedTypeHashCode(candidateNamedType, currentHash);\n }\n }\n }\n\n return currentHash;\n }\n\n private int CombineNamedTypeHashCode(INamedTypeSymbol x, int currentHash)\n {\n if (x.IsTupleType)\n {\n return Hash.Combine(currentHash, Hash.CombineValues(x.TupleElements));\n }\n\n // If we want object and dynamic to be the same, and this is 'object', then return\n // the same hash we do for 'dynamic'.\n currentHash =\n Hash.Combine((int)GetTypeKind(x),\n Hash.Combine(IsConstructedFromSelf(x),\n Hash.Combine(x.Arity,\n Hash.Combine(x.Name,\n Hash.Combine(x.IsAnonymousType,\n Hash.Combine(x.IsUnboundGenericType,\n Hash.Combine(GetNullableAnnotationsHashCode(x),\n GetHashCode(x.ContainingSymbol, currentHash))))))));\n\n if (x.IsAnonymousType)\n {\n return CombineAnonymousTypeHashCode(x, currentHash);\n }\n\n return IsConstructedFromSelf(x) || x.IsUnboundGenericType\n ? currentHash\n : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator);\n }\n\n private int CombineAnonymousTypeHashCode(INamedTypeSymbol x, int currentHash)\n {\n if (x.TypeKind == TypeKind.Delegate)\n {\n return GetHashCode(x.DelegateInvokeMethod, currentHash);\n }\n else\n {\n var xMembers = x.GetValidAnonymousTypeProperties();\n\n return xMembers.Aggregate(currentHash, (a, p) =>\n {\n return Hash.Combine(p.Name,\n Hash.Combine(p.IsReadOnly,\n GetHashCode(p.Type, a)));\n });\n }\n }\n\n private int CombineHashCodes(INamespaceSymbol x, int currentHash)\n {\n if (x.IsGlobalNamespace && _symbolEquivalenceComparer._assemblyComparerOpt == null)\n {\n // Exclude global namespace's container's hash when assemblies can differ.\n return Hash.Combine(x.Name, currentHash);\n }\n\n return\n Hash.Combine(x.IsGlobalNamespace,\n Hash.Combine(x.Name,\n GetHashCode(x.ContainingSymbol, currentHash)));\n }\n\n private int CombineHashCodes(IParameterSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.IsRefOrOut(),\n Hash.Combine(x.Name,\n GetHashCode(x.Type,\n GetHashCode(x.ContainingSymbol, currentHash))));\n }\n\n private int CombineHashCodes(IPointerTypeSymbol x, int currentHash)\n {\n return\n Hash.Combine(typeof(IPointerTypeSymbol).GetHashCode(),\n GetHashCode(x.PointedAtType, currentHash));\n }\n\n private int CombineHashCodes(IPropertySymbol x, int currentHash)\n {\n currentHash =\n Hash.Combine(x.IsIndexer,\n Hash.Combine(x.Name,\n Hash.Combine(x.Parameters.Length,\n GetHashCode(x.ContainingSymbol, currentHash))));\n\n return CombineHashCodes(x.Parameters, currentHash, _parameterAggregator);\n }\n\n private int CombineHashCodes(IEventSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.Name,\n GetHashCode(x.ContainingSymbol, currentHash));\n }\n\n public int CombineHashCodes(ITypeParameterSymbol x, int currentHash)\n {\n Debug.Assert(\n (x.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(x.DeclaringMethod!)) ||\n (x.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(x.ContainingType)) ||\n x.TypeParameterKind == TypeParameterKind.Cref);\n\n currentHash =\n Hash.Combine(x.Ordinal,\n Hash.Combine((int)x.TypeParameterKind, currentHash));\n\n if (x.TypeParameterKind == TypeParameterKind.Method && _compareMethodTypeParametersByIndex)\n {\n return currentHash;\n }\n\n if (x.TypeParameterKind == TypeParameterKind.Type && x.ContainingType.IsAnonymousType)\n {\n // Anonymous type type parameters compare by index as well to prevent\n // recursion.\n return currentHash;\n }\n\n if (x.TypeParameterKind == TypeParameterKind.Cref)\n {\n return currentHash;\n }\n\n return\n GetHashCode(x.ContainingSymbol, currentHash);\n }\n\n private static int CombineHashCodes(IRangeVariableSymbol x, int currentHash)\n => Hash.Combine(x.Locations.FirstOrDefault(), currentHash);\n\n private static int CombineHashCodes(IPreprocessingSymbol x, int currentHash)\n => Hash.Combine(x.GetHashCode(), currentHash);\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Linq;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Shared.Utilities\n{\n internal partial class SymbolEquivalenceComparer\n {\n private class GetHashCodeVisitor\n {\n private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer;\n private readonly bool _compareMethodTypeParametersByIndex;\n private readonly bool _objectAndDynamicCompareEqually;\n private readonly Func _parameterAggregator;\n private readonly Func _symbolAggregator;\n\n public GetHashCodeVisitor(\n SymbolEquivalenceComparer symbolEquivalenceComparer,\n bool compareMethodTypeParametersByIndex,\n bool objectAndDynamicCompareEqually)\n {\n _symbolEquivalenceComparer = symbolEquivalenceComparer;\n _compareMethodTypeParametersByIndex = compareMethodTypeParametersByIndex;\n _objectAndDynamicCompareEqually = objectAndDynamicCompareEqually;\n _parameterAggregator = (acc, sym) => Hash.Combine(symbolEquivalenceComparer.ParameterEquivalenceComparer.GetHashCode(sym), acc);\n _symbolAggregator = (acc, sym) => GetHashCode(sym, acc);\n }\n\n public int GetHashCode(ISymbol? x, int currentHash)\n {\n if (x == null)\n return 0;\n\n x = UnwrapAlias(x);\n\n // Special case. If we're comparing signatures then we want to compare 'object'\n // and 'dynamic' as the same. However, since they're different types, we don't\n // want to bail out using the above check.\n\n if (x.Kind == SymbolKind.DynamicType ||\n (_objectAndDynamicCompareEqually && IsObjectType(x)))\n {\n return Hash.Combine(GetNullableAnnotationsHashCode((ITypeSymbol)x), Hash.Combine(typeof(IDynamicTypeSymbol), currentHash));\n }\n\n return GetHashCodeWorker(x, currentHash);\n }\n\n private int GetNullableAnnotationsHashCode(ITypeSymbol type)\n => _symbolEquivalenceComparer._ignoreNullableAnnotations ? 0 : type.NullableAnnotation.GetHashCode();\n\n private int GetHashCodeWorker(ISymbol x, int currentHash)\n => x.Kind switch\n {\n SymbolKind.ArrayType => CombineHashCodes((IArrayTypeSymbol)x, currentHash),\n SymbolKind.Assembly => CombineHashCodes((IAssemblySymbol)x, currentHash),\n SymbolKind.Event => CombineHashCodes((IEventSymbol)x, currentHash),\n SymbolKind.Field => CombineHashCodes((IFieldSymbol)x, currentHash),\n SymbolKind.Label => CombineHashCodes((ILabelSymbol)x, currentHash),\n SymbolKind.Local => CombineHashCodes((ILocalSymbol)x, currentHash),\n SymbolKind.Method => CombineHashCodes((IMethodSymbol)x, currentHash),\n SymbolKind.NetModule => CombineHashCodes((IModuleSymbol)x, currentHash),\n SymbolKind.NamedType => CombineHashCodes((INamedTypeSymbol)x, currentHash),\n SymbolKind.Namespace => CombineHashCodes((INamespaceSymbol)x, currentHash),\n SymbolKind.Parameter => CombineHashCodes((IParameterSymbol)x, currentHash),\n SymbolKind.PointerType => CombineHashCodes((IPointerTypeSymbol)x, currentHash),\n SymbolKind.Property => CombineHashCodes((IPropertySymbol)x, currentHash),\n SymbolKind.RangeVariable => CombineHashCodes((IRangeVariableSymbol)x, currentHash),\n SymbolKind.TypeParameter => CombineHashCodes((ITypeParameterSymbol)x, currentHash),\n SymbolKind.Preprocessing => CombineHashCodes((IPreprocessingSymbol)x, currentHash),\n _ => -1,\n };\n\n private int CombineHashCodes(IArrayTypeSymbol x, int currentHash)\n {\n return\n Hash.Combine(GetNullableAnnotationsHashCode(x),\n Hash.Combine(x.Rank,\n GetHashCode(x.ElementType, currentHash)));\n }\n\n private int CombineHashCodes(IAssemblySymbol x, int currentHash)\n => Hash.Combine(_symbolEquivalenceComparer._assemblyComparerOpt?.GetHashCode(x) ?? 0, currentHash);\n\n private int CombineHashCodes(IFieldSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.Name,\n GetHashCode(x.ContainingSymbol, currentHash));\n }\n\n private static int CombineHashCodes(ILabelSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.Name,\n Hash.Combine(x.Locations.FirstOrDefault(), currentHash));\n }\n\n private static int CombineHashCodes(ILocalSymbol x, int currentHash)\n => Hash.Combine(x.Locations.FirstOrDefault(), currentHash);\n\n private static int CombineHashCodes(ImmutableArray array, int currentHash, Func func)\n => array.Aggregate(currentHash, func);\n\n private int CombineHashCodes(IMethodSymbol x, int currentHash)\n {\n currentHash = Hash.Combine(x.MetadataName, currentHash);\n if (x.MethodKind == MethodKind.AnonymousFunction)\n {\n return Hash.Combine(x.Locations.FirstOrDefault(), currentHash);\n }\n\n currentHash =\n Hash.Combine(IsPartialMethodImplementationPart(x),\n Hash.Combine(IsPartialMethodDefinitionPart(x),\n Hash.Combine(x.IsDefinition,\n Hash.Combine(IsConstructedFromSelf(x),\n Hash.Combine(x.Arity,\n Hash.Combine(x.Parameters.Length,\n Hash.Combine(x.Name, currentHash)))))));\n\n var checkContainingType = CheckContainingType(x);\n if (checkContainingType)\n {\n currentHash = GetHashCode(x.ContainingSymbol, currentHash);\n }\n\n currentHash =\n CombineHashCodes(x.Parameters, currentHash, _parameterAggregator);\n\n return IsConstructedFromSelf(x)\n ? currentHash\n : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator);\n }\n\n private int CombineHashCodes(IModuleSymbol x, int currentHash)\n => CombineHashCodes(x.ContainingAssembly, Hash.Combine(x.Name, currentHash));\n\n private int CombineHashCodes(INamedTypeSymbol x, int currentHash)\n {\n currentHash = CombineNamedTypeHashCode(x, currentHash);\n\n if (x is IErrorTypeSymbol errorType)\n {\n foreach (var candidate in errorType.CandidateSymbols)\n {\n if (candidate is INamedTypeSymbol candidateNamedType)\n {\n currentHash = CombineNamedTypeHashCode(candidateNamedType, currentHash);\n }\n }\n }\n\n return currentHash;\n }\n\n private int CombineNamedTypeHashCode(INamedTypeSymbol x, int currentHash)\n {\n if (x.IsTupleType)\n {\n return Hash.Combine(currentHash, Hash.CombineValues(x.TupleElements));\n }\n\n // If we want object and dynamic to be the same, and this is 'object', then return\n // the same hash we do for 'dynamic'.\n currentHash =\n Hash.Combine((int)GetTypeKind(x),\n Hash.Combine(IsConstructedFromSelf(x),\n Hash.Combine(x.Arity,\n Hash.Combine(x.Name,\n Hash.Combine(x.IsAnonymousType,\n Hash.Combine(x.IsUnboundGenericType,\n Hash.Combine(GetNullableAnnotationsHashCode(x),\n GetHashCode(x.ContainingSymbol, currentHash))))))));\n\n if (x.IsAnonymousType)\n {\n return CombineAnonymousTypeHashCode(x, currentHash);\n }\n\n return IsConstructedFromSelf(x) || x.IsUnboundGenericType\n ? currentHash\n : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator);\n }\n\n private int CombineAnonymousTypeHashCode(INamedTypeSymbol x, int currentHash)\n {\n if (x.TypeKind == TypeKind.Delegate)\n {\n return GetHashCode(x.DelegateInvokeMethod, currentHash);\n }\n else\n {\n var xMembers = x.GetValidAnonymousTypeProperties();\n\n return xMembers.Aggregate(currentHash, (a, p) =>\n {\n return Hash.Combine(p.Name,\n Hash.Combine(p.IsReadOnly,\n GetHashCode(p.Type, a)));\n });\n }\n }\n\n private int CombineHashCodes(INamespaceSymbol x, int currentHash)\n {\n if (x.IsGlobalNamespace && _symbolEquivalenceComparer._assemblyComparerOpt == null)\n {\n // Exclude global namespace's container's hash when assemblies can differ.\n return Hash.Combine(x.Name, currentHash);\n }\n\n return\n Hash.Combine(x.IsGlobalNamespace,\n Hash.Combine(x.Name,\n GetHashCode(x.ContainingSymbol, currentHash)));\n }\n\n private int CombineHashCodes(IParameterSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.IsRefOrOut(),\n Hash.Combine(x.Name,\n GetHashCode(x.Type,\n GetHashCode(x.ContainingSymbol, currentHash))));\n }\n\n private int CombineHashCodes(IPointerTypeSymbol x, int currentHash)\n {\n return\n Hash.Combine(typeof(IPointerTypeSymbol).GetHashCode(),\n GetHashCode(x.PointedAtType, currentHash));\n }\n\n private int CombineHashCodes(IPropertySymbol x, int currentHash)\n {\n currentHash =\n Hash.Combine(x.IsIndexer,\n Hash.Combine(x.Name,\n Hash.Combine(x.Parameters.Length,\n GetHashCode(x.ContainingSymbol, currentHash))));\n\n return CombineHashCodes(x.Parameters, currentHash, _parameterAggregator);\n }\n\n private int CombineHashCodes(IEventSymbol x, int currentHash)\n {\n return\n Hash.Combine(x.Name,\n GetHashCode(x.ContainingSymbol, currentHash));\n }\n\n public int CombineHashCodes(ITypeParameterSymbol x, int currentHash)\n {\n Debug.Assert(\n (x.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(x.DeclaringMethod!)) ||\n (x.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(x.ContainingType)) ||\n x.TypeParameterKind == TypeParameterKind.Cref);\n\n currentHash =\n Hash.Combine(x.Ordinal,\n Hash.Combine((int)x.TypeParameterKind, currentHash));\n\n if (x.TypeParameterKind == TypeParameterKind.Method && _compareMethodTypeParametersByIndex)\n {\n return currentHash;\n }\n\n if (x.TypeParameterKind == TypeParameterKind.Type && x.ContainingType.IsAnonymousType)\n {\n // Anonymous type type parameters compare by index as well to prevent\n // recursion.\n return currentHash;\n }\n\n if (x.TypeParameterKind == TypeParameterKind.Cref)\n {\n return currentHash;\n }\n\n return\n GetHashCode(x.ContainingSymbol, currentHash);\n }\n\n private static int CombineHashCodes(IRangeVariableSymbol x, int currentHash)\n => Hash.Combine(x.Locations.FirstOrDefault(), currentHash);\n\n private static int CombineHashCodes(IPreprocessingSymbol x, int currentHash)\n => Hash.Combine(x.GetHashCode(), currentHash);\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":422,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/InternalUtilities/CommandLineUtilities.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Roslyn.Utilities\n{\n internal static class CommandLineUtilities\n {\n /// \n /// Split a command line by the same rules as Main would get the commands except the original\n /// state of backslashes and quotes are preserved. For example in normal Windows command line \n /// parsing the following command lines would produce equivalent Main arguments:\n /// \n /// - /r:a,b\n /// - /r:\"a,b\"\n /// \n /// This method will differ as the latter will have the quotes preserved. The only case where \n /// quotes are removed is when the entire argument is surrounded by quotes without any inner\n /// quotes. \n /// \n /// \n /// Rules for command line parsing, according to MSDN:\n /// \n /// Arguments are delimited by white space, which is either a space or a tab.\n /// \n /// A string surrounded by double quotation marks (\"string\") is interpreted \n /// as a single argument, regardless of white space contained within. \n /// A quoted string can be embedded in an argument.\n /// \n /// A double quotation mark preceded by a backslash (\\\") is interpreted as a \n /// literal double quotation mark character (\").\n /// \n /// Backslashes are interpreted literally, unless they immediately precede a \n /// double quotation mark.\n /// \n /// If an even number of backslashes is followed by a double quotation mark, \n /// one backslash is placed in the argv array for every pair of backslashes, \n /// and the double quotation mark is interpreted as a string delimiter.\n /// \n /// If an odd number of backslashes is followed by a double quotation mark, \n /// one backslash is placed in the argv array for every pair of backslashes, \n /// and the double quotation mark is \"escaped\" by the remaining backslash, \n /// causing a literal double quotation mark (\") to be placed in argv.\n /// \n public static List SplitCommandLineIntoArguments(string commandLine, bool removeHashComments)\n {\n return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _);\n }\n\n public static List SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar)\n {\n var list = new List();\n SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar);\n return list;\n }\n\n public static void SplitCommandLineIntoArguments(ReadOnlySpan commandLine, bool removeHashComments, StringBuilder builder, List list, out char? illegalChar)\n {\n var i = 0;\n\n builder.Length = 0;\n illegalChar = null;\n while (i < commandLine.Length)\n {\n while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i]))\n {\n i++;\n }\n\n if (i == commandLine.Length)\n {\n break;\n }\n\n if (commandLine[i] == '#' && removeHashComments)\n {\n break;\n }\n\n var quoteCount = 0;\n builder.Length = 0;\n while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0)))\n {\n var current = commandLine[i];\n switch (current)\n {\n case '\\\\':\n {\n var slashCount = 0;\n do\n {\n builder.Append(commandLine[i]);\n i++;\n slashCount++;\n } while (i < commandLine.Length && commandLine[i] == '\\\\');\n\n // Slashes not followed by a quote character can be ignored for now\n if (i >= commandLine.Length || commandLine[i] != '\"')\n {\n break;\n }\n\n // If there is an odd number of slashes then it is escaping the quote\n // otherwise it is just a quote.\n if (slashCount % 2 == 0)\n {\n quoteCount++;\n }\n\n builder.Append('\"');\n i++;\n break;\n }\n\n case '\"':\n builder.Append(current);\n quoteCount++;\n i++;\n break;\n\n default:\n if ((current >= 0x1 && current <= 0x1f) || current == '|')\n {\n if (illegalChar == null)\n {\n illegalChar = current;\n }\n }\n else\n {\n builder.Append(current);\n }\n\n i++;\n break;\n }\n }\n\n // If the quote string is surrounded by quotes with no interior quotes then \n // remove the quotes here. \n if (quoteCount == 2 && builder[0] == '\"' && builder[builder.Length - 1] == '\"')\n {\n builder.Remove(0, length: 1);\n builder.Remove(builder.Length - 1, length: 1);\n }\n\n if (builder.Length > 0)\n {\n list.Add(builder.ToString());\n }\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Roslyn.Utilities\n{\n internal static class CommandLineUtilities\n {\n /// \n /// Split a command line by the same rules as Main would get the commands except the original\n /// state of backslashes and quotes are preserved. For example in normal Windows command line \n /// parsing the following command lines would produce equivalent Main arguments:\n /// \n /// - /r:a,b\n /// - /r:\"a,b\"\n /// \n /// This method will differ as the latter will have the quotes preserved. The only case where \n /// quotes are removed is when the entire argument is surrounded by quotes without any inner\n /// quotes. \n /// \n /// \n /// Rules for command line parsing, according to MSDN:\n /// \n /// Arguments are delimited by white space, which is either a space or a tab.\n /// \n /// A string surrounded by double quotation marks (\"string\") is interpreted \n /// as a single argument, regardless of white space contained within. \n /// A quoted string can be embedded in an argument.\n /// \n /// A double quotation mark preceded by a backslash (\\\") is interpreted as a \n /// literal double quotation mark character (\").\n /// \n /// Backslashes are interpreted literally, unless they immediately precede a \n /// double quotation mark.\n /// \n /// If an even number of backslashes is followed by a double quotation mark, \n /// one backslash is placed in the argv array for every pair of backslashes, \n /// and the double quotation mark is interpreted as a string delimiter.\n /// \n /// If an odd number of backslashes is followed by a double quotation mark, \n /// one backslash is placed in the argv array for every pair of backslashes, \n /// and the double quotation mark is \"escaped\" by the remaining backslash, \n /// causing a literal double quotation mark (\") to be placed in argv.\n /// \n public static List SplitCommandLineIntoArguments(string commandLine, bool removeHashComments)\n {\n return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _);\n }\n\n public static List SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar)\n {\n var list = new List();\n SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar);\n return list;\n }\n\n public static void SplitCommandLineIntoArguments(ReadOnlySpan commandLine, bool removeHashComments, StringBuilder builder, List list, out char? illegalChar)\n {\n var i = 0;\n\n builder.Length = 0;\n illegalChar = null;\n while (i < commandLine.Length)\n {\n while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i]))\n {\n i++;\n }\n\n if (i == commandLine.Length)\n {\n break;\n }\n\n if (commandLine[i] == '#' && removeHashComments)\n {\n break;\n }\n\n var quoteCount = 0;\n builder.Length = 0;\n while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0)))\n {\n var current = commandLine[i];\n switch (current)\n {\n case '\\\\':\n {\n var slashCount = 0;\n do\n {\n builder.Append(commandLine[i]);\n i++;\n slashCount++;\n } while (i < commandLine.Length && commandLine[i] == '\\\\');\n\n // Slashes not followed by a quote character can be ignored for now\n if (i >= commandLine.Length || commandLine[i] != '\"')\n {\n break;\n }\n\n // If there is an odd number of slashes then it is escaping the quote\n // otherwise it is just a quote.\n if (slashCount % 2 == 0)\n {\n quoteCount++;\n }\n\n builder.Append('\"');\n i++;\n break;\n }\n\n case '\"':\n builder.Append(current);\n quoteCount++;\n i++;\n break;\n\n default:\n if ((current >= 0x1 && current <= 0x1f) || current == '|')\n {\n if (illegalChar == null)\n {\n illegalChar = current;\n }\n }\n else\n {\n builder.Append(current);\n }\n\n i++;\n break;\n }\n }\n\n // If the quote string is surrounded by quotes with no interior quotes then \n // remove the quotes here. \n if (quoteCount == 2 && builder[0] == '\"' && builder[builder.Length - 1] == '\"')\n {\n builder.Remove(0, length: 1);\n builder.Remove(builder.Length - 1, length: 1);\n }\n\n if (builder.Length > 0)\n {\n list.Add(builder.ToString());\n }\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":423,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationAsyncResult.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\n#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n// D:\\Roslyn\\Main\\Open\\Binaries\\Debug\\Microsoft.VisualStudio.Debugger.Engine.dll\n#endregion\n\nusing System;\n\nnamespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation\n{\n public struct DkmEvaluationAsyncResult\n {\n private readonly DkmEvaluationResult _result;\n\n public DkmEvaluationAsyncResult(DkmEvaluationResult Result)\n : this()\n {\n if (Result == null)\n {\n throw new ArgumentNullException(nameof(Result));\n }\n\n _result = Result;\n }\n\n public int ErrorCode { get { throw new NotImplementedException(); } }\n\n public DkmEvaluationResult Result { get { return _result; } }\n\n internal Exception Exception { get; set; }\n\n public static DkmEvaluationAsyncResult CreateErrorResult(Exception exception)\n {\n return new DkmEvaluationAsyncResult() { Exception = exception };\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\n#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n// D:\\Roslyn\\Main\\Open\\Binaries\\Debug\\Microsoft.VisualStudio.Debugger.Engine.dll\n#endregion\n\nusing System;\n\nnamespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation\n{\n public struct DkmEvaluationAsyncResult\n {\n private readonly DkmEvaluationResult _result;\n\n public DkmEvaluationAsyncResult(DkmEvaluationResult Result)\n : this()\n {\n if (Result == null)\n {\n throw new ArgumentNullException(nameof(Result));\n }\n\n _result = Result;\n }\n\n public int ErrorCode { get { throw new NotImplementedException(); } }\n\n public DkmEvaluationResult Result { get { return _result; } }\n\n internal Exception Exception { get; set; }\n\n public static DkmEvaluationAsyncResult CreateErrorResult(Exception exception)\n {\n return new DkmEvaluationAsyncResult() { Exception = exception };\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":424,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptInlineRenameReplacementKindHelpers.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis.Editor;\nusing Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript\n{\n internal static class VSTypeScriptInlineRenameReplacementKindHelpers\n {\n public static VSTypeScriptInlineRenameReplacementKind ConvertFrom(InlineRenameReplacementKind kind)\n {\n return kind switch\n {\n InlineRenameReplacementKind.NoConflict => VSTypeScriptInlineRenameReplacementKind.NoConflict,\n InlineRenameReplacementKind.ResolvedReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict,\n InlineRenameReplacementKind.ResolvedNonReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict,\n InlineRenameReplacementKind.UnresolvedConflict => VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict,\n InlineRenameReplacementKind.Complexified => VSTypeScriptInlineRenameReplacementKind.Complexified,\n _ => throw ExceptionUtilities.UnexpectedValue(kind),\n };\n }\n\n public static InlineRenameReplacementKind ConvertTo(VSTypeScriptInlineRenameReplacementKind kind)\n {\n return kind switch\n {\n VSTypeScriptInlineRenameReplacementKind.NoConflict => InlineRenameReplacementKind.NoConflict,\n VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict => InlineRenameReplacementKind.ResolvedReferenceConflict,\n VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict => InlineRenameReplacementKind.ResolvedNonReferenceConflict,\n VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict => InlineRenameReplacementKind.UnresolvedConflict,\n VSTypeScriptInlineRenameReplacementKind.Complexified => InlineRenameReplacementKind.Complexified,\n _ => throw ExceptionUtilities.UnexpectedValue(kind),\n };\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis.Editor;\nusing Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript\n{\n internal static class VSTypeScriptInlineRenameReplacementKindHelpers\n {\n public static VSTypeScriptInlineRenameReplacementKind ConvertFrom(InlineRenameReplacementKind kind)\n {\n return kind switch\n {\n InlineRenameReplacementKind.NoConflict => VSTypeScriptInlineRenameReplacementKind.NoConflict,\n InlineRenameReplacementKind.ResolvedReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict,\n InlineRenameReplacementKind.ResolvedNonReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict,\n InlineRenameReplacementKind.UnresolvedConflict => VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict,\n InlineRenameReplacementKind.Complexified => VSTypeScriptInlineRenameReplacementKind.Complexified,\n _ => throw ExceptionUtilities.UnexpectedValue(kind),\n };\n }\n\n public static InlineRenameReplacementKind ConvertTo(VSTypeScriptInlineRenameReplacementKind kind)\n {\n return kind switch\n {\n VSTypeScriptInlineRenameReplacementKind.NoConflict => InlineRenameReplacementKind.NoConflict,\n VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict => InlineRenameReplacementKind.ResolvedReferenceConflict,\n VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict => InlineRenameReplacementKind.ResolvedNonReferenceConflict,\n VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict => InlineRenameReplacementKind.UnresolvedConflict,\n VSTypeScriptInlineRenameReplacementKind.Complexified => InlineRenameReplacementKind.Complexified,\n _ => throw ExceptionUtilities.UnexpectedValue(kind),\n };\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":425,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/Symbols/Source/SourceClonedParameterSymbol.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Symbols\n{\n /// \n /// Represents a source parameter cloned from another , when they must share attribute data and default constant value.\n /// For example, parameters on a property symbol are cloned to generate parameters on accessors.\n /// Similarly parameters on delegate invoke method are cloned to delegate begin/end invoke methods.\n /// \n internal abstract class SourceClonedParameterSymbol : SourceParameterSymbolBase\n {\n // if true suppresses params-array and default value:\n private readonly bool _suppressOptional;\n\n protected readonly SourceParameterSymbol _originalParam;\n\n internal SourceClonedParameterSymbol(SourceParameterSymbol originalParam, Symbol newOwner, int newOrdinal, bool suppressOptional)\n : base(newOwner, newOrdinal)\n {\n Debug.Assert((object)originalParam != null);\n _suppressOptional = suppressOptional;\n _originalParam = originalParam;\n }\n\n public override bool IsImplicitlyDeclared => true;\n\n public override bool IsDiscard => _originalParam.IsDiscard;\n\n public override ImmutableArray DeclaringSyntaxReferences\n {\n get\n {\n // Since you can't get from the syntax node that represents the original parameter \n // back to this symbol we decided not to return the original syntax node here.\n return ImmutableArray.Empty;\n }\n }\n\n public override bool IsParams\n {\n get { return !_suppressOptional && _originalParam.IsParams; }\n }\n\n internal override bool IsMetadataOptional\n {\n get\n {\n // pseudo-custom attributes are not suppressed:\n return _suppressOptional ? _originalParam.HasOptionalAttribute : _originalParam.IsMetadataOptional;\n }\n }\n\n internal override ConstantValue ExplicitDefaultConstantValue\n {\n get\n {\n // pseudo-custom attributes are not suppressed:\n return _suppressOptional ? _originalParam.DefaultValueFromAttributes : _originalParam.ExplicitDefaultConstantValue;\n }\n }\n\n internal override ConstantValue DefaultValueFromAttributes\n {\n get { return _originalParam.DefaultValueFromAttributes; }\n }\n\n #region Forwarded\n\n public override TypeWithAnnotations TypeWithAnnotations\n {\n get { return _originalParam.TypeWithAnnotations; }\n }\n\n public override RefKind RefKind\n {\n get { return _originalParam.RefKind; }\n }\n\n internal override bool IsMetadataIn\n {\n get { return _originalParam.IsMetadataIn; }\n }\n\n internal override bool IsMetadataOut\n {\n get { return _originalParam.IsMetadataOut; }\n }\n\n public override ImmutableArray Locations\n {\n get { return _originalParam.Locations; }\n }\n\n public override ImmutableArray GetAttributes()\n {\n return _originalParam.GetAttributes();\n }\n\n public sealed override string Name\n {\n get { return _originalParam.Name; }\n }\n\n public override ImmutableArray RefCustomModifiers\n {\n get { return _originalParam.RefCustomModifiers; }\n }\n\n internal override MarshalPseudoCustomAttributeData MarshallingInformation\n {\n get { return _originalParam.MarshallingInformation; }\n }\n\n internal override bool IsIDispatchConstant\n {\n get { return _originalParam.IsIDispatchConstant; }\n }\n\n internal override bool IsIUnknownConstant\n {\n get { return _originalParam.IsIUnknownConstant; }\n }\n\n internal override FlowAnalysisAnnotations FlowAnalysisAnnotations\n {\n get { return FlowAnalysisAnnotations.None; }\n }\n\n internal override ImmutableHashSet NotNullIfParameterNotNull\n {\n get { return ImmutableHashSet.Empty; }\n }\n\n internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable;\n\n internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable;\n\n #endregion\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Symbols\n{\n /// \n /// Represents a source parameter cloned from another , when they must share attribute data and default constant value.\n /// For example, parameters on a property symbol are cloned to generate parameters on accessors.\n /// Similarly parameters on delegate invoke method are cloned to delegate begin/end invoke methods.\n /// \n internal abstract class SourceClonedParameterSymbol : SourceParameterSymbolBase\n {\n // if true suppresses params-array and default value:\n private readonly bool _suppressOptional;\n\n protected readonly SourceParameterSymbol _originalParam;\n\n internal SourceClonedParameterSymbol(SourceParameterSymbol originalParam, Symbol newOwner, int newOrdinal, bool suppressOptional)\n : base(newOwner, newOrdinal)\n {\n Debug.Assert((object)originalParam != null);\n _suppressOptional = suppressOptional;\n _originalParam = originalParam;\n }\n\n public override bool IsImplicitlyDeclared => true;\n\n public override bool IsDiscard => _originalParam.IsDiscard;\n\n public override ImmutableArray DeclaringSyntaxReferences\n {\n get\n {\n // Since you can't get from the syntax node that represents the original parameter \n // back to this symbol we decided not to return the original syntax node here.\n return ImmutableArray.Empty;\n }\n }\n\n public override bool IsParams\n {\n get { return !_suppressOptional && _originalParam.IsParams; }\n }\n\n internal override bool IsMetadataOptional\n {\n get\n {\n // pseudo-custom attributes are not suppressed:\n return _suppressOptional ? _originalParam.HasOptionalAttribute : _originalParam.IsMetadataOptional;\n }\n }\n\n internal override ConstantValue ExplicitDefaultConstantValue\n {\n get\n {\n // pseudo-custom attributes are not suppressed:\n return _suppressOptional ? _originalParam.DefaultValueFromAttributes : _originalParam.ExplicitDefaultConstantValue;\n }\n }\n\n internal override ConstantValue DefaultValueFromAttributes\n {\n get { return _originalParam.DefaultValueFromAttributes; }\n }\n\n #region Forwarded\n\n public override TypeWithAnnotations TypeWithAnnotations\n {\n get { return _originalParam.TypeWithAnnotations; }\n }\n\n public override RefKind RefKind\n {\n get { return _originalParam.RefKind; }\n }\n\n internal override bool IsMetadataIn\n {\n get { return _originalParam.IsMetadataIn; }\n }\n\n internal override bool IsMetadataOut\n {\n get { return _originalParam.IsMetadataOut; }\n }\n\n public override ImmutableArray Locations\n {\n get { return _originalParam.Locations; }\n }\n\n public override ImmutableArray GetAttributes()\n {\n return _originalParam.GetAttributes();\n }\n\n public sealed override string Name\n {\n get { return _originalParam.Name; }\n }\n\n public override ImmutableArray RefCustomModifiers\n {\n get { return _originalParam.RefCustomModifiers; }\n }\n\n internal override MarshalPseudoCustomAttributeData MarshallingInformation\n {\n get { return _originalParam.MarshallingInformation; }\n }\n\n internal override bool IsIDispatchConstant\n {\n get { return _originalParam.IsIDispatchConstant; }\n }\n\n internal override bool IsIUnknownConstant\n {\n get { return _originalParam.IsIUnknownConstant; }\n }\n\n internal override FlowAnalysisAnnotations FlowAnalysisAnnotations\n {\n get { return FlowAnalysisAnnotations.None; }\n }\n\n internal override ImmutableHashSet NotNullIfParameterNotNull\n {\n get { return ImmutableHashSet.Empty; }\n }\n\n internal override ImmutableArray InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable;\n\n internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable;\n\n #endregion\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":426,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Test/Semantic/Semantics/SemanticErrorTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.CSharp.Test.Utilities;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\nusing static Roslyn.Test.Utilities.TestMetadata;\n\nnamespace Microsoft.CodeAnalysis.CSharp.UnitTests\n{\n /// \n /// this place is dedicated to binding related error tests\n /// \n public class SemanticErrorTests : CompilingTestBase\n {\n #region \"Targeted Error Tests - please arrange tests in the order of error code\"\n\n [Fact]\n public void CS0019ERR_BadBinaryOps01()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static void Main()\n {\n bool q = false;\n if (q == 1)\n { }\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 9, Column = 17 });\n }\n\n [Fact]\n public void CS0019ERR_BadBinaryOps02()\n {\n var text =\n@\"using System;\nenum E { A, B, C }\nenum F { X = (E.A + E.B) * DayOfWeek.Monday } // no error\nclass C\n{\n static void M(object o)\n {\n M((E.A + E.B) * DayOfWeek.Monday);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 8, Column = 12 });\n }\n\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps03()\n {\n var text =\n@\"delegate void MyDelegate1(ref int x, out float y);\nclass Program\n{\n public void DelegatedMethod1(ref int x, out float y)\n {\n y = 1;\n }\n public void DelegatedMethod2(out int x, ref float y)\n {\n x = 1;\n }\n public void DelegatedMethod3(out int x, float y = 1)\n {\n x = 1;\n }\n static void Main(string[] args)\n {\n Program mc = new Program();\n MyDelegate1 md1 = null;\n md1 += mc.DelegatedMethod1;\n md1 += mc.DelegatedMethod2; // Invalid\n md1 += mc.DelegatedMethod3; // Invalid\n md1 -= mc.DelegatedMethod1;\n md1 -= mc.DelegatedMethod2; // Invalid\n md1 -= mc.DelegatedMethod3; // Invalid\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (21,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1'\n // md1 += mc.DelegatedMethod2; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod2\").WithArguments(\"DelegatedMethod2\", \"MyDelegate1\"),\n // (22,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1'\n // md1 += mc.DelegatedMethod3; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod3\").WithArguments(\"DelegatedMethod3\", \"MyDelegate1\"),\n // (24,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1'\n // md1 -= mc.DelegatedMethod2; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod2\").WithArguments(\"DelegatedMethod2\", \"MyDelegate1\"),\n // (25,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1'\n // md1 -= mc.DelegatedMethod3; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod3\").WithArguments(\"DelegatedMethod3\", \"MyDelegate1\")\n );\n }\n\n // Method List to removal or concatenation\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps04()\n {\n var text =\n@\"using System;\ndelegate void boo();\npublic class abc\n{\n public void bar() { System.Console.WriteLine(\"\"bar\"\"); }\n static public void far() { System.Console.WriteLine(\"\"far\"\"); }\n}\nclass C\n{\n static void Main(string[] args)\n {\n abc p = new abc();\n boo goo = null;\n boo goo1 = new boo(abc.far);\n boo[] arrfoo = { p.bar, abc.far };\n goo += arrfoo; // Invalid\n goo -= arrfoo; // Invalid\n goo += new boo[] { p.bar, abc.far };\t// Invalid\n goo -= new boo[] { p.bar, abc.far };\t// Invalid\n goo += Delegate.Combine(arrfoo);\t// Invalid\n goo += Delegate.Combine(goo, goo1); \t// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo += arrfoo; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"arrfoo\").WithArguments(\"boo[]\", \"boo\"),\n // (17,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo -= arrfoo; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"arrfoo\").WithArguments(\"boo[]\", \"boo\"),\n // (18,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo += new boo[] { p.bar, abc.far };\t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new boo[] { p.bar, abc.far }\").WithArguments(\"boo[]\", \"boo\"),\n // (19,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo -= new boo[] { p.bar, abc.far };\t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new boo[] { p.bar, abc.far }\").WithArguments(\"boo[]\", \"boo\"),\n // (20,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?)\n // goo += Delegate.Combine(arrfoo);\t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"Delegate.Combine(arrfoo)\").WithArguments(\"System.Delegate\", \"boo\"),\n // (21,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?)\n // goo += Delegate.Combine(goo, goo1); \t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"Delegate.Combine(goo, goo1)\").WithArguments(\"System.Delegate\", \"boo\")\n );\n }\n\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps05()\n {\n var text =\n@\"public delegate double MyDelegate1(ref int integerPortion, out float fraction);\npublic delegate double MyDelegate2(ref int integerPortion, out float fraction);\nclass C\n{\n static void Main(string[] args)\n {\n C mc = new C();\n MyDelegate1 md1 = null;\n MyDelegate2 md2 = null;\n md1 += md2; // Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0029: Cannot implicitly convert type 'MyDelegate2' to 'MyDelegate1'\n // md1 += md2; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"md2\").WithArguments(\"MyDelegate2\", \"MyDelegate1\")\n );\n }\n\n // Anonymous method to removal or concatenation\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps06()\n {\n var text =\n@\"delegate void boo(int x);\nclass C\n{\n static void Main(string[] args)\n {\n boo goo = null;\n goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid\n goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate (string x) { System.Console.WriteLine(x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (7,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (8,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate (string x) { System.Console.WriteLine(x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (8,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\")\n );\n }\n\n // Lambda expression to removal or concatenation\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps07()\n {\n var text =\n@\"delegate void boo(int x);\nclass C\n{\n static void Main(string[] args)\n {\n boo goo = null;\n goo += (string x) => { };// Invalid\n goo -= (string x) => { };// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"(string x) => { }\").WithArguments(\"lambda expression\", \"boo\"),\n // (7,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (8,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo -= (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"(string x) => { }\").WithArguments(\"lambda expression\", \"boo\"),\n // (8,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo -= (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\")\n );\n }\n\n // Successive operator for addition and subtraction assignment\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps08()\n {\n var text =\n@\"using System;\ndelegate void boo(int x);\nclass C\n{\n public void bar(int x) { Console.WriteLine(\"\"\"\", x); }\n static public void far(int x) { Console.WriteLine(\"\"far:{0}\"\", x); }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += p.bar + far;// Invalid\n goo += (x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); } + far;// Invalid\n goo += delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); } + far;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,16): error CS0019: Operator '+' cannot be applied to operands of type 'method group' and 'method group'\n // goo += p.bar + far;// Invalid\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"p.bar + far\").WithArguments(\"+\", \"method group\", \"method group\").WithLocation(11, 16),\n // (12,16): error CS0019: Operator '+' cannot be applied to operands of type 'lambda expression' and 'method group'\n // goo += (x) => { System.Console.WriteLine(\"Lambda:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.ERR_BadBinaryOps, @\"(x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); } + far\").WithArguments(\"+\", \"lambda expression\", \"method group\").WithLocation(12, 16),\n // (12,70): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate.\n // goo += (x) => { System.Console.WriteLine(\"Lambda:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"+\").WithArguments(\"+\").WithLocation(12, 70),\n // (13,16): error CS0019: Operator '+' cannot be applied to operands of type 'anonymous method' and 'method group'\n // goo += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.ERR_BadBinaryOps, @\"delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); } + far\").WithArguments(\"+\", \"anonymous method\", \"method group\").WithLocation(13, 16),\n // (13,83): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate.\n // goo += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"+\").WithArguments(\"+\").WithLocation(13, 83)\n );\n }\n\n // Removal or concatenation for the delegate on Variance\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps09()\n {\n var text =\n@\"using System.Collections.Generic;\n\ndelegate IList Delegate1(List x);\ndelegate IEnumerable Delegate2(IList x);\ndelegate IEnumerable Delegate3(IList x);\n\nclass C\n{\n public static List Method1(IList x)\n {\n return null;\n }\n\n public static IList Method1(IList x)\n {\n return null;\n }\n static void Main(string[] args)\n {\n Delegate1 d1 = Method1;\n d1 += Method1;\n Delegate2 d2 = Method1;\n d2 += Method1;\n Delegate3 d3 = Method1;\n d1 += d2; // invalid\n d2 += d1; // invalid\n d2 += d3; // invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (25,15): error CS0029: Cannot implicitly convert type 'Delegate2' to 'Delegate1'\n // d1 += d2; // invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"d2\").WithArguments(\"Delegate2\", \"Delegate1\"),\n // (26,15): error CS0029: Cannot implicitly convert type 'Delegate1' to 'Delegate2'\n // d2 += d1; // invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"d1\").WithArguments(\"Delegate1\", \"Delegate2\"),\n // (27,15): error CS0029: Cannot implicitly convert type 'Delegate3' to 'Delegate2'\n // d2 += d3; // invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"d3\").WithArguments(\"Delegate3\", \"Delegate2\")\n );\n }\n\n // generic-delegate (goo(...)) += non generic-methodgroup(bar(...))\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps10()\n {\n var text =\n@\"delegate void boo(T x);\nclass C\n{\n public void bar(int x) { System.Console.WriteLine(\"\"bar:{0}\"\", x); }\n public void bar1(string x) { System.Console.WriteLine(\"\"bar1:{0}\"\", x); }\n\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += p.bar;// OK\n goo += p.bar1;// Invalid\n goo += (x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// OK\n goo += (string x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// Invalid\n goo += delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// OK\n goo += delegate (string x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// Invalid\n\n boo goo1 = null;\n goo1 += p.bar;// Invalid\n goo1 += p.bar1;// OK\n goo1 += (x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// OK\n goo1 += (int x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// Invalid\n goo1 += delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// Invalid\n goo1 += delegate (string x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// OK\n goo += goo1;// Invalid\n goo1 += goo;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,18): error CS0123: No overload for 'bar1' matches delegate 'boo'\n // goo += p.bar1;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"bar1\").WithArguments(\"bar1\", \"boo\"),\n // (14,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += (string x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"(string x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); }\").WithArguments(\"lambda expression\", \"boo\"),\n // (14,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += (string x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (16,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += delegate (string x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"delegate (string x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (16,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += delegate (string x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (19,19): error CS0123: No overload for 'bar' matches delegate 'boo'\n // goo1 += p.bar;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"bar\").WithArguments(\"bar\", \"boo\"),\n // (22,17): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo1 += (int x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"(int x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); }\").WithArguments(\"lambda expression\", \"boo\"),\n // (22,22): error CS1678: Parameter 1 is declared as type 'int' but should be 'string'\n // goo1 += (int x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"int\", \"\", \"string\"),\n // (23,17): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo1 += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (23,31): error CS1678: Parameter 1 is declared as type 'int' but should be 'string'\n // goo1 += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"int\", \"\", \"string\"),\n // (25,16): error CS0029: Cannot implicitly convert type 'boo' to 'boo'\n // goo += goo1;// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"goo1\").WithArguments(\"boo\", \"boo\"),\n // (26,17): error CS0029: Cannot implicitly convert type 'boo' to 'boo'\n // goo1 += goo;// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"goo\").WithArguments(\"boo\", \"boo\")\n );\n }\n\n // generic-delegate (goo(...)) += generic-methodgroup(bar(...))\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps11()\n {\n var text =\n@\"delegate void boo(T x);\nclass C\n{\n static void far(T x) { }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += far;// OK\n goo += far;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0123: No overload for 'far' matches delegate 'boo'\n // goo += far;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"far\").WithArguments(\"far\", \"boo\")\n );\n }\n\n // non generic-delegate (goo(...)) += generic-methodgroup(bar(...))\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps12()\n {\n var text =\n@\"delegate void boo(T x);\nclass C\n{\n static void far(T x) { }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += far;// OK\n goo += far;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0123: No overload for 'far' matches delegate 'boo'\n // goo += far;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"far\").WithArguments(\"far\", \"boo\")\n );\n }\n\n // distinguish '|' from '||'\n [WorkItem(540235, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540235\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps13()\n {\n var text = @\"\nclass C\n{\n int a = 1 | 1;\n int b = 1 & 1;\n int c = 1 || 1;\n int d = 1 && 1;\n\n bool e = true | true;\n bool f = true & true;\n bool g = true || true;\n bool h = true && true;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,13): error CS0019: Operator '||' cannot be applied to operands of type 'int' and 'int'\n // int c = 1 || 1;\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"1 || 1\").WithArguments(\"||\", \"int\", \"int\"),\n // (7,13): error CS0019: Operator '&&' cannot be applied to operands of type 'int' and 'int'\n // int d = 1 && 1;\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"1 && 1\").WithArguments(\"&&\", \"int\", \"int\"),\n // (4,9): warning CS0414: The field 'C.a' is assigned but its value is never used\n // int a = 1 | 1;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"a\").WithArguments(\"C.a\"),\n // (5,9): warning CS0414: The field 'C.b' is assigned but its value is never used\n // int b = 1 & 1;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"b\").WithArguments(\"C.b\"),\n // (9,10): warning CS0414: The field 'C.e' is assigned but its value is never used\n // bool e = true | true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"e\").WithArguments(\"C.e\"),\n // (10,10): warning CS0414: The field 'C.f' is assigned but its value is never used\n // bool f = true & true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"f\").WithArguments(\"C.f\"),\n // (11,10): warning CS0414: The field 'C.g' is assigned but its value is never used\n // bool g = true || true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"g\").WithArguments(\"C.g\"),\n // (12,10): warning CS0414: The field 'C.h' is assigned but its value is never used\n // bool h = true && true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"h\").WithArguments(\"C.h\"));\n }\n\n /// \n /// Conversion errors for Null Coalescing operator(??)\n /// \n [Fact]\n public void CS0019ERR_BadBinaryOps14()\n {\n var text = @\"\npublic class D { }\npublic class Error\n{\n public int? NonNullableValueType_a(int a)\n {\n int? b = null;\n int? z = a ?? b;\n return z;\n }\n public int? NonNullableValueType_b(char ch)\n {\n char b = ch;\n int? z = null ?? b;\n return z;\n }\n public int NonNullableValueType_const_a(char ch)\n {\n char b = ch;\n int z = 10 ?? b;\n return z;\n }\n public D NoPossibleConversionError()\n {\n D b = new D();\n Error a = null;\n D z = a ?? b;\n return z;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'int?'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"a ?? b\").WithArguments(\"??\", \"int\", \"int?\"),\n // (13,18): error CS0019: Operator '??' cannot be applied to operands of type '' and 'char'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null ?? b\").WithArguments(\"??\", \"\", \"char\"),\n // (19,17): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'char'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"10 ?? b\").WithArguments(\"??\", \"int\", \"char\"),\n // (26,15): error CS0019: Operator '??' cannot be applied to operands of type 'Error' and 'D'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"a ?? b\").WithArguments(\"??\", \"Error\", \"D\"));\n }\n\n [WorkItem(542115, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542115\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps15()\n {\n var text =\n@\"class C\n{\n static void M(T1 t1, T2 t2, T3 t3, T4 t4, int i, C c)\n where T2 : class\n where T3 : struct\n where T4 : T1\n {\n bool b;\n b = (t1 == t1);\n b = (t1 == t2);\n b = (t1 == t3);\n b = (t1 == t4);\n b = (t1 == i);\n b = (t1 == c);\n b = (t1 == null);\n b = (t2 == t1);\n b = (t2 == t2);\n b = (t2 == t3);\n b = (t2 == t4);\n b = (t2 == i);\n b = (t2 == c);\n b = (t2 == null);\n b = (t3 == t1);\n b = (t3 == t2);\n b = (t3 == t3);\n b = (t3 == t4);\n b = (t3 == i);\n b = (t3 == c);\n b = (t3 == null);\n b = (t4 != t1);\n b = (t4 != t2);\n b = (t4 != t3);\n b = (t4 != t4);\n b = (t4 != i);\n b = (t4 != c);\n b = (t4 != null);\n b = (i != t1);\n b = (i != t2);\n b = (i != t3);\n b = (i != t4);\n b = (i != i);\n b = (i != c);\n b = (i != null);\n b = (c != t1);\n b = (c != t2);\n b = (c != t3);\n b = (c != t4);\n b = (c != i);\n b = (c != c);\n b = (c != null);\n b = (null != t1);\n b = (null != t2);\n b = (null != t3);\n b = (null != t4);\n b = (null != i);\n b = (null != c);\n b = (null != null);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T1'\n // b = (t1 == t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t1\").WithArguments(\"==\", \"T1\", \"T1\"),\n // (10,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T2'\n // b = (t1 == t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t2\").WithArguments(\"==\", \"T1\", \"T2\"),\n // (11,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T3'\n // b = (t1 == t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t3\").WithArguments(\"==\", \"T1\", \"T3\"),\n // (12,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T4'\n // b = (t1 == t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t4\").WithArguments(\"==\", \"T1\", \"T4\"),\n // (13,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'int'\n // b = (t1 == i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == i\").WithArguments(\"==\", \"T1\", \"int\"),\n // (14,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'C'\n // b = (t1 == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == c\").WithArguments(\"==\", \"T1\", \"C\"),\n // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T1'\n // b = (t2 == t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == t1\").WithArguments(\"==\", \"T2\", \"T1\"),\n // (18,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T3'\n // b = (t2 == t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == t3\").WithArguments(\"==\", \"T2\", \"T3\"),\n // (19,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T4'\n // b = (t2 == t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == t4\").WithArguments(\"==\", \"T2\", \"T4\"),\n // (20,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'int'\n // b = (t2 == i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == i\").WithArguments(\"==\", \"T2\", \"int\"),\n // (23,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T1'\n // b = (t3 == t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t1\").WithArguments(\"==\", \"T3\", \"T1\"),\n // (24,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T2'\n // b = (t3 == t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t2\").WithArguments(\"==\", \"T3\", \"T2\"),\n // (25,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T3'\n // b = (t3 == t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t3\").WithArguments(\"==\", \"T3\", \"T3\"),\n // (26,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T4'\n // b = (t3 == t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t4\").WithArguments(\"==\", \"T3\", \"T4\"),\n // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'int'\n // b = (t3 == i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == i\").WithArguments(\"==\", \"T3\", \"int\"),\n // (28,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'C'\n // b = (t3 == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == c\").WithArguments(\"==\", \"T3\", \"C\"),\n // (29,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and ''\n // b = (t3 == null);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == null\").WithArguments(\"==\", \"T3\", \"\"),\n // (30,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T1'\n // b = (t4 != t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t1\").WithArguments(\"!=\", \"T4\", \"T1\"),\n // (31,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T2'\n // b = (t4 != t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t2\").WithArguments(\"!=\", \"T4\", \"T2\"),\n // (32,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T3'\n // b = (t4 != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t3\").WithArguments(\"!=\", \"T4\", \"T3\"),\n // (33,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T4'\n // b = (t4 != t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t4\").WithArguments(\"!=\", \"T4\", \"T4\"),\n // (34,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'int'\n // b = (t4 != i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != i\").WithArguments(\"!=\", \"T4\", \"int\"),\n // (35,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'C'\n // b = (t4 != c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != c\").WithArguments(\"!=\", \"T4\", \"C\"),\n // (37,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T1'\n // b = (i != t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t1\").WithArguments(\"!=\", \"int\", \"T1\"),\n // (38,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T2'\n // b = (i != t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t2\").WithArguments(\"!=\", \"int\", \"T2\"),\n // (39,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T3'\n // b = (i != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t3\").WithArguments(\"!=\", \"int\", \"T3\"),\n // (40,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T4'\n // b = (i != t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t4\").WithArguments(\"!=\", \"int\", \"T4\"),\n // (42,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'C'\n // b = (i != c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != c\").WithArguments(\"!=\", \"int\", \"C\"),\n // (44,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T1'\n // b = (c != t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != t1\").WithArguments(\"!=\", \"C\", \"T1\"),\n // (46,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T3'\n // b = (c != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != t3\").WithArguments(\"!=\", \"C\", \"T3\"),\n // (47,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T4'\n // b = (c != t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != t4\").WithArguments(\"!=\", \"C\", \"T4\"),\n // (48,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'int'\n // b = (c != i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != i\").WithArguments(\"!=\", \"C\", \"int\"),\n // (53,14): error CS0019: Operator '!=' cannot be applied to operands of type '' and 'T3'\n // b = (null != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null != t3\").WithArguments(\"!=\", \"\", \"T3\"),\n // (17,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // b = (t2 == t2);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"t2 == t2\"),\n // (41,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // b = (i != i);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"i != i\"),\n // (43,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // b = (i != null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != null\").WithArguments(\"true\", \"int\", \"int?\"),\n // (49,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // b = (c != c);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"c != c\"),\n // (55,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // b = (null != i);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != i\").WithArguments(\"true\", \"int\", \"int?\"));\n }\n\n [Fact]\n public void CS0019ERR_BadBinaryOps16()\n {\n var text =\n@\"class A { }\nclass B : A { }\ninterface I { }\nclass C\n{\n static void M(T t, U u, A a, B b, C c, I i)\n where T : A\n where U : B\n {\n bool x;\n x = (t == t);\n x = (t == u);\n x = (t == a);\n x = (t == b);\n x = (t == c);\n x = (t == i);\n x = (u == t);\n x = (u == u);\n x = (u == a);\n x = (u == b);\n x = (u == c);\n x = (u == i);\n x = (a == t);\n x = (a == u);\n x = (a == a);\n x = (a == b);\n x = (a == c);\n x = (a == i);\n x = (b == t);\n x = (b == u);\n x = (b == a);\n x = (b == b);\n x = (b == c);\n x = (b == i);\n x = (c == t);\n x = (c == u);\n x = (c == a);\n x = (c == b);\n x = (c == c);\n x = (c == i);\n x = (i == t);\n x = (i == u);\n x = (i == a);\n x = (i == b);\n x = (i == c);\n x = (i == i);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,14): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'C'\n // x = (t == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t == c\").WithArguments(\"==\", \"T\", \"C\"),\n // (21,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and 'C'\n // x = (u == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"u == c\").WithArguments(\"==\", \"U\", \"C\"),\n // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'A' and 'C'\n // x = (a == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"a == c\").WithArguments(\"==\", \"A\", \"C\"),\n // (33,14): error CS0019: Operator '==' cannot be applied to operands of type 'B' and 'C'\n // x = (b == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"b == c\").WithArguments(\"==\", \"B\", \"C\"),\n // (35,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'T'\n // x = (c == t);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == t\").WithArguments(\"==\", \"C\", \"T\"),\n // (36,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'U'\n // x = (c == u);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == u\").WithArguments(\"==\", \"C\", \"U\"),\n // (37,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A'\n // x = (c == a);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == a\").WithArguments(\"==\", \"C\", \"A\"),\n // (38,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'B'\n // x = (c == b);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == b\").WithArguments(\"==\", \"C\", \"B\"),\n // (11,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (t == t);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"t == t\"),\n // (18,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (u == u);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"u == u\"),\n // (25,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (a == a);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"a == a\"),\n // (32,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (b == b);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"b == b\"),\n // (39,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (c == c);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"c == c\"),\n // (46,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (i == i);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"i == i\"));\n }\n\n [Fact]\n public void CS0019ERR_BadBinaryOps17()\n {\n var text =\n@\"struct S { }\nabstract class A\n{\n internal virtual void M(U u) where U : T\n {\n bool b;\n b = (u == null);\n b = (null != u);\n }\n}\nclass B : A\n{\n internal override void M(U u)\n {\n bool b;\n b = (u == null);\n b = (null != u);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and ''\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"u == null\").WithArguments(\"==\", \"U\", \"\").WithLocation(16, 14),\n // (17,14): error CS0019: Operator '!=' cannot be applied to operands of type '' and 'U'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null != u\").WithArguments(\"!=\", \"\", \"U\").WithLocation(17, 14));\n }\n\n [Fact]\n public void CS0020ERR_IntDivByZero()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static int Main()\n {\n int s = 1 / 0; // CS0020\n return s;\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 21 } });\n }\n\n [Fact]\n public void CS0020ERR_IntDivByZero_02()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static void Main()\n {\n decimal x1 = 1.20M / 0; // CS0020\n decimal x2 = 1.20M / decimal.Zero; // CS0020\n decimal x3 = decimal.MaxValue / decimal.Zero; // CS0020\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 26 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 9, Column = 26 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 10, Column = 26 } });\n }\n\n [Fact]\n public void CS0021ERR_BadIndexLHS()\n {\n var text =\n@\"enum E { }\nclass C\n{\n static void M()\n {\n object o;\n o = M[0];\n o = ((System.Action)null)[0];\n o = ((dynamic)o)[0];\n o = default(E)[0];\n o = default(T)[0];\n o = (new C())[0];\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,13): error CS0021: Cannot apply indexing with [] to an expression of type 'method group'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"M[0]\").WithArguments(\"method group\").WithLocation(7, 13),\n // (8,13): error CS0021: Cannot apply indexing with [] to an expression of type 'System.Action'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"((System.Action)null)[0]\").WithArguments(\"System.Action\").WithLocation(8, 13),\n // (10,13): error CS0021: Cannot apply indexing with [] to an expression of type 'E'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"default(E)[0]\").WithArguments(\"E\").WithLocation(10, 13),\n // (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'T'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"default(T)[0]\").WithArguments(\"T\").WithLocation(11, 13),\n // (12,13): error CS0021: Cannot apply indexing with [] to an expression of type 'C'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"(new C())[0]\").WithArguments(\"C\").WithLocation(12, 13));\n }\n\n [Fact]\n public void CS0022ERR_BadIndexCount()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static void Main()\n {\n int[,] a = new int[10,2] ;\n a[2] = 4; //bad index count in access\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIndexCount, Line = 9, Column = 25 } });\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount02()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1 2]; //bad index count in size specifier - no initializer\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS1003: Syntax error, ',' expected\n Diagnostic(ErrorCode.ERR_SyntaxError, \"2\").WithArguments(\",\", \"\"));\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount03()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1 2] { 1 }; //bad index count in size specifier - with initializer\n }\n}\n\";\n // NOTE: Dev10 just gives a parse error on '2'\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS1003: Syntax error, ',' expected\n Diagnostic(ErrorCode.ERR_SyntaxError, \"2\").WithArguments(\",\", \"\"),\n // (6,35): error CS0846: A nested array initializer is expected\n Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, \"1\"));\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount04()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1,]; //bad index count in size specifier - no initializer\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS0443: Syntax error; value expected\n Diagnostic(ErrorCode.ERR_ValueExpected, \"\"));\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount05()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1,] { { 1 } }; //bad index count in size specifier - with initializer\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS0443: Syntax error; value expected\n Diagnostic(ErrorCode.ERR_ValueExpected, \"\"));\n }\n\n [WorkItem(539590, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp1()\n {\n var text = @\"\nnamespace X\n{\n class C\n {\n object M()\n {\n object q = new object();\n if (!q) // CS0023\n { }\n\n object obj = -null; // CS0023\n obj = !null; // CS0023\n obj = ~null; // CS0023\n\n obj++; // CS0023\n --obj; // CS0023\n return +null; // CS0023\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,17): error CS0023: Operator '!' cannot be applied to operand of type 'object'\n // if (!q) // CS0023\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"!q\").WithArguments(\"!\", \"object\").WithLocation(9, 17),\n // (12,26): error CS8310: Operator '-' cannot be applied to operand ''\n // object obj = -null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"-null\").WithArguments(\"-\", \"\").WithLocation(12, 26),\n // (13,19): error CS8310: Operator '!' cannot be applied to operand ''\n // obj = !null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"!null\").WithArguments(\"!\", \"\").WithLocation(13, 19),\n // (14,19): error CS8310: Operator '~' cannot be applied to operand ''\n // obj = ~null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"~null\").WithArguments(\"~\", \"\").WithLocation(14, 19),\n // (16,13): error CS0023: Operator '++' cannot be applied to operand of type 'object'\n // obj++; // CS0023\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"obj++\").WithArguments(\"++\", \"object\").WithLocation(16, 13),\n // (17,13): error CS0023: Operator '--' cannot be applied to operand of type 'object'\n // --obj; // CS0023\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"--obj\").WithArguments(\"--\", \"object\").WithLocation(17, 13),\n // (18,20): error CS8310: Operator '+' cannot be applied to operand ''\n // return +null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"+null\").WithArguments(\"+\", \"\").WithLocation(18, 20)\n );\n }\n\n [WorkItem(539590, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_Nullable()\n {\n var text = @\"\npublic class Test\n{\n public static void Main()\n {\n bool? b = !null; // CS0023\n int? n = ~null; // CS0023\n float? f = +null; // CS0023\n long? u = -null; // CS0023\n\n ++n;\n n--;\n --u;\n u++;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,19): error CS8310: Operator '!' cannot be applied to operand ''\n // bool? b = !null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"!null\").WithArguments(\"!\", \"\").WithLocation(6, 19),\n // (7,18): error CS8310: Operator '~' cannot be applied to operand ''\n // int? n = ~null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"~null\").WithArguments(\"~\", \"\").WithLocation(7, 18),\n // (8,20): error CS8310: Operator '+' cannot be applied to operand ''\n // float? f = +null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"+null\").WithArguments(\"+\", \"\").WithLocation(8, 20),\n // (9,19): error CS8310: Operator '-' cannot be applied to operand ''\n // long? u = -null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"-null\").WithArguments(\"-\", \"\").WithLocation(9, 19)\n );\n }\n\n [WorkItem(539590, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp2()\n {\n var text = @\"\nnamespace X\n{\n class C\n {\n void M()\n {\n System.Action f = M;\n f = +M; // CS0023\n f = +(() => { }); // CS0023\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,17): error CS0023: Operator '+' cannot be applied to operand of type 'method group'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"+M\").WithArguments(\"+\", \"method group\"),\n // (10,17): error CS0023: Operator '+' cannot be applied to operand of type 'lambda expression'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"+(() => { })\").WithArguments(\"+\", \"lambda expression\"));\n }\n\n [WorkItem(540211, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_VoidMissingInstanceMethod()\n {\n var text = @\"class C\n{\n void M()\n {\n M().Goo();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \".\").WithArguments(\".\", \"void\"));\n }\n\n [WorkItem(540211, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_VoidToString()\n {\n var text = @\"class C\n{\n void M()\n {\n M().ToString(); //plausible, but still wrong\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \".\").WithArguments(\".\", \"void\"));\n }\n\n [WorkItem(540329, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_null()\n {\n var text = @\"\nclass X\n{\n static void Main()\n {\n int x = null.Length;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"null.Length\").WithArguments(\".\", \"\"));\n }\n\n [WorkItem(540329, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_lambdaExpression()\n {\n var text = @\"\nclass X\n{\n static void Main()\n {\n System.Func f = arg => { arg = 2; return arg; }.ToString();\n \n var x = delegate { }.ToString();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"arg => { arg = 2; return arg; }.ToString\").WithArguments(\".\", \"lambda expression\"),\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"delegate { }.ToString\").WithArguments(\".\", \"anonymous method\"));\n }\n\n [Fact]\n public void CS0026ERR_ThisInStaticMeth()\n {\n var text = @\"\npublic class MyClass\n{\n public static int i = 0;\n\n public static void Main()\n {\n // CS0026\n this.i = this.i + 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 18 }\n });\n }\n\n [Fact]\n public void CS0026ERR_ThisInStaticMeth_StaticConstructor()\n {\n var text = @\"\npublic class MyClass\n{\n int f;\n void M() { }\n int P { get; set; }\n\n static MyClass()\n {\n this.f = this.P;\n this.M();\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (10,18): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (11,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"));\n }\n\n [Fact]\n public void CS0026ERR_ThisInStaticMeth_Combined()\n {\n var text = @\"\nusing System;\n\nclass CLS\n{\n static CLS() { var x = this.ToString(); }\n static object FLD = this.ToString();\n static object PROP { get { return this.ToString(); } }\n static object METHOD() { return this.ToString(); }\n}\n\nclass A : Attribute\n{\n public object P;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,25): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static object FLD = this.ToString();\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (6,28): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static CLS() { var x = this.ToString(); }\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (8,39): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static object PROP { get { return this.ToString(); } }\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (9,37): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static object METHOD() { return this.ToString(); }\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null\n // public object P;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"P\").WithArguments(\"A.P\", \"null\")\n );\n }\n\n [Fact]\n public void CS0027ERR_ThisInBadContext()\n {\n var text = @\"\nnamespace ConsoleApplication3\n{\n class MyClass\n {\n int err1 = this.Fun() + 1; // CS0027 \n public void Fun()\n {\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 6, Column = 20 } });\n }\n\n [Fact]\n public void CS0027ERR_ThisInBadContext_2()\n {\n var text = @\"\nusing System;\n\n[assembly: A(P = this.ToString())]\n\nclass A : Attribute\n{\n public object P;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,18): error CS0027: Keyword 'this' is not available in the current context\n // [assembly: A(P = this.ToString())]\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\"));\n }\n\n [Fact]\n public void CS0027ERR_ThisInBadContext_Interactive()\n {\n string text = @\"\nint a;\nint b = a;\nint c = this.a; // 1\nthis.c = // 2\n this.a; // 3\nint prop { get { return 1; } set { this.a = 1;} } // 4\n\nvoid goo() {\n this.goo(); // 5\n this.a = // 6\n this.b; // 7\n object c = this; // 8\n}\n\nthis.prop = 1; // 9\n\nclass C\n{\n C() : base()\n {\n }\n\n void goo()\n {\n this.goo(); // OK\n }\n}\";\n var comp = CreateCompilationWithMscorlib45(\n new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script) });\n comp.VerifyDiagnostics(\n // (4,9): error CS0027: Keyword 'this' is not available in the current context\n // int c = this.a; // 1\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(4, 9),\n // (5,1): error CS0027: Keyword 'this' is not available in the current context\n // this.c = // 2\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(5, 1),\n // (6,5): error CS0027: Keyword 'this' is not available in the current context\n // this.a; // 3\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(6, 5),\n // (16,1): error CS0027: Keyword 'this' is not available in the current context\n // this.prop = 1; // 9\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(16, 1),\n // (7,36): error CS0027: Keyword 'this' is not available in the current context\n // int prop { get { return 1; } set { this.a = 1;} } // 4\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(7, 36),\n // (10,5): error CS0027: Keyword 'this' is not available in the current context\n // this.goo(); // 5\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(10, 5),\n // (11,5): error CS0027: Keyword 'this' is not available in the current context\n // this.a = // 6\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(11, 5),\n // (12,9): error CS0027: Keyword 'this' is not available in the current context\n // this.b; // 7\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(12, 9),\n // (13,16): error CS0027: Keyword 'this' is not available in the current context\n // object c = this; // 8\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(13, 16)\n );\n }\n\n [Fact]\n public void CS0029ERR_NoImplicitConv01()\n {\n var text = @\"\nnamespace ConsoleApplication3\n{\n class MyClass\n {\n\n int err1 = 1; \n\n public string Fun()\n {\n return err1;\n }\n\n public static void Main()\n {\n MyClass c = new MyClass();\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConv, Line = 11, Column = 20 } });\n }\n\n [Fact]\n public void CS0029ERR_NoImplicitConv02()\n {\n var source = \"enum E { A = new[] { 1, 2, 3 } }\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,14): error CS0029: Cannot implicitly convert type 'int[]' to 'int'\n // enum E { A = new[] { 1, 2, 3 } }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new[] { 1, 2, 3 }\").WithArguments(\"int[]\", \"int\").WithLocation(1, 14));\n }\n\n [Fact]\n public void CS0029ERR_NoImplicitConv03()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n const C d = F();\n }\n static D F()\n {\n return null;\n }\n}\nclass D\n{\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,21): error CS0029: Cannot implicitly convert type 'D' to 'C'\n // const C d = F();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"F()\").WithArguments(\"D\", \"C\").WithLocation(5, 21));\n }\n\n [WorkItem(541719, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541719\")]\n [Fact]\n public void CS0029ERR_NoImplicitConv04()\n {\n var text =\n@\"class C1\n{\n public static void Main()\n {\n bool m = true;\n int[] arr = new int[m]; // Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,29): error CS0029: Cannot implicitly convert type 'bool' to 'int'\n // int[] arr = new int[m]; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"m\").WithArguments(\"bool\", \"int\").WithLocation(6, 29));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void ThrowExpression_ImplicitVoidConversion_Return()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n return true ? throw null : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,23): error CS0029: Cannot implicitly convert type '' to 'void'\n // return true ? throw null : M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"throw null\").WithArguments(\"\", \"void\").WithLocation(6, 23));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void ThrowExpression_ImplicitVoidConversion_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n object obj = true ? throw null : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,29): error CS0029: Cannot implicitly convert type '' to 'void'\n // object obj = true ? throw null : M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"throw null\").WithArguments(\"\", \"void\").WithLocation(6, 29));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void IntLiteral_ImplicitVoidConversion_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n var obj = true ? 0 : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,19): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'void'\n // var obj = true ? 0 : M2();\n Diagnostic(ErrorCode.ERR_InvalidQM, \"true ? 0 : M2()\").WithArguments(\"int\", \"void\").WithLocation(6, 19)\n );\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_ImplicitVoidConversion_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n object obj = true ? M2() : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object'\n // object obj = true ? M2() : M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"true ? M2() : M2()\").WithArguments(\"void\", \"object\").WithLocation(6, 22));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_ImplicitVoidConversion_DiscardAssignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n _ = true ? M2() : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS8209: A value of type 'void' may not be assigned.\n // _ = true ? M2() : M2();\n Diagnostic(ErrorCode.ERR_VoidAssignment, \"_\").WithLocation(6, 9));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n object obj = M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object'\n // object obj = M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"M2()\").WithArguments(\"void\", \"object\").WithLocation(6, 22));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_DiscardAssignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n _ = M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS8209: A value of type 'void' may not be assigned.\n // _ = M2();\n Diagnostic(ErrorCode.ERR_VoidAssignment, \"_\").WithLocation(6, 9));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_ImplicitVoidConversion_Return()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n return true ? M2() : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0127: Since 'C.M1()' returns void, a return keyword must not be followed by an object expression\n // return true ? M2() : M2();\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"C.M1()\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0030ERR_NoExplicitConv()\n {\n var text = @\"\nnamespace x\n{\n public class iii\n {\n public static iii operator ++(iii aa)\n {\n return (iii)0; // CS0030\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,20): error CS0030: Cannot convert type 'int' to 'x.iii'\n // return (iii)0; // CS0030\n Diagnostic(ErrorCode.ERR_NoExplicitConv, \"(iii)0\").WithArguments(\"int\", \"x.iii\"));\n }\n\n [WorkItem(528539, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539\")]\n [WorkItem(1119609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609\")]\n [WorkItem(920, \"http://github.com/dotnet/roslyn/issues/920\")]\n [Fact]\n public void CS0030ERR_NoExplicitConv02()\n {\n const string text = @\"\npublic class C\n{\n public static void Main()\n {\n decimal x = (decimal)double.PositiveInfinity;\n }\n}\";\n var diagnostics = CreateCompilation(text).GetDiagnostics();\n\n var savedCurrentCulture = Thread.CurrentThread.CurrentCulture;\n var savedCurrentUICulture = Thread.CurrentThread.CurrentUICulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;\n\n try\n {\n diagnostics.Verify(\n // (6,21): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal'\n // decimal x = (decimal)double.PositiveInfinity;\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.PositiveInfinity\").WithArguments(\"Infinity\", \"decimal\"),\n // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used\n // decimal x = (decimal)double.PositiveInfinity;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\"));\n }\n finally\n {\n Thread.CurrentThread.CurrentCulture = savedCurrentCulture;\n Thread.CurrentThread.CurrentUICulture = savedCurrentUICulture;\n }\n }\n\n [Fact]\n public void CS0030ERR_NoExplicitConv_Foreach()\n {\n var text = @\"\npublic class Test\n{\n static void Main(string[] args)\n {\n int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } };\n foreach (int outer in arr) { } // invalid\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoExplicitConv, \"foreach\").WithArguments(\"int[]\", \"int\"));\n }\n\n [Fact]\n public void CS0031ERR_ConstOutOfRange01()\n {\n var text =\n@\"public class a\n{\n int num = (int)2147483648M; //CS0031\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (3,15): error CS0031: Constant value '2147483648M' cannot be converted to a 'int'\n // int num = (int)2147483648M; //CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(int)2147483648M\").WithArguments(\"2147483648M\", \"int\"),\n // (3,9): warning CS0414: The field 'a.num' is assigned but its value is never used\n // int num = (int)2147483648M; //CS0031\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"num\").WithArguments(\"a.num\"));\n }\n\n [WorkItem(528539, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539\")]\n [Fact]\n public void CS0031ERR_ConstOutOfRange02()\n {\n var text = @\"\nenum E : ushort\n{\n A = 10,\n B = -1 // CS0031\n}\nenum F : sbyte\n{\n A = 0x7f,\n B = 0xf0, // CS0031\n C,\n D = (A + 1) - 2,\n E = (A + 1), // CS0031\n}\nclass A\n{\n byte bt = 256;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,9): error CS0031: Constant value '-1' cannot be converted to a 'ushort'\n // B = -1 // CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"-1\").WithArguments(\"-1\", \"ushort\").WithLocation(5, 9),\n // (10,9): error CS0031: Constant value '240' cannot be converted to a 'sbyte'\n // B = 0xf0, // CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"0xf0\").WithArguments(\"240\", \"sbyte\").WithLocation(10, 9),\n // (13,10): error CS0031: Constant value '128' cannot be converted to a 'sbyte'\n // E = (A + 1), // CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"A + 1\").WithArguments(\"128\", \"sbyte\").WithLocation(13, 10),\n // (17,15): error CS0031: Constant value '256' cannot be converted to a 'byte'\n // byte bt = 256;\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"256\").WithArguments(\"256\", \"byte\").WithLocation(17, 15),\n // (17,10): warning CS0414: The field 'A.bt' is assigned but its value is never used\n // byte bt = 256;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"bt\").WithArguments(\"A.bt\").WithLocation(17, 10));\n }\n\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked04()\n {\n // Confirm that we truncate the constant value before performing the range check\n var template =\n@\"public class C\n{\n void M()\n {\n System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 0.9));\n System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 1.0)); //CS0221\n System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 0.9));\n System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 1.0)); //CS0221\n }\n}\n\";\n var integralTypes = new Type[]\n {\n typeof(char),\n typeof(sbyte),\n typeof(byte),\n typeof(short),\n typeof(ushort),\n typeof(int),\n typeof(uint),\n };\n\n foreach (Type t in integralTypes)\n {\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(template.Replace(\"System.Int32\", t.ToString()),\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 });\n }\n }\n\n // Note that the errors for Int64 and UInt64 are not\n // exactly the same as for Int32, etc. above, but the\n // differences match the native compiler.\n [WorkItem(528715, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528715\")]\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked05()\n {\n // Confirm that we truncate the constant value before performing the range check\n var text1 =\n@\"public class C\n{\n void M()\n {\n System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 0.9));\n System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 1.0));\n System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 0.9)); //CS0221\n System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 1.0)); //CS0221\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text1,\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 });\n\n var text2 =\n@\"public class C\n{\n void M()\n {\n System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 0.9));\n System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 1.0)); //CS0221\n System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 0.9)); //CS0221\n System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 1.0)); //CS0221\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text2,\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 });\n\n var text3 =\n@\"class C\n{\n static void Main()\n {\n System.Console.WriteLine(long.MinValue);\n System.Console.WriteLine((long)(double)long.MinValue);\n }\n}\";\n CreateCompilation(text3).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0034ERR_AmbigBinaryOps()\n {\n #region \"Source\"\n var text = @\"\npublic class A\n{\n // allows for the conversion of A object to int\n public static implicit operator int(A s)\n {\n return 0;\n }\n\n public static implicit operator string(A i)\n {\n return null;\n }\n}\n\npublic class B\n{\n public static implicit operator int(B s)\n // one way to resolve this CS0034 is to make one conversion explicit\n // public static explicit operator int (B s)\n {\n return 0;\n }\n\n public static implicit operator string(B i)\n {\n return null;\n }\n\n public static implicit operator B(string i)\n {\n return null;\n }\n\n public static implicit operator B(int i)\n {\n return null;\n }\n}\n\npublic class C\n{\n public static void Main()\n {\n A a = new A();\n B b = new B();\n b = b + a; // CS0034\n // another way to resolve this CS0034 is to make a cast\n // b = b + (int)a;\n }\n}\n\";\n #endregion\n\n CreateCompilation(text).VerifyDiagnostics(\n // (47,13): error CS0034: Operator '+' is ambiguous on operands of type 'B' and 'A'\n // b = b + a; // CS0034\n Diagnostic(ErrorCode.ERR_AmbigBinaryOps, \"b + a\").WithArguments(\"+\", \"B\", \"A\"));\n }\n\n [Fact]\n public void CS0035ERR_AmbigUnaryOp_RoslynCS0023()\n {\n var text = @\"\nclass MyClass\n{\n private int i;\n\n public MyClass(int i)\n {\n this.i = i;\n }\n\n public static implicit operator double(MyClass x)\n {\n return (double)x.i;\n }\n\n public static implicit operator decimal(MyClass x)\n {\n return (decimal)x.i;\n }\n}\n\nclass MyClass2\n{\n static void Main()\n {\n MyClass x = new MyClass(7);\n object o = -x; // CS0035\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (27,20): error CS0035: Operator '-' is ambiguous on an operand of type 'MyClass'\n // object o = -x; // CS0035\n Diagnostic(ErrorCode.ERR_AmbigUnaryOp, \"-x\").WithArguments(\"-\", \"MyClass\"));\n }\n\n [Fact]\n public void CS0037ERR_ValueCantBeNull01()\n {\n var source =\n@\"enum E { }\nstruct S { }\nclass C\n{\n static void M()\n {\n int i;\n i = null;\n i = (int)null;\n E e;\n e = null;\n e = (E)null;\n S s;\n s = null;\n s = (S)null;\n X x;\n x = null;\n x = (X)null;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"null\").WithArguments(\"int\").WithLocation(8, 13),\n // (9,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(int)null\").WithArguments(\"int\").WithLocation(9, 13),\n // (11,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"null\").WithArguments(\"E\").WithLocation(11, 13),\n // (12,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(E)null\").WithArguments(\"E\").WithLocation(12, 13),\n // (14,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"null\").WithArguments(\"S\").WithLocation(14, 13),\n // (15,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(S)null\").WithArguments(\"S\").WithLocation(15, 13),\n // (16,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"X\").WithArguments(\"X\").WithLocation(16, 9),\n // (18,14): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"X\").WithArguments(\"X\").WithLocation(18, 14));\n }\n\n [Fact]\n public void CS0037ERR_ValueCantBeNull02()\n {\n var source =\n@\"interface I { }\nclass A { }\nclass B\n where T2 : class\n where T3 : struct\n where T4 : new()\n where T5 : I\n where T6 : A\n where T7 : T1\n{\n static void M(object o)\n {\n o = (T1)null;\n o = (T2)null;\n o = (T3)null;\n o = (T4)null;\n o = (T5)null;\n o = (T6)null;\n o = (T7)null;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,17): error CS0037: Cannot convert null to 'T1' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T1)null\").WithArguments(\"T1\").WithLocation(13, 13),\n // (15,17): error CS0037: Cannot convert null to 'T3' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T3)null\").WithArguments(\"T3\").WithLocation(15, 13),\n // (16,17): error CS0037: Cannot convert null to 'T4' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T4)null\").WithArguments(\"T4\").WithLocation(16, 13),\n // (17,17): error CS0037: Cannot convert null to 'T5' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T5)null\").WithArguments(\"T5\").WithLocation(17, 13),\n // (19,17): error CS0037: Cannot convert null to 'T7' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T7)null\").WithArguments(\"T7\").WithLocation(19, 13));\n }\n\n [WorkItem(539589, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539589\")]\n [Fact]\n public void CS0037ERR_ValueCantBeNull03()\n {\n var text = @\"\nclass Program\n{\n enum MyEnum\n {\n Zero = 0,\n One = 1\n }\n\n static int Main()\n {\n return Goo((MyEnum)null);\n }\n\n static int Goo(MyEnum x)\n {\n return 1;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(MyEnum)null\").WithArguments(\"Program.MyEnum\").WithLocation(12, 20));\n }\n\n [Fact(), WorkItem(528875, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528875\")]\n public void CS0038ERR_WrongNestedThis()\n {\n var text = @\"\nclass OuterClass\n{\n public int count;\n // try the following line instead\n // public static int count;\n\n class InnerClass\n {\n void func()\n {\n // or, create an instance\n // OuterClass class_inst = new OuterClass();\n // int count2 = class_inst.count;\n int count2 = count; // CS0038\n }\n }\n\n public static void Main()\n {\n }\n}\";\n // Triage decided not to implement the more specific error (WrongNestedThis) and stick with ObjectRequired.\n var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary()\n {\n { MessageProvider.Instance.GetIdForErrorCode(649), ReportDiagnostic.Suppress }\n }));\n\n comp.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ObjectRequired, \"count\").WithArguments(\"OuterClass.count\"));\n }\n\n [Fact]\n public void CS0039ERR_NoExplicitBuiltinConv01()\n {\n var text =\n@\"class A\n{\n}\nclass B: A\n{\n}\nclass C: A\n{\n}\nclass M\n{\n static void Main()\n {\n A a = new C();\n B b = new B();\n C c;\n\n // This is valid; there is a built-in reference\n // conversion from A to C.\n c = a as C; \n\n //The following generates CS0039; there is no\n // built-in reference conversion from B to C.\n c = b as C; // CS0039\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (24,13): error CS0039: Cannot convert type 'B' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion\n Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, \"b as C\").WithArguments(\"B\", \"C\").WithLocation(24, 13));\n }\n\n [Fact, WorkItem(541142, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541142\")]\n public void CS0039ERR_NoExplicitBuiltinConv02()\n {\n var text =\n@\"delegate void D();\nclass C\n{\n static void M(C c)\n {\n (F as D)();\n (c.F as D)();\n (G as D)();\n }\n void F() { }\n static void G() { }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // (F as D)();\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"F as D\").WithLocation(6, 10),\n // (7,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // (c.F as D)();\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"c.F as D\").WithLocation(7, 10),\n // (8,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // (G as D)();\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"G as D\").WithLocation(8, 10));\n }\n\n [Fact, WorkItem(542047, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542047\")]\n public void CS0039ERR_ConvTypeReferenceToObject()\n {\n var text = @\"using System;\nclass C\n{\n static void Main()\n {\n TypedReference a = new TypedReference();\n object obj = a as object; //CS0039\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n //(7,22): error CS0039: Cannot convert type 'System.TypedReference' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion\n Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, \"a as object\").WithArguments(\"System.TypedReference\", \"object\").WithLocation(7, 22));\n }\n\n [Fact]\n public void CS0069ERR_EventPropertyInInterface()\n {\n var text = @\"\ninterface I\n{\n event System.Action E1 { add; }\n event System.Action E2 { remove; }\n event System.Action E3 { add; remove; }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(\n // (4,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E1 { add; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"add\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(4, 30),\n // (4,33): error CS0073: An add or remove accessor must have a body\n // event System.Action E1 { add; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(4, 33),\n // (5,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E2 { remove; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"remove\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(5, 30),\n // (5,36): error CS0073: An add or remove accessor must have a body\n // event System.Action E2 { remove; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(5, 36),\n // (6,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"add\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(6, 30),\n // (6,33): error CS0073: An add or remove accessor must have a body\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(6, 33),\n // (6,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"remove\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(6, 35),\n // (6,41): error CS0073: An add or remove accessor must have a body\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(6, 41),\n // (4,25): error CS0065: 'I.E1': event property must have both add and remove accessors\n // event System.Action E1 { add; }\n Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, \"E1\").WithArguments(\"I.E1\").WithLocation(4, 25),\n // (5,25): error CS0065: 'I.E2': event property must have both add and remove accessors\n // event System.Action E2 { remove; }\n Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, \"E2\").WithArguments(\"I.E2\").WithLocation(5, 25));\n }\n\n [Fact]\n public void CS0070ERR_BadEventUsage()\n {\n var text = @\"\npublic delegate void EventHandler();\n\npublic class A\n{\n public event EventHandler Click;\n\n public static void OnClick()\n {\n EventHandler eh;\n A a = new A();\n eh = a.Click;\n }\n\n public static void Main()\n {\n }\n}\n\npublic class B\n{\n public int mf ()\n {\n EventHandler eh = new EventHandler(A.OnClick);\n A a = new A();\n eh = a.Click; // CS0070\n // try the following line instead\n // a.Click += eh;\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsage, Line = 26, Column = 14 } });\n }\n\n [Fact]\n public void CS0079ERR_BadEventUsageNoField()\n {\n var text = @\"\npublic delegate void MyEventHandler();\n\npublic class Class1\n{\n private MyEventHandler _e;\n\n public event MyEventHandler Pow\n {\n add\n {\n _e += value;\n }\n remove\n {\n _e -= value;\n }\n }\n\n public void Handler()\n {\n }\n\n public void Fire()\n {\n if (_e != null)\n {\n Pow(); // CS0079\n // try the following line instead\n // _e();\n }\n }\n\n public static void Main()\n {\n Class1 p = new Class1();\n p.Pow += new MyEventHandler(p.Handler);\n p._e();\n p.Pow += new MyEventHandler(p.Handler);\n p._e();\n p._e -= new MyEventHandler(p.Handler);\n if (p._e != null)\n {\n p._e();\n }\n p.Pow -= new MyEventHandler(p.Handler);\n if (p._e != null)\n {\n p._e();\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsageNoField, Line = 28, Column = 13 } });\n }\n\n [WorkItem(538213, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538213\")]\n [Fact]\n public void CS0103ERR_NameNotInContext()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n IO.File.Exists(\"\"test\"\");\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"IO\").WithArguments(\"IO\").WithLocation(6, 9));\n }\n\n [WorkItem(542574, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542574\")]\n [Fact]\n public void CS0103ERR_NameNotInContextLambdaExtension()\n {\n var text = @\"using System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] sourceA = { 1, 2, 3, 4, 5 };\n int[] sourceB = { 3, 4, 5, 6, 7 };\n\n var query = sourceA.Join(sourceB, a => b, b => 5, (a, b) => a + b);\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"b\").WithArguments(\"b\").WithLocation(9, 48));\n }\n\n [Fact()]\n public void CS0103ERR_NameNotInContext_foreach()\n {\n var text = @\"class C\n{\n static void Main()\n {\n foreach (var y in new[] {new {y = y }}){ }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"y\").WithArguments(\"y\").WithLocation(5, 43));\n }\n\n [WorkItem(528780, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528780\")]\n [Fact]\n public void CS0103ERR_NameNotInContext_namedAndOptional()\n {\n var text = @\"using System;\nclass NamedExample\n{\n static void Main(string[] args)\n {\n }\n static int CalculateBMI(int weight, int height = weight)\n {\n return (weight * 703) / (height * height);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,54): error CS0103: The name 'weight' does not exist in the current context\n // static int CalculateBMI(int weight, int height = weight)\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"weight\").WithArguments(\"weight\").WithLocation(7, 54),\n // (1,1): hidden CS8019: Unnecessary using directive.\n // using System;\n Diagnostic(ErrorCode.HDN_UnusedUsingDirective, \"using System;\").WithLocation(1, 1)\n );\n }\n\n [Fact]\n public void CS0118ERR_BadSKknown()\n {\n CreateCompilation(\n@\"public class TestType {}\n\npublic class MyClass {\n\n public static int Main() {\n TestType myTest = new TestType();\n bool b = myTest is myTest;\n return 1;\n }\n\n}\", parseOptions: TestOptions.Regular6)\n .VerifyDiagnostics(\n // (7,22): error CS0118: 'myTest' is a 'variable' but is used like a 'type'\n Diagnostic(ErrorCode.ERR_BadSKknown, \"myTest\").WithArguments(\"myTest\", \"variable\", \"type\"));\n }\n\n [Fact]\n public void CS0118ERR_BadSKknown_02()\n {\n CreateCompilation(@\"\nusing System;\npublic class P {\n public static void Main(string[] args) {\n#pragma warning disable 219\n Action a = null;\n Action b = null;\n }\n}\")\n .VerifyDiagnostics(\n // (6,16): error CS0118: 'args' is a variable but is used like a type\n // Action a = null;\n Diagnostic(ErrorCode.ERR_BadSKknown, \"args\").WithArguments(\"args\", \"variable\", \"type\").WithLocation(6, 16),\n // (7,16): error CS0118: 'a' is a variable but is used like a type\n // Action b = null;\n Diagnostic(ErrorCode.ERR_BadSKknown, \"a\").WithArguments(\"a\", \"variable\", \"type\").WithLocation(7, 16));\n }\n\n\n [Fact]\n public void CS0118ERR_BadSKknown_CheckedUnchecked()\n {\n string source = @\"\nusing System;\n \nclass Program\n{\n static void Main()\n {\n\t\tvar z = 1;\n \n\t\t(Console).WriteLine(); // error\n (System).Console.WriteLine(); // error\n checked(Console).WriteLine(); // error \n checked(System).Console.WriteLine(); // error\n\n checked(z).ToString(); // ok\n checked(typeof(Console)).ToString(); // ok\n checked(Console.WriteLine)(); // ok\n checked(z) = 1; // ok\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,4): error CS0119: 'System.Console' is a type, which is not valid in the given context\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"Console\").WithArguments(\"System.Console\", \"type\"),\n // (11,10): error CS0118: 'System' is a namespace but is used like a variable\n Diagnostic(ErrorCode.ERR_BadSKknown, \"System\").WithArguments(\"System\", \"namespace\", \"variable\"),\n // (12,17): error CS0119: 'System.Console' is a type, which is not valid in the given context\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"Console\").WithArguments(\"System.Console\", \"type\"),\n // (13,17): error CS0118: 'System' is a namespace but is used like a variable\n Diagnostic(ErrorCode.ERR_BadSKknown, \"System\").WithArguments(\"System\", \"namespace\", \"variable\"));\n }\n\n [WorkItem(542773, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542773\")]\n [Fact]\n public void CS0119ERR_BadSKunknown01_switch()\n {\n CreateCompilation(\n@\"class A\n{\n public static void Main()\n { }\n void goo(color color1)\n {\n switch (color)\n {\n default:\n break;\n }\n }\n}\nenum color\n{\n blue,\n green\n}\n\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadSKunknown, \"color\").WithArguments(\"color\", \"type\"));\n }\n\n [Fact, WorkItem(538214, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214\"), WorkItem(528703, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528703\")]\n public void CS0119ERR_BadSKunknown01()\n {\n var source =\n@\"class Test\n{\n public static void M()\n {\n int x = 0;\n x = (global::System.Int32) + x;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,14): error CS0119: 'int' is a type, which is not valid in the given context\n // x = (global::System.Int32) + x;\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"global::System.Int32\").WithArguments(\"int\", \"type\"),\n // (6,14): error CS0119: 'int' is a type, which is not valid in the given context\n // x = (global::System.Int32) + x;\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"global::System.Int32\").WithArguments(\"int\", \"type\"));\n }\n\n [Fact]\n public void CS0119ERR_BadSKunknown02()\n {\n var source =\n@\"class A\n{\n internal static object F;\n internal static void M() { }\n}\nclass B where T : A\n{\n static void M(T t)\n {\n U.ReferenceEquals(T.F, null);\n T.M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,27): error CS0119: 'T' is a type parameter, which is not valid in the given context\n // U.ReferenceEquals(T.F, null);\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"T\").WithArguments(\"T\", \"type parameter\"),\n // (10,9): error CS0119: 'U' is a type parameter, which is not valid in the given context\n // U.ReferenceEquals(T.F, null);\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"U\").WithArguments(\"U\", \"type parameter\"),\n // (11,9): error CS0119: 'T' is a type parameter, which is not valid in the given context\n // T.M();\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"T\").WithArguments(\"T\", \"type parameter\"),\n // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null\n // internal static object F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"A.F\", \"null\")\n );\n }\n\n [WorkItem(541203, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541203\")]\n [Fact]\n public void CS0119ERR_BadSKunknown_InThrowStmt()\n {\n CreateCompilation(\n@\"class Test\n{\n public static void M()\n {\n throw System.Exception;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"System.Exception\").WithArguments(\"System.Exception\", \"type\"));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue01()\n {\n var source =\n@\"namespace x\n{\n public class C\n {\n const int x = 1;\n\n const int a = x + b;\n const int b = x + c;\n const int c = x + d;\n const int d = x + e;\n const int e = x + a;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,19): error CS0110: The evaluation of the constant value for 'x.C.a' involves a circular definition\n // const int a = x + b;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"a\").WithArguments(\"x.C.a\").WithLocation(7, 19));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue02()\n {\n var source =\n@\"enum E { A = B, B = A }\nenum F { X, Y = Y }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition\n // enum E { A = B, B = A }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"A\").WithArguments(\"E.A\").WithLocation(1, 10),\n // (2,13): error CS0110: The evaluation of the constant value for 'F.Y' involves a circular definition\n // enum F { X, Y = Y }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"Y\").WithArguments(\"F.Y\").WithLocation(2, 13));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue03()\n {\n var source =\n@\"enum E { A, B = A } // no error\nenum F { W, X = Z, Y, Z }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (2,13): error CS0110: The evaluation of the constant value for 'F.X' involves a circular definition\n // enum F { W, X = Z, Y, Z }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"X\").WithArguments(\"F.X\").WithLocation(2, 13));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue04()\n {\n var source =\n@\"enum E { A = B, B }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition\n // enum E { A = B, B }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"A\").WithArguments(\"E.A\").WithLocation(1, 10));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue05()\n {\n var source =\n@\"enum E { A = C, B = C, C }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,17): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition\n // enum E { A = C, B = C, C }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"B\").WithArguments(\"E.B\").WithLocation(1, 17));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue06()\n {\n var source =\n@\"class C\n{\n private const int F = (int)E.B;\n enum E { A = F, B }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,23): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition\n // private const int F = (int)E.B;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"F\").WithArguments(\"C.F\").WithLocation(3, 23));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue07()\n {\n // Should report errors from other subexpressions\n // in addition to circular reference.\n var source =\n@\"class C\n{\n const int F = (long)(F + F + G);\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,34): error CS0103: The name 'G' does not exist in the current context\n // const int F = (long)(F + F + G);\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"G\").WithArguments(\"G\").WithLocation(3, 34),\n // (3,15): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition\n // const int F = (long)(F + F + G);\n Diagnostic(ErrorCode.ERR_CircConstValue, \"F\").WithArguments(\"C.F\").WithLocation(3, 15));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue08()\n {\n // Decimal constants are special (since they're not runtime constants).\n var source =\n@\"class C\n{\n const decimal D = D;\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,19): error CS0110: The evaluation of the constant value for 'C.D' involves a circular definition\n // const decimal D = D;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"D\").WithArguments(\"C.D\").WithLocation(3, 19));\n }\n\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_1()\n {\n var test = @\"\nint x;\n\";\n CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics(\n // (2,5): warning CS0168: The variable 'x' is declared but never used\n // int x;\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"x\").WithArguments(\"x\").WithLocation(2, 5)\n );\n }\n\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_2()\n {\n var test = @\"\nnamespace x\n{\n using System;\n void Method(string str) // CS0116\n {\n Console.WriteLine(str);\n }\n}\nint AIProp { get ; set ; }\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test,\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 10 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 10, Column = 5 });\n }\n\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_3()\n {\n var test = @\"\nnamespace ns1\n{\n goto Labl; // Invalid\n const int x = 1;\n Lab1:\n const int y = 2;\n}\n\";\n // TODO (tomat): EOFUnexpected shouldn't be reported if we enable parsing global statements in namespaces\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test,\n // (4,5): error CS1022: Type or namespace definition, or end-of-file expected\n // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods\n // (4,14): error CS1022: Type or namespace definition, or end-of-file expected\n // (6,5): error CS0116: A namespace does not directly contain members such as fields or methods\n // (6,9): error CS1022: Type or namespace definition, or end-of-file expected\n // (5,15): error CS0116: A namespace does not directly contain members such as fields or methods\n // (7,15): error CS0116: A namespace does not directly contain members such as fields or methods\n new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 5 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 4, Column = 10 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 14 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 6, Column = 5 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 6, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 7, Column = 15 });\n }\n\n [WorkItem(540091, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091\")]\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_4()\n {\n var test = @\"\ndelegate int D();\nD d = null;\n\";\n CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics(\n // (3,1): error CS8803: Top-level statements must precede namespace and type declarations.\n // D d = null;\n Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, \"D d = null;\").WithLocation(3, 1),\n // (3,3): warning CS0219: The variable 'd' is assigned but its value is never used\n // D d = null;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"d\").WithArguments(\"d\").WithLocation(3, 3)\n );\n }\n\n [WorkItem(540091, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091\")]\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_5()\n {\n var test = @\"\ndelegate int D();\nD d = {;}\n\";\n // In this case, CS0116 is suppressed because of the syntax errors\n\n CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics(\n // (3,1): error CS8803: Top-level statements must precede namespace and type declarations.\n // D d = {;}\n Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, \"D d = {;\").WithLocation(3, 1),\n // (3,8): error CS1513: } expected\n Diagnostic(ErrorCode.ERR_RbraceExpected, \";\"),\n // (3,9): error CS1022: Type or namespace definition, or end-of-file expected\n Diagnostic(ErrorCode.ERR_EOFExpected, \"}\"),\n // (3,7): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead.\n Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, \"{\"));\n }\n\n [WorkItem(539129, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539129\")]\n [Fact]\n public void CS0117ERR_NoSuchMember()\n {\n CreateCompilation(\n@\"enum E { }\nclass C\n{\n static void M()\n {\n C.F(E.A);\n C.P = C.Q;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"F\").WithArguments(\"C\", \"F\"),\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"A\").WithArguments(\"E\", \"A\"),\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"P\").WithArguments(\"C\", \"P\"),\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"Q\").WithArguments(\"C\", \"Q\"));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired01()\n {\n CreateCompilation(\n@\"class C\n{\n object field;\n object Property { get; set; }\n void Method() { }\n static void M()\n {\n field = Property;\n C.field = C.Property;\n Method();\n C.Method();\n }\n}\n\")\n .VerifyDiagnostics(\n // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\").WithLocation(8, 9),\n // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\").WithLocation(8, 17),\n // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.field\").WithArguments(\"C.field\").WithLocation(9, 9),\n // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Property\").WithArguments(\"C.Property\").WithLocation(9, 19),\n // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\").WithLocation(10, 9),\n // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // C.Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Method\").WithArguments(\"C.Method()\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired02()\n {\n CreateCompilation(\n@\"using System;\n\nclass Program\n{\n private readonly int v = 5;\n delegate int del(int i);\n static void Main(string[] args)\n {\n del myDelegate = (int x) => x * v;\n Console.Write(string.Concat(myDelegate(7), \"\"he\"\"));\n }\n}\")\n .VerifyDiagnostics(\n // (9,41): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"v\").WithArguments(\"Program.v\"));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired03()\n {\n var source =\n@\"delegate int boo();\ninterface I\n{\n int bar();\n}\npublic struct abc : I\n{\n public int bar() { System.Console.WriteLine(\"\"bar\"\"); return 0x01; }\n}\nclass C\n{\n static void Main(string[] args)\n {\n abc p = new abc();\n boo goo = null;\n goo += new boo(I.bar);\n goo();\n }\n}\";\n CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(\n // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()'\n // goo += new boo(I.bar);\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"I.bar\").WithArguments(\"I.bar()\"),\n // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used\n // abc p = new abc();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"p\").WithArguments(\"p\")\n );\n CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics(\n // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()'\n // goo += new boo(I.bar);\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"I.bar\").WithArguments(\"I.bar()\").WithLocation(16, 24),\n // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used\n // abc p = new abc();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"p\").WithArguments(\"p\").WithLocation(14, 13)\n );\n }\n\n [WorkItem(543950, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543950\")]\n [Fact]\n public void CS0120ERR_ObjectRequired04()\n {\n CreateCompilation(\n@\"using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n var f = new Func(() => ToString());\n var g = new Func(() => GetHashCode());\n }\n}\")\n .VerifyDiagnostics(\n // (7,40): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()'\n // var f = new Func(() => ToString());\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"ToString\").WithArguments(\"object.ToString()\"),\n // (8,37): error CS0120: An object reference is required for the non-static field, method, or property 'object.GetHashCode()'\n // var g = new Func(() => GetHashCode());\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"GetHashCode\").WithArguments(\"object.GetHashCode()\")\n );\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired_ConstructorInitializer()\n {\n CreateCompilation(\n@\"class B\n{\n public B(params int[] p) { }\n}\n\nclass C : B\n{\n int instanceField;\n static int staticField;\n\n int InstanceProperty { get; set; }\n static int StaticProperty { get; set; }\n\n int InstanceMethod() { return 0; }\n static int StaticMethod() { return 0; }\n\n C(int param) : base(\n param,\n instanceField, //CS0120\n staticField,\n InstanceProperty, //CS0120\n StaticProperty,\n InstanceMethod(), //CS0120\n StaticMethod(),\n this.instanceField, //CS0027\n C.staticField,\n this.InstanceProperty, //CS0027\n C.StaticProperty,\n this.InstanceMethod(), //CS0027\n C.StaticMethod()) \n { \n }\n}\n\")\n .VerifyDiagnostics(\n // (19,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.instanceField'\n // instanceField, //CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"instanceField\").WithArguments(\"C.instanceField\").WithLocation(19, 9),\n // (21,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceProperty'\n // InstanceProperty, //CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"InstanceProperty\").WithArguments(\"C.InstanceProperty\").WithLocation(21, 9),\n // (23,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceMethod()'\n // InstanceMethod(), //CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"InstanceMethod\").WithArguments(\"C.InstanceMethod()\").WithLocation(23, 9),\n // (25,9): error CS0027: Keyword 'this' is not available in the current context\n // this.instanceField, //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(25, 9),\n // (27,9): error CS0027: Keyword 'this' is not available in the current context\n // this.InstanceProperty, //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(27, 9),\n // (29,9): error CS0027: Keyword 'this' is not available in the current context\n // this.InstanceMethod(), //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(29, 9),\n // (8,9): warning CS0649: Field 'C.instanceField' is never assigned to, and will always have its default value 0\n // int instanceField;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"instanceField\").WithArguments(\"C.instanceField\", \"0\").WithLocation(8, 9),\n // (9,16): warning CS0649: Field 'C.staticField' is never assigned to, and will always have its default value 0\n // static int staticField;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"staticField\").WithArguments(\"C.staticField\", \"0\").WithLocation(9, 16));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired_StaticConstructor()\n {\n CreateCompilation(\n@\"class C\n{\n object field;\n object Property { get; set; }\n void Method() { }\n static C()\n {\n field = Property;\n C.field = C.Property;\n Method();\n C.Method();\n }\n}\n\")\n .VerifyDiagnostics(\n // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\").WithLocation(8, 9),\n // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\").WithLocation(8, 17),\n // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.field\").WithArguments(\"C.field\").WithLocation(9, 9),\n // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Property\").WithArguments(\"C.Property\").WithLocation(9, 19),\n // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\").WithLocation(10, 9),\n // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // C.Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Method\").WithArguments(\"C.Method()\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired_NestedClass()\n {\n CreateCompilation(\n@\"\nclass C\n{\n object field;\n object Property { get; set; }\n void Method() { }\n\n class D\n {\n object field2;\n object Property2 { get; set; }\n\n public void Goo() \n {\n object f = field;\n object p = Property;\n Method();\n }\n\n public static void Bar() \n {\n object f1 = field;\n object p1 = Property;\n Method();\n\n object f2 = field2;\n object p2 = Property2;\n Goo();\n }\n }\n\n class E : C\n {\n public void Goo() \n {\n object f3 = field;\n object p3 = Property;\n Method();\n }\n }\n}\")\n .VerifyDiagnostics(\n // (15,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // object f = field;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\"),\n // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // object p = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\"),\n // (17,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\"),\n // (22,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // object f1 = field;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\"),\n // (23,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // object p1 = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\"),\n // (24,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\"),\n // (26,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.field2'\n // object f2 = field2;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field2\").WithArguments(\"C.D.field2\"),\n // (27,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Property2'\n // object p2 = Property2;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property2\").WithArguments(\"C.D.Property2\"),\n // (28,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Goo()'\n // Goo();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Goo\").WithArguments(\"C.D.Goo()\"),\n // (4,12): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null\n // object field;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"field\").WithArguments(\"C.field\", \"null\"),\n // (10,16): warning CS0649: Field 'C.D.field2' is never assigned to, and will always have its default value null\n // object field2;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"field2\").WithArguments(\"C.D.field2\", \"null\"));\n }\n\n [Fact, WorkItem(541505, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505\")]\n public void CS0120ERR_ObjectRequired_Attribute()\n {\n var text = @\"\nusing System.ComponentModel;\nenum ProtectionLevel\n{\n Privacy = 0\n}\nclass F\n{\n [DefaultValue(Prop.Privacy)] // CS0120\n ProtectionLevel Prop { get { return 0; } }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,17): error CS0120: An object reference is required for the non-static field, method, or property 'F.Prop'\n // [DefaultValue(Prop.Privacy)] // CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Prop\").WithArguments(\"F.Prop\"),\n // (9,17): error CS0176: Member 'ProtectionLevel.Privacy' cannot be accessed with an instance reference; qualify it with a type name instead\n // [DefaultValue(Prop.Privacy)] // CS0120\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"Prop.Privacy\").WithArguments(\"ProtectionLevel.Privacy\") // Extra In Roslyn\n );\n }\n\n [Fact]\n public void CS0121ERR_AmbigCall()\n {\n var text = @\"\npublic class C\n{\n void f(int i, double d) { }\n void f(double d, int i) { }\n\n public static void Main()\n {\n new C().f(1, 1); // CS0121\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.f(int, double)' and 'C.f(double, int)'\n // new C().f(1, 1); // CS0121\n Diagnostic(ErrorCode.ERR_AmbigCall, \"f\").WithArguments(\"C.f(int, double)\", \"C.f(double, int)\")\n );\n }\n\n [WorkItem(539817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539817\")]\n [Fact]\n public void CS0122ERR_BadAccess()\n {\n var text = @\"\nclass Base\n{\n private class P { int X; }\n}\n\nclass Test : Base\n{\n void M()\n {\n object o = (P p) => 0;\n int x = P.X;\n int y = (P)null;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,21): error CS0122: 'Base.P' is inaccessible due to its protection level\n // object o = (P p) => 0;\n Diagnostic(ErrorCode.ERR_BadAccess, \"P\").WithArguments(\"Base.P\"),\n // (12,17): error CS0122: 'Base.P' is inaccessible due to its protection level\n // int x = P.X;\n Diagnostic(ErrorCode.ERR_BadAccess, \"P\").WithArguments(\"Base.P\"),\n // (13,18): error CS0122: 'Base.P' is inaccessible due to its protection level\n // int y = (P)null;\n Diagnostic(ErrorCode.ERR_BadAccess, \"P\").WithArguments(\"Base.P\"),\n // (4,27): warning CS0169: The field 'Base.P.X' is never used\n // private class P { int X; }\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"X\").WithArguments(\"Base.P.X\"));\n }\n\n [WorkItem(537683, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537683\")]\n [Fact]\n public void CS0122ERR_BadAccess02()\n {\n var text = @\"public class Outer\n{\n private class base1 { }\n}\n\npublic class MyClass : Outer.base1\n{\n}\n\";\n var comp = CreateCompilation(text);\n var type1 = comp.SourceModule.GlobalNamespace.GetMembers(\"MyClass\").Single() as NamedTypeSymbol;\n var b = type1.BaseType();\n var errs = comp.GetDiagnostics();\n Assert.Equal(1, errs.Count());\n Assert.Equal(122, errs.First().Code);\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [Fact]\n public void CS0122ERR_BadAccess03()\n {\n var text = @\"\nclass C1\n{\n private C1() { }\n}\nclass C2\n{\n protected C2() { }\n private C2(short x) {}\n}\n\nclass C3 : C2\n{\n C3() : base(3) {} // CS0122\n}\n\nclass Test\n{\n public static int Main()\n {\n C1 c1 = new C1(); // CS0122\n C2 c2 = new C2(); // CS0122\n return 1;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,12): error CS0122: 'C2.C2(short)' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"base\").WithArguments(\"C2.C2(short)\"),\n // (21,21): error CS0122: 'C1.C1()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"C1\").WithArguments(\"C1.C1()\"),\n // (22,21): error CS0122: 'C2.C2()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"C2\").WithArguments(\"C2.C2()\"));\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [WorkItem(540336, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540336\")]\n [Fact]\n public void CS0122ERR_BadAccess04()\n {\n var text = @\"\nclass A\n{\n protected class ProtectedClass { }\n\n public class B : I { }\n}\ninterface I { }\n\nclass Error\n{\n static void Goo(I i) { }\n\n static void Main()\n {\n Goo(new A.B());\n }\n}\n\";\n var tree = Parse(text);\n var compilation = CreateCompilation(tree);\n var model = compilation.GetSemanticModel(tree);\n\n var compilationUnit = tree.GetCompilationUnitRoot();\n var classError = (TypeDeclarationSyntax)compilationUnit.Members[2];\n var mainMethod = (MethodDeclarationSyntax)classError.Members[1];\n var callStmt = (ExpressionStatementSyntax)mainMethod.Body.Statements[0];\n var callExpr = callStmt.Expression;\n\n var callPosition = callExpr.SpanStart;\n\n var boundCall = model.GetSpeculativeSymbolInfo(callPosition, callExpr, SpeculativeBindingOption.BindAsExpression);\n\n Assert.Null(boundCall.Symbol);\n Assert.Equal(1, boundCall.CandidateSymbols.Length);\n Assert.Equal(CandidateReason.OverloadResolutionFailure, boundCall.CandidateReason);\n\n var constructedMethodSymbol = (IMethodSymbol)(boundCall.CandidateSymbols[0]);\n Assert.Equal(\"void Error.Goo(I i)\", constructedMethodSymbol.ToTestDisplayString());\n\n var typeArgSymbol = constructedMethodSymbol.TypeArguments.Single();\n Assert.Equal(\"A.ProtectedClass\", typeArgSymbol.ToTestDisplayString());\n Assert.False(model.IsAccessible(callPosition, typeArgSymbol), \"Protected inner class is inaccessible\");\n\n var paramTypeSymbol = constructedMethodSymbol.Parameters.Single().Type;\n Assert.Equal(\"I\", paramTypeSymbol.ToTestDisplayString());\n Assert.False(model.IsAccessible(callPosition, typeArgSymbol), \"Type should be inaccessible since type argument is inaccessible\");\n\n // The original test attempted to verify that \"Error.Goo\" is an \n // inaccessible method when inside Error.Main. The C# specification nowhere gives \n // a special rule for constructed generic methods; the accessibility domain of\n // a method depends only on its declared accessibility and the declared accessibility\n // of its containing type. \n //\n // We should decide whether the answer to \"is this method accessible in Main?\" is \n // yes or no, and if no, change the implementation of IsAccessible accordingly.\n //\n // Assert.False(model.IsAccessible(callPosition, constructedMethodSymbol), \"Method should be inaccessible since parameter type is inaccessible\");\n\n compilation.VerifyDiagnostics(\n // (16,9): error CS0122: 'Error.Goo(I)' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"Goo\").WithArguments(\"Error.Goo(I)\"));\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [Fact]\n public void CS0122ERR_BadAccess05()\n {\n var text = @\"\nclass Base\n{\n private Base() { }\n}\n\nclass Derived : Base\n{\n private Derived() : this(1) { } //fine: can see own private members\n private Derived(int x) : base() { } //CS0122: cannot see base private members\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,30): error CS0122: 'Base.Base()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"base\").WithArguments(\"Base.Base()\"));\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [Fact]\n public void CS0122ERR_BadAccess06()\n {\n var text = @\"\nclass Base\n{\n private Base() { } //private, but a match\n public Base(int x) { } //public, but not a match\n}\n\nclass Derived : Base\n{\n private Derived() { } //implicit constructor initializer\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,13): error CS0122: 'Base.Base()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"Derived\").WithArguments(\"Base.Base()\"));\n }\n\n [Fact]\n public void CS0123ERR_MethDelegateMismatch()\n {\n var text = @\"\ndelegate void D();\ndelegate void D2(int i);\n\npublic class C\n{\n public static void f(int i) { }\n\n public static void Main()\n {\n D d = new D(f); // CS0123\n D2 d2 = new D2(f); // OK\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethDelegateMismatch, Line = 11, Column = 15 } });\n }\n\n [WorkItem(539909, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909\")]\n [Fact]\n public void CS0123ERR_MethDelegateMismatch_01()\n {\n var text = @\"\ndelegate void boo(short x);\nclass C\n{\n static void far(T x) { }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += far;// Invalid\n goo += far;// OK\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0123: No overload for 'C.far(int)' matches delegate 'boo'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"far\").WithArguments(\"C.far(int)\", \"boo\"));\n }\n\n [WorkItem(539909, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909\")]\n [WorkItem(540053, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540053\")]\n [Fact]\n public void CS0123ERR_MethDelegateMismatch_02()\n {\n var text = @\"\ndelegate void boo(short x);\nclass C\n{\n public static void far(T x) { }\n public static void par(U x) { System.Console.WriteLine(\"\"par\"\"); }\n public static boo goo = null;\n\n}\nclass D\n{\n static void Main(string[] args)\n {\n C p = new C();\n C.goo += C.far;\n C.goo += C.par;\n C.goo(byte.MaxValue);\n C.goo(long.MaxValue);\n C.goo(long.MaxValue);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,24): error CS0123: No overload for 'C.far(long)' matches delegate 'boo'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"C.far\").WithArguments(\"C.far(long)\", \"boo\").WithLocation(15, 24),\n // (16,32): error CS0123: No overload for 'par' matches delegate 'boo'\n // C.goo += C.par;\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"par\").WithArguments(\"par\", \"boo\").WithLocation(16, 32),\n // (18,21): error CS1503: Argument 1: cannot convert from 'long' to 'short'\n Diagnostic(ErrorCode.ERR_BadArgType, \"long.MaxValue\").WithArguments(\"1\", \"long\", \"short\").WithLocation(18, 21),\n // (19,22): error CS1503: Argument 1: cannot convert from 'long' to 'short'\n Diagnostic(ErrorCode.ERR_BadArgType, \"long.MaxValue\").WithArguments(\"1\", \"long\", \"short\").WithLocation(19, 22)\n );\n }\n\n [Fact]\n public void CS0123ERR_MethDelegateMismatch_DelegateVariance()\n {\n var text = @\"\ndelegate TOut D(TIn p);\n\nclass A { }\nclass B : A { }\nclass C : B { }\n\nclass Test\n{\n static void Main()\n {\n D d;\n d = F1; //CS0407\n d = F2; //CS0407\n d = F3; //CS0123\n d = F4;\n d = F5;\n d = F6; //CS0123\n d = F7;\n d = F8;\n d = F9; //CS0123\n }\n\n static A F1(A p) { return null; }\n static A F2(B p) { return null; }\n static A F3(C p) { return null; }\n\n static B F4(A p) { return null; }\n static B F5(B p) { return null; }\n static B F6(C p) { return null; }\n\n static C F7(A p) { return null; }\n static C F8(B p) { return null; }\n static C F9(C p) { return null; }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (13,13): error CS0407: 'A Test.F1(A)' has the wrong return type\n Diagnostic(ErrorCode.ERR_BadRetType, \"F1\").WithArguments(\"Test.F1(A)\", \"A\"),\n // (14,13): error CS0407: 'A Test.F2(B)' has the wrong return type\n Diagnostic(ErrorCode.ERR_BadRetType, \"F2\").WithArguments(\"Test.F2(B)\", \"A\"),\n // (15,13): error CS0123: No overload for 'F3' matches delegate 'D'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"F3\").WithArguments(\"F3\", \"D\"),\n // (18,13): error CS0123: No overload for 'F6' matches delegate 'D'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"F6\").WithArguments(\"F6\", \"D\"),\n // (21,13): error CS0123: No overload for 'F9' matches delegate 'D'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"F9\").WithArguments(\"F9\", \"D\"));\n }\n\n [Fact]\n public void CS0126ERR_RetObjectRequired()\n {\n var source =\n@\"namespace N\n{\n class C\n {\n object F() { return; }\n X G() { return; }\n C P { get { return; } }\n Y Q { get { return; } }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)\n // X G() { return; }\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"X\").WithArguments(\"X\").WithLocation(6, 9),\n // (8,9): error CS0246: The type or namespace name 'Y' could not be found (are you missing a using directive or an assembly reference?)\n // Y Q { get { return; } }\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"Y\").WithArguments(\"Y\").WithLocation(8, 9),\n // (5,22): error CS0126: An object of a type convertible to 'object' is required\n // object F() { return; }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"object\").WithLocation(5, 22),\n // (6,17): error CS0126: An object of a type convertible to 'X' is required\n // X G() { return; }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"X\").WithLocation(6, 17),\n // (7,21): error CS0126: An object of a type convertible to 'C' is required\n // C P { get { return; } }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"N.C\").WithLocation(7, 21),\n // (8,21): error CS0126: An object of a type convertible to 'Y' is required\n // Y Q { get { return; } }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"Y\").WithLocation(8, 21));\n }\n\n [WorkItem(540115, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540115\")]\n [Fact]\n public void CS0126ERR_RetObjectRequired_02()\n {\n var source =\n@\"namespace Test\n{\n public delegate object D();\n\n public class TestClass\n {\n public static int Test(D src)\n {\n src();\n return 0;\n }\n }\n\n public class MainClass\n {\n public static int Main()\n {\n return TestClass.Test(delegate() { return; });\n// The native compiler produces two errors for this code:\n//\n// CS0126: An object of a type convertible to 'object' is required\n//\n// CS1662: Cannot convert anonymous method to delegate type \n// 'Test.D' because some of the return types in the block are not implicitly \n// convertible to the delegate return type\n//\n// This is not great; the first error is right, but does not tell us anything about\n// the fact that overload resolution has failed on the first argument. The second\n// error is actually incorrect; it is not that 'some of the return types are incorrect',\n// it is that some of the returns do not return anything in the first place! There's\n// no 'type' to get wrong. \n//\n// I would like Roslyn to give two errors:\n//\n// CS1503: Argument 1: cannot convert from 'anonymous method' to 'Test.D'\n// CS0126: An object of a type convertible to 'object' is required\n//\n// Neal Gafter says: I'd like one error instead of two. There is an error inside the\n// body of the lambda. It is enough to report that specific error. This is consistent\n// with our design guideline to suppress errors higher in the tree when it is caused\n// by an error lower in the tree.\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (18,48): error CS0126: An object of a type convertible to 'object' is required\n // return TestClass.Test(delegate() { return; });\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"object\").WithLocation(18, 48));\n }\n\n [Fact]\n public void CS0127ERR_RetNoObjectRequired()\n {\n var source =\n@\"namespace MyNamespace\n{\n public class MyClass\n {\n public void F() { return 0; } // CS0127\n public int P\n {\n get { return 0; }\n set { return 0; } // CS0127, set has an implicit void return type\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,27): error CS0127: Since 'MyClass.F()' returns void, a return keyword must not be followed by an object expression\n // public void F() { return 0; } // CS0127\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"MyNamespace.MyClass.F()\").WithLocation(5, 27),\n // (9,19): error CS0127: Since 'MyClass.P.set' returns void, a return keyword must not be followed by an object expression\n // set { return 0; } // CS0127, set has an implicit void return type\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"MyNamespace.MyClass.P.set\").WithLocation(9, 19));\n }\n\n [Fact]\n public void CS0127ERR_RetNoObjectRequired_StaticConstructor()\n {\n string text = @\"\nclass C\n{\n static C()\n {\n return 1;\n }\n}\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0127: Since 'C.C()' returns void, a return keyword must not be followed by an object expression\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"C.C()\"));\n }\n\n [Fact]\n public void CS0128ERR_LocalDuplicate()\n {\n var text = @\"\nnamespace MyNamespace\n{\n public class MyClass\n {\n public static void Main()\n {\n char i = 'a';\n int i = 2; // CS0128\n if (i == 2) {}\n }\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (9,14): error CS0128: A local variable or function named 'i' is already defined in this scope\n // int i = 2; // CS0128\n Diagnostic(ErrorCode.ERR_LocalDuplicate, \"i\").WithArguments(\"i\").WithLocation(9, 14),\n // (9,14): warning CS0219: The variable 'i' is assigned but its value is never used\n // int i = 2; // CS0128\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"i\").WithArguments(\"i\").WithLocation(9, 14)\n );\n }\n\n [Fact]\n public void CS0131ERR_AssgLvalueExpected01()\n {\n CreateCompilation(\n@\"class C\n{\n int i = 0;\n int P { get; set; }\n int this[int x] { get { return x; } set { } }\n void M()\n {\n ++P = 1; // CS0131\n ++i = 1; // CS0131\n ++this[0] = 1; //CS0131\n }\n}\n\")\n .VerifyDiagnostics(\n // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"++P\"),\n // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"++i\"),\n // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"++this[0]\"));\n }\n\n [Fact]\n public void CS0131ERR_AssgLvalueExpected02()\n {\n var source =\n@\"class C\n{\n const object NoObject = null;\n static void M()\n {\n const int i = 0;\n i += 1;\n 3 *= 1;\n (i + 1) -= 1;\n \"\"string\"\" = null;\n null = new object();\n NoObject = \"\"string\"\";\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // i += 1;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"i\").WithLocation(7, 9),\n // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // 3 *= 1;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"3\").WithLocation(8, 9),\n // (9,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // (i + 1) -= 1;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"i + 1\").WithLocation(9, 10),\n // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // \"string\" = null;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, @\"\"\"string\"\"\").WithLocation(10, 9),\n // (11,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // null = new object();\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"null\").WithLocation(11, 9),\n // (12,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // NoObject = \"string\";\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"NoObject\").WithLocation(12, 9));\n }\n\n /// \n /// Breaking change from Dev10. CS0131 is now reported for all value\n /// types, not just struct types. Specifically, CS0131 is now reported\n /// for type parameters constrained to \"struct\". (See also CS1612.)\n /// \n [WorkItem(528763, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528763\")]\n [Fact]\n public void CS0131ERR_AssgLvalueExpected03()\n {\n var source =\n@\"struct S\n{\n public object P { get; set; }\n public object this[object index] { get { return null; } set { } }\n}\ninterface I\n{\n object P { get; set; }\n object this[object index] { get; set; }\n}\nclass C\n{\n static void M()\n where T : struct, I\n {\n default(S).P = null;\n default(T).P = null; // Dev10: no error\n default(S)[0] = null;\n default(T)[0] = null; // Dev10: no error\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(S).P\").WithLocation(16, 9),\n // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T).P\").WithLocation(17, 9),\n // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(S)[0]\").WithLocation(18, 9),\n // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T)[0]\").WithLocation(19, 9));\n }\n\n [WorkItem(538077, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538077\")]\n [Fact]\n public void CS0132ERR_StaticConstParam()\n {\n var text = @\"\nclass A\n{\n static A(int z)\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Parameters = new string[] { \"A.A(int)\" } } });\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression01()\n {\n var source =\n@\"class MyClass\n{\n public const int a = b; //no error since b is declared const\n public const int b = c; //CS0133, c is not constant\n public static int c = 1; //change static to const to correct program\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,25): error CS0133: The expression being assigned to 'MyClass.b' must be constant\n // public const int b = c; //CS0133, c is not constant\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"c\").WithArguments(\"MyClass.b\").WithLocation(4, 25));\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression02()\n {\n var source =\n@\"enum E\n{\n X,\n Y = C.F(),\n Z = C.G() + 1,\n}\nclass C\n{\n public static E F()\n {\n return E.X;\n }\n public static int G()\n {\n return 0;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,9): error CS0266: Cannot implicitly convert type 'E' to 'int'. An explicit conversion exists (are you missing a cast?)\n // Y = C.F(),\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"C.F()\").WithArguments(\"E\", \"int\").WithLocation(4, 9),\n // (4,9): error CS0133: The expression being assigned to 'E.Y' must be constant\n // Y = C.F(),\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"C.F()\").WithArguments(\"E.Y\").WithLocation(4, 9),\n // (5,9): error CS0133: The expression being assigned to 'E.Z' must be constant\n // Z = C.G() + 1,\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"C.G() + 1\").WithArguments(\"E.Z\").WithLocation(5, 9));\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression03()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n int y = 1;\n const int x = 2 * y;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,23): error CS0133: The expression being assigned to 'x' must be constant\n // const int x = 2 * y;\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"2 * y\").WithArguments(\"x\").WithLocation(6, 23));\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression04()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n const int x = x + x;\n }\n}\";\n CreateCompilationWithMscorlib45(source).VerifyDiagnostics(\n // (5,27): error CS0110: The evaluation of the constant value for 'x' involves a circular definition\n // const int x = x + x;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"x\").WithArguments(\"x\").WithLocation(5, 27),\n // (5,23): error CS0110: The evaluation of the constant value for 'x' involves a circular definition\n // const int x = x + x;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"x\").WithArguments(\"x\").WithLocation(5, 23));\n }\n\n [Fact]\n public void CS0135ERR_NameIllegallyOverrides()\n {\n // See NameCollisionTests.cs for commentary on this error.\n\n var text = @\"\npublic class MyClass2\n{\n public static int i = 0;\n\n public static void Main()\n {\n {\n int i = 4; // CS0135: Roslyn reports this error here\n i++;\n }\n i = 0; // Native compiler reports the error here\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);\n }\n\n [Fact]\n public void CS0135ERR_NameIllegallyOverrides02()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\n\nclass Test\n{\n static int x;\n static void Main()\n {\n int z = x;\n var y = from x in Enumerable.Range(1, 100) // CS1931\n select x;\n }\n}\").VerifyDiagnostics(\n // (6,16): warning CS0649: Field 'Test.x' is never assigned to, and will always have its default value 0\n // static int x;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"x\").WithArguments(\"Test.x\", \"0\").WithLocation(6, 16)\n);\n }\n\n [Fact]\n public void CS0136ERR_LocalIllegallyOverrides01()\n {\n // See comments in NameCollisionTests for thoughts on this error.\n\n string text =\n@\"class C\n{\n static void M(object x)\n {\n string x = null; // CS0136\n string y = null;\n if (x != null)\n {\n int y = 0; // CS0136\n M(y);\n }\n M(x);\n M(y);\n }\n object P\n {\n get\n {\n int value = 0; // no error\n return value;\n }\n set\n {\n int value = 0; // CS0136\n M(value);\n }\n }\n static void N(int q)\n {\n System.Func f = q=>q; // 0136\n }\n}\";\n var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7_3);\n comp.VerifyDiagnostics(\n // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // string x = null; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"x\").WithArguments(\"x\").WithLocation(5, 16),\n // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int y = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"y\").WithArguments(\"y\").WithLocation(9, 17),\n // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int value = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"value\").WithArguments(\"value\").WithLocation(24, 17),\n // (30,35): error CS0136: A local or parameter named 'q' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // System.Func f = q=>q; // 0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"q\").WithArguments(\"q\").WithLocation(30, 35));\n\n comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // string x = null; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"x\").WithArguments(\"x\").WithLocation(5, 16),\n // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int y = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"y\").WithArguments(\"y\").WithLocation(9, 17),\n // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int value = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"value\").WithArguments(\"value\").WithLocation(24, 17));\n }\n\n [Fact]\n public void CS0136ERR_LocalIllegallyOverrides02()\n {\n // See comments in NameCollisionTests for commentary on this error.\n\n CreateCompilation(\n@\"class C\n{\n static void M(object o)\n {\n try\n {\n }\n catch (System.IO.IOException e) \n {\n M(e);\n }\n catch (System.Exception e) // Legal; the two 'e' variables are in non-overlapping declaration spaces\n {\n M(e);\n }\n try\n {\n }\n catch (System.Exception o) // CS0136: Illegal; the two 'o' variables are in overlapping declaration spaces.\n {\n M(o);\n }\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"o\").WithArguments(\"o\").WithLocation(19, 33));\n }\n\n [Fact]\n public void CS0136ERR_LocalIllegallyOverrides03()\n {\n // See comments in NameCollisionTests for commentary on this error.\n\n CreateCompilation(\n@\"class C\n{\n int field = 0;\n int property { get; set; }\n\n static public void Main()\n {\n int[] ints = new int[] { 1, 2, 3 };\n string[] strings = new string[] { \"\"1\"\", \"\"2\"\", \"\"3\"\" };\n int conflict = 1;\n System.Console.WriteLine(conflict);\n foreach (int field in ints) { } // Legal: local hides field but name is used consistently\n foreach (string property in strings) { } // Legal: local hides property but name is used consistently\n foreach (string conflict in strings) { } // 0136: local hides another local in an enclosing local declaration space.\n }\n}\n\")\n .VerifyDiagnostics(\n // (14,25): error CS0136: A local or parameter named 'conflict' cannot be declared in this \n // scope because that name is used in an enclosing local scope to define a local or parameter\n // foreach (string conflict in strings) { } // 0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"conflict\").WithArguments(\"conflict\").WithLocation(14, 25),\n // (3,9): warning CS0414: The field 'C.field' is assigned but its value is never used\n // int field = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"field\").WithArguments(\"C.field\"));\n }\n\n [WorkItem(538045, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538045\")]\n [Fact]\n public void CS0139ERR_NoBreakOrCont()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public static void Main(bool b)\n {\n if (b)\n continue; // CS0139\n else\n break; // CS0139\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 9, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 11, Column = 17 }});\n }\n\n [WorkItem(542400, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542400\")]\n [Fact]\n public void CS0140ERR_DuplicateLabel()\n {\n var text = @\"\nnamespace MyNamespace\n{\n public class MyClass\n {\n public static void Main()\n {\n label1: int i = M();\n label1: int j = M(); // CS0140, comment this line to resolve\n goto label1;\n }\n static int M() { return 0; }\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (9,10): error CS0140: The label 'label1' is a duplicate\n // label1: int j = M(); // CS0140, comment this line to resolve\n Diagnostic(ErrorCode.ERR_DuplicateLabel, \"label1\").WithArguments(\"label1\").WithLocation(9, 10)\n );\n }\n\n [WorkItem(542420, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420\")]\n [Fact]\n public void ErrorMeansSuccess_Attribute()\n {\n var text = @\"\nusing A;\nusing B;\nusing System;\n\nnamespace A\n{\n class var { }\n class XAttribute : Attribute { }\n}\nnamespace B\n{\n class var { }\n class XAttribute : Attribute { }\n class X : Attribute { }\n}\nclass Xyzzy\n{\n [X] // 17.2 If an attribute class is found both with and without this suffix, an ambiguity is present and a compile-time error occurs.\n public static void Main(string[] args)\n {\n }\n static int M() { return 0; }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics();\n }\n\n [WorkItem(542420, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420\")]\n [Fact]\n public void ErrorMeansSuccess_var()\n {\n var text = @\"\nusing A;\nusing B;\n\nnamespace A\n{\n class var { }\n}\nnamespace B\n{\n class var { }\n}\nclass Xyzzy\n{\n public static void Main(string[] args)\n {\n var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ...\n }\n static int M() { return 0; }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (21,9): error CS0104: 'var' is an ambiguous reference between 'A.var' and 'B.var'\n // var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ...\n Diagnostic(ErrorCode.ERR_AmbigContext, \"var\").WithArguments(\"var\", \"A.var\", \"B.var\")\n );\n }\n\n [Fact]\n public void CS0144ERR_NoNewAbstract()\n {\n var text = @\"\ninterface ii\n{\n}\n\nabstract class aa\n{\n}\n\npublic class a\n{\n public static void Main()\n {\n ii xx = new ii(); // CS0144\n ii yy = new ii(Error); // CS0144, CS0103\n aa zz = new aa(); // CS0144\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[]\n {\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 14, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 15, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 16, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 15, Column = 22 }\n });\n }\n\n [WorkItem(539583, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539583\")]\n [Fact]\n public void CS0150ERR_ConstantExpected()\n {\n var test = @\"\nclass C\n{\n static void Main()\n {\n byte x = 1;\n int[] a1 = new int[x];\n int[] a2 = new int[x] { 1 }; //CS0150\n\n const sbyte y = 1;\n const short z = 2;\n int[] b1 = new int[y + z];\n int[] b2 = new int[y + z] { 1, 2, 3 };\n }\n}\n\";\n CreateCompilation(test).VerifyDiagnostics(\n // (8,28): error CS0150: A constant value is expected\n Diagnostic(ErrorCode.ERR_ConstantExpected, \"x\"));\n }\n\n [Fact()]\n public void CS0151ERR_IntegralTypeValueExpected()\n {\n var text = @\"\npublic class iii\n{\n public static implicit operator int (iii aa)\n {\n return 0;\n }\n\n public static implicit operator long (iii aa)\n {\n return 0;\n }\n\n public static void Main()\n {\n iii a = new iii();\n\n switch (a) // CS0151, compiler cannot choose between int and long\n {\n case 1:\n break;\n }\n }\n}\";\n var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6);\n comp.VerifyDiagnostics(\n // (18,15): error CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier.\n // switch (a) // CS0151, compiler cannot choose between int and long\n Diagnostic(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, \"a\").WithLocation(18, 15),\n // (20,15): error CS0029: Cannot implicitly convert type 'int' to 'iii'\n // case 1:\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"1\").WithArguments(\"int\", \"iii\").WithLocation(20, 15)\n );\n }\n\n [Fact]\n public void CS0152ERR_DuplicateCaseLabel()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public static void Main()\n {\n int i = 0;\n\n switch (i)\n {\n case 1:\n i++;\n return;\n\n case 1: // CS0152, two case 1 statements\n i++;\n return;\n }\n }\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (16,13): error CS0152: The switch statement contains multiple cases with the label value '1'\n // case 1: // CS0152, two case 1 statements\n Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, \"case 1:\").WithArguments(\"1\").WithLocation(16, 13)\n );\n }\n\n [Fact]\n public void CS0153ERR_InvalidGotoCase()\n {\n var text = @\"\npublic class a\n{\n public static void Main()\n {\n goto case 5; // CS0153\n }\n}\";\n\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,7): error CS0153: A goto case is only valid inside a switch statement\n // goto case 5; // CS0153\n Diagnostic(ErrorCode.ERR_InvalidGotoCase, \"goto case 5;\").WithLocation(6, 7));\n }\n\n [Fact]\n public void CS0153ERR_InvalidGotoCase_2()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n string Fruit = \"\"Apple\"\";\n switch (Fruit)\n {\n case \"\"Banana\"\":\n break;\n default:\n break;\n }\n goto default;\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (14,9): error CS0153: A goto case is only valid inside a switch statement\n // goto default;\n Diagnostic(ErrorCode.ERR_InvalidGotoCase, \"goto default;\").WithLocation(14, 9));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet01()\n {\n CreateCompilation(\n@\"class C\n{\n static object P { set { } }\n static int Q { set { } }\n static void M(object o)\n {\n C.P = null;\n o = C.P; // CS0154\n M(P); // CS0154\n ++C.Q; // CS0154\n }\n}\n\")\n .VerifyDiagnostics(\n // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"C.P\").WithArguments(\"C.P\"),\n // (9,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\"),\n // (10,11): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"C.Q\").WithArguments(\"C.Q\"));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet02()\n {\n var source =\n@\"class A\n{\n public virtual A P { get; set; }\n public object Q { set { } }\n}\nclass B : A\n{\n public override A P { set { } }\n void M()\n {\n M(Q); // CS0154, no get method\n }\n static void M(B b)\n {\n object o = b.P; // no error\n o = b.Q; // CS0154, no get method\n b.P.Q = null; // no error\n o = b.P.Q; // CS0154, no get method\n }\n static void M(object o) { }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (11,11): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor\n // M(Q); // CS0154, no get method\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"A.Q\").WithLocation(11, 11),\n // (16,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor\n // o = b.Q; // CS0154, no get method\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"b.Q\").WithArguments(\"A.Q\").WithLocation(16, 13),\n // (18,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor\n // o = b.P.Q; // CS0154, no get method\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"b.P.Q\").WithArguments(\"A.Q\").WithLocation(18, 13));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet03()\n {\n var source =\n@\"class C\n{\n int P { set { } }\n void M()\n {\n P += 1;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,9): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n // P += 1;\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet04()\n {\n var source =\n@\"class C\n{\n object p;\n object P { set { p = P; } }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,26): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n // object P { set { p = P; } }\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(4, 26));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet05()\n {\n CreateCompilation(\n@\"class C\n{\n object P { set { } }\n static bool Q { set { } }\n void M()\n {\n object o = P as string;\n o = P ?? Q;\n o = (o != null) ? P : Q;\n o = !Q;\n }\n}\")\n .VerifyDiagnostics(\n // (7,20): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(7, 20),\n // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(8, 13),\n // (8,18): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"C.Q\").WithLocation(8, 18),\n // (9,27): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(9, 27),\n // (9,31): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"C.Q\").WithLocation(9, 31),\n // (10,14): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"C.Q\").WithLocation(10, 14));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet06()\n {\n CreateCompilation(\n@\"class C\n{\n int this[int x] { set { } }\n void M(int b)\n {\n b = this[0];\n b = 1 + this[1];\n M(this[2]);\n this[3]++;\n this[4] += 1;\n }\n}\")\n .VerifyDiagnostics(\n // (6,13): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[0]\").WithArguments(\"C.this[int]\"),\n // (7,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[1]\").WithArguments(\"C.this[int]\"),\n // (8,11): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[2]\").WithArguments(\"C.this[int]\"),\n // (9,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[3]\").WithArguments(\"C.this[int]\"),\n // (10,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[4]\").WithArguments(\"C.this[int]\"));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet07()\n {\n var source1 =\n@\"public class A\n{\n public virtual object P { private get { return null; } set { } }\n}\npublic class B : A\n{\n public override object P { set { } }\n}\";\n var compilation1 = CreateCompilation(source1);\n compilation1.VerifyDiagnostics();\n var compilationVerifier = CompileAndVerify(compilation1);\n var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData);\n var source2 =\n@\"class C\n{\n static void M(B b)\n {\n var o = b.P;\n b.P = o;\n }\n}\";\n var compilation2 = CreateCompilation(source2, references: new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (5,17): error CS0154: The property or indexer 'B.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"b.P\").WithArguments(\"B.P\").WithLocation(5, 17));\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType()\n {\n var text =\n@\"interface IA { }\ninterface IB : IA { }\nstruct S { }\nclass C\n{\n static void M()\n {\n try { }\n catch (object) { }\n catch (System.Exception) { }\n catch (System.DateTime) { }\n catch (System.Int32) { }\n catch (IA) { }\n catch (IB) { }\n catch (S) { }\n catch (S) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"object\").WithLocation(9, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"System.Exception\").WithArguments(\"object\").WithLocation(10, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"System.DateTime\").WithLocation(11, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"System.Int32\").WithLocation(12, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"IA\").WithLocation(13, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"IB\").WithLocation(14, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"S\").WithLocation(15, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"S\").WithLocation(16, 16));\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_Null()\n {\n var text = @\"class C\n{\n static readonly bool False = false;\n const string T = null;\n\n static void M(object o) \n {\n const string s = null;\n if (False) throw null;\n if (False) throw (string)null; //CS0155\n if (False) throw s; //CS0155\n if (False) throw T; //CS0155\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception'\n // if (False) throw (string)null; //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"(string)null\").WithArguments(\"string\", \"System.Exception\").WithLocation(10, 26),\n // (11,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception'\n // if (False) throw s; //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"s\").WithArguments(\"string\", \"System.Exception\").WithLocation(11, 26),\n // (12,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception'\n // if (False) throw T; //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"T\").WithArguments(\"string\", \"System.Exception\").WithLocation(12, 26)\n );\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_FailingAs()\n {\n var text = @\"\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n {\n if (False) throw new C() as D; //CS0155, though always null\n }\n}\n\nclass D : C { }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,26): error CS0029: Cannot implicitly convert type 'D' to 'System.Exception'\n // if (False) throw new C() as D; //CS0155, though always null\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new C() as D\").WithArguments(\"D\", \"System.Exception\").WithLocation(8, 26)\n );\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_TypeParameters()\n {\n var text = @\"using System;\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n where TC : class\n where TS : struct\n where TE : Exception, new()\n {\n if (False) throw default(T); //CS0155\n if (False) throw default(TC); //CS0155\n if (False) throw default(TS); //CS0155\n if (False) throw default(TE);\n if (False) throw new TE();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,26): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception'\n // if (False) throw default(T); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"default(T)\").WithArguments(\"T\", \"System.Exception\").WithLocation(11, 26),\n // (12,26): error CS0029: Cannot implicitly convert type 'TC' to 'System.Exception'\n // if (False) throw default(TC); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"default(TC)\").WithArguments(\"TC\", \"System.Exception\").WithLocation(12, 26),\n // (13,26): error CS0029: Cannot implicitly convert type 'TS' to 'System.Exception'\n // if (False) throw default(TS); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"default(TS)\").WithArguments(\"TS\", \"System.Exception\").WithLocation(13, 26)\n );\n }\n\n [Fact()]\n public void CS0155ERR_BadExceptionType_UserDefinedConversions()\n {\n var text = @\"using System;\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n {\n if (False) throw new Implicit(); //CS0155\n if (False) throw new Explicit(); //CS0155\n if (False) throw (Exception)new Implicit();\n if (False) throw (Exception)new Explicit();\n }\n}\n\nclass Implicit\n{\n public static implicit operator Exception(Implicit i)\n {\n return null;\n }\n}\n\nclass Explicit\n{\n public static explicit operator Exception(Explicit i)\n {\n return null;\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"new Implicit()\"),\n // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"new Explicit()\")\n );\n CreateCompilation(text).VerifyDiagnostics(\n // (9,26): error CS0266: Cannot implicitly convert type 'Explicit' to 'System.Exception'. An explicit conversion exists (are you missing a cast?)\n // if (False) throw new Explicit(); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"new Explicit()\").WithArguments(\"Explicit\", \"System.Exception\").WithLocation(9, 26)\n );\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_Dynamic()\n {\n var text = @\"\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n {\n dynamic d = null;\n if (False) throw d; //CS0155\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (9,26): error CS0155: The type caught or thrown must be derived from System.Exception\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"d\"));\n CreateCompilation(text).VerifyDiagnostics(); // dynamic conversion to Exception\n }\n\n [WorkItem(542995, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542995\")]\n [Fact]\n public void CS0155ERR_BadExceptionType_Struct()\n {\n var text = @\"\npublic class Test\n{\n public static void Main(string[] args)\n {\n }\n private void Method()\n {\n try\n {\n }\n catch (s1 s)\n {\n }\n }\n}\nstruct s1\n{ }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,16): error CS0155: The type caught or thrown must be derived from System.Exception\n // catch (s1 s)\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"s1\"),\n // (12,19): warning CS0168: The variable 's' is declared but never used\n // catch (s1 s)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"s\").WithArguments(\"s\")\n );\n }\n\n [Fact]\n public void CS0156ERR_BadEmptyThrow()\n {\n var text = @\"\nusing System;\n\nnamespace x\n{\n public class b : Exception\n {\n }\n\n public class a\n {\n public static void Main()\n {\n try\n {\n throw; // CS0156\n }\n\n catch(b)\n {\n throw; // this throw is valid\n }\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEmptyThrow, Line = 16, Column = 13 } });\n }\n\n [Fact]\n public void CS0156ERR_BadEmptyThrow_Nesting()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n bool b = System.DateTime.Now.Second > 1; //avoid unreachable code\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n }\n catch\n {\n if (b) throw; //fine\n try\n {\n if (b) throw; //fine\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0724\n\n try\n {\n if (b) throw; //CS0724\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0724\n }\n }\n }\n finally\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (9,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (12,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (20,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (41,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (44,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (52,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"));\n }\n\n [Fact]\n public void CS0156ERR_BadEmptyThrow_Lambdas()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n bool b = System.DateTime.Now.Second > 1; // avoid unreachable code\n System.Action a;\n a = () => { throw; }; //CS0156\n try\n {\n a = () =>\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n };\n }\n catch\n {\n a = () =>\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n };\n }\n finally\n {\n a = () =>\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n };\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,21): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (13,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (16,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (24,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (32,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (35,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (43,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (51,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (54,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (62,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"));\n }\n\n [WorkItem(540817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817\")]\n [Fact]\n public void CS0157ERR_BadFinallyLeave01()\n {\n var text =\n@\"class C\n{\n static int F;\n static void M()\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n Before:\n ;\n try\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n else if (F == 2)\n goto TryBlock;\n else if (F == 3)\n return;\n TryBlock:\n ;\n }\n catch (System.Exception)\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n else if (F == 2)\n goto CatchBlock;\n else if (F == 3)\n return;\n CatchBlock:\n ;\n }\n finally\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n else if (F == 2)\n goto FinallyBlock;\n else if (F == 3)\n return;\n FinallyBlock:\n ;\n }\n After:\n ;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (41,17): error CS0157: Control cannot leave the body of a finally clause\n // goto Before;\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"goto\"),\n // (43,17): error CS0157: Control cannot leave the body of a finally clause\n // goto After;\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"goto\"),\n // (47,17): error CS0157: Control cannot leave the body of a finally clause\n // return;\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"return\"),\n // (3,16): warning CS0649: Field 'C.F' is never assigned to, and will always have its default value 0\n // static int F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"C.F\", \"0\")\n );\n }\n\n [WorkItem(540817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817\")]\n [Fact]\n public void CS0157ERR_BadFinallyLeave02()\n {\n var text =\n@\"using System;\nclass C\n{\n static void F(int i)\n {\n }\n static void M()\n {\n for (int i = 0; i < 10;)\n {\n if (i < 5)\n {\n try { F(i); }\n catch (Exception) { continue; }\n finally { break; }\n }\n else\n {\n try { F(i); }\n catch (Exception) { break; }\n finally { continue; }\n }\n }\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"break\").WithLocation(15, 27),\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"continue\").WithLocation(21, 27));\n }\n\n [WorkItem(540817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817\")]\n [Fact]\n public void CS0157ERR_BadFinallyLeave03()\n {\n var text = @\"\nclass C\n{\n static void Main(string[] args)\n {\n int i = 0;\n try { i = 1; }\n catch { i = 2; }\n finally { i = 3; goto lab1; }// invalid\n lab1:\n return;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (9,26): error CS0157: Control cannot leave the body of a finally clause\n // finally { i = 3; goto lab1; }// invalid\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"goto\"),\n // (6,13): warning CS0219: The variable 'i' is assigned but its value is never used\n // int i = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"i\").WithArguments(\"i\")\n );\n }\n\n [WorkItem(539890, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890\")]\n [Fact]\n public void CS0158ERR_LabelShadow()\n {\n var text = @\"\nnamespace MyNamespace\n{\n public class MyClass\n {\n public static void Main()\n {\n goto lab1;\n lab1:\n {\n lab1:\n goto lab1; // CS0158\n }\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelShadow, Line = 11, Column = 13 } });\n }\n\n [WorkItem(539890, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890\")]\n [Fact]\n public void CS0158ERR_LabelShadow_02()\n {\n var text = @\"\ndelegate int del(int i);\nclass C\n{\n static void Main(string[] args)\n {\n del p = x =>\n {\n goto label1;\n label1: // invalid\n return x * x;\n };\n label1:\n return;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (10,9): error CS0158: The label 'label1' shadows another label by the same name in a contained scope\n // label1: // invalid\n Diagnostic(ErrorCode.ERR_LabelShadow, \"label1\").WithArguments(\"label1\"),\n // (13,5): warning CS0164: This label has not been referenced\n // label1:\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label1\")\n );\n }\n\n [WorkItem(539875, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539875\")]\n [Fact]\n public void CS0159ERR_LabelNotFound()\n {\n var text = @\"\npublic class Cls\n{\n public static void Main()\n {\n goto Label2;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelNotFound, Line = 6, Column = 14 }\n });\n }\n\n [WorkItem(528799, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528799\")]\n [Fact()]\n public void CS0159ERR_LabelNotFound_2()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int s = 23;\n switch (s)\n {\n case 21:\n break;\n case 23:\n goto default;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,17): error CS0159: No such label 'default:' within the scope of the goto statement\n // goto default;\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"goto default;\").WithArguments(\"default:\"),\n // (11,13): error CS8070: Control cannot fall out of switch from final case label ('case 23:')\n // case 23:\n Diagnostic(ErrorCode.ERR_SwitchFallOut, \"case 23:\").WithArguments(\"case 23:\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_3()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n goto Label;\n }\n public static void Goo()\n {\n Label:\n ;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label\").WithArguments(\"Label\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_4()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n for (int i = 0; i < 10; i++)\n {\n Label:\n i++;\n }\n goto Label;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label\").WithArguments(\"Label\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_5()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n if (true)\n {\n Label1:\n goto Label2;\n }\n else\n {\n Label2:\n goto Label1;\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label2\").WithArguments(\"Label2\"),\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label1\").WithArguments(\"Label1\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"Label2\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label1\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label2\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_6()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n { goto L; }\n { L: return; }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"L\").WithArguments(\"L\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"L\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_7()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int i = 3;\n if (true)\n {\n label1:\n goto label3;\n if (!false)\n {\n label2:\n goto label5;\n if (i > 2)\n {\n label3:\n goto label2;\n if (i == 3)\n {\n label4:\n if (i < 5)\n {\n label5:\n if (i == 4)\n {\n }\n else\n {\n System.Console.WriteLine(\"\"a\"\");\n }\n }\n }\n }\n }\n }\n }\n}\n\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"label3\").WithArguments(\"label3\"),\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"label5\").WithArguments(\"label5\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"if\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"label4\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"label5\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label1\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label3\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label4\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label5\"));\n }\n\n [WorkItem(540818, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540818\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_8()\n {\n var text = @\"\ndelegate int del(int i);\nclass C\n{\n static void Main(string[] args)\n {\n del q = x =>\n {\n goto label2; // invalid\n return x * x;\n };\n label2:\n return;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (10,17): warning CS0162: Unreachable code detected\n // return x * x;\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"),\n // (9,17): error CS0159: No such label 'label2' within the scope of the goto statement\n // goto label2; // invalid\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"goto\").WithArguments(\"label2\"),\n // (12,5): warning CS0164: This label has not been referenced\n // label2:\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label2\")\n );\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_9()\n {\n var text = @\"\npublic class Test\n{\n static public void Main(string[] args)\n {\n string[] S = new string[] { \"\"ABC\"\", \"\"XYZ\"\" };\n foreach (string x in S)\n {\n goto innerLoop;\n foreach (char y in x)\n {\n innerLoop:\n return;\n }\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"innerLoop\").WithArguments(\"innerLoop\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"innerLoop\"));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch()\n {\n var text =\n@\"using System;\nusing System.IO;\nclass A : Exception { }\nclass B : A { }\nclass C : IOException { }\ninterface I { }\nclass D : Exception, I { }\nclass E : IOException, I { }\nclass F : Exception { }\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) { }\n catch (D) { }\n catch (E) { }\n catch (IOException) { }\n catch (C) { }\n catch (F) { }\n catch (F) { }\n catch (Exception) { }\n catch (B) { }\n catch (StackOverflowException) { }\n catch (F) { }\n catch (F) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"C\").WithArguments(\"System.IO.IOException\").WithLocation(19, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"B\").WithArguments(\"A\").WithLocation(23, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"StackOverflowException\").WithArguments(\"System.Exception\").WithLocation(24, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"F\").WithArguments(\"F\").WithLocation(25, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"F\").WithArguments(\"System.Exception\").WithLocation(26, 16));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_Filter1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n int a = 1;\n try { }\n catch when (a == 1) { }\n catch (Exception e) when (e.Message == null) { }\n catch (A) { }\n catch (B e) when (e.Message == null) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('A')\n // catch (B e) when (e.Message == null) { }\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"B\").WithArguments(\"A\").WithLocation(15, 16));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse_NonBoolean()\n {\n // Non-boolean constant filters are not considered for WRN_FilterIsConstant warnings. \n\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (1) { }\n catch (B) when (0) { }\n catch (B) when (\"\"false\"\") { }\n catch (B) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): error CS0029: Cannot implicitly convert type 'int' to 'bool'\n // catch (A) when (1) { }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"1\").WithArguments(\"int\", \"bool\").WithLocation(11, 25),\n // (12,25): error CS0029: Cannot implicitly convert type 'int' to 'bool'\n // catch (B) when (0) { }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"0\").WithArguments(\"int\", \"bool\").WithLocation(12, 25),\n // (13,25): error CS0029: Cannot implicitly convert type 'string' to 'bool'\n // catch (B) when (\"false\") { }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, @\"\"\"false\"\"\").WithArguments(\"string\", \"bool\").WithLocation(13, 25),\n // (14,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (B) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(14, 25));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) { }\n catch (B) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(11, 25),\n // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (B) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(12, 25));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse2()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when ((1+1)!=2) { }\n catch (B) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"(1+1)!=2\").WithLocation(11, 25),\n // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (B) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(12, 25));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse3()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) { }\n finally { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(10, 25));\n }\n\n [Fact]\n public void CS8360WRN_FilterIsConstantRedundantTryCatch1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, \"false\").WithLocation(10, 25));\n }\n\n [Fact]\n public void CS8360WRN_FilterIsConstantRedundantTryCatch2()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when ((1+1)!=2) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, \"(1+1)!=2\").WithLocation(10, 25));\n }\n\n [Fact]\n public void CS7095WRN_FilterIsConstantTrue1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (true) { }\n catch (B) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch (A) when (true) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"true\").WithLocation(11, 25));\n }\n\n [Fact]\n public void CS7095WRN_FilterIsConstantTrue2()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch when (true) { }\n catch (A) { }\n catch when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch when (true) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"true\").WithLocation(10, 21),\n // (12,19): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(12, 21));\n }\n\n [Fact]\n public void CS7095WRN_FilterIsConstantTrue3()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch when ((1+1)==2) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch when (true) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"(1+1)==2\").WithLocation(10, 21));\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode_Filter_ConstantCondition()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) \n {\n Console.WriteLine(1); \n }\n catch (B) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) \n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(11, 25),\n // (13,13): warning CS0162: Unreachable code detected\n // Console.WriteLine(1); \n Diagnostic(ErrorCode.WRN_UnreachableCode, \"Console\").WithLocation(13, 13)\n );\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode_Filter_ConstantCondition2()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n static void M()\n {\n int x;\n try { }\n catch (Exception) when (false) \n {\n Console.WriteLine(x);\n }\n }\n}\n\";\n // Unlike an unreachable code in if statement block we don't allow using\n // a variable that's not definitely assigned. The reason why we allow it in an if statement\n // is to make conditional compilation easier. Such scenario doesn't apply to filters.\n\n CreateCompilation(text).VerifyDiagnostics(\n // (10,33): warning CS7105: Filter expression is a constant 'false', consider removing the try-catch block\n // catch (Exception) when (false) \n Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, \"false\").WithLocation(10, 33),\n // (12,13): warning CS0162: Unreachable code detected\n // Console.WriteLine(x);\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"Console\").WithLocation(12, 13)\n );\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode_Filter_ConstantCondition3()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n static void M()\n {\n int x;\n try { }\n catch (Exception) when (true) \n {\n Console.WriteLine(x);\n }\n }\n}\n\";\n // Unlike an unreachable code in if statement block we don't allow using\n // a variable that's not definitely assigned. The reason why we allow it in an if statement\n // is to make conditional compilation easier. Such scenario doesn't apply to filters.\n\n CreateCompilation(text).VerifyDiagnostics(\n // (10,33): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch (Exception) when (true) \n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"true\").WithLocation(10, 33),\n // (12,31): error CS0165: Use of unassigned local variable 'x'\n // Console.WriteLine(x);\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(12, 31)\n );\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_Dynamic()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic class A\n{\n public void M1()\n {\n try\n {\n Goo();\n }\n catch (EG)\n {\n }\n catch (EG)\n {\n }\n }\n\n void Goo() { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"EG\").WithArguments(\"EG\"));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_TypeParameter()\n {\n string source = @\"\nusing System;\n\npublic class EA : Exception { }\npublic class EB : EA { }\n\npublic class A where T : EB\n{\n public void M1()\n {\n try\n {\n Goo();\n }\n catch (EA)\n {\n }\n catch (T)\n {\n }\n }\n\n void Goo() { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (18,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EA')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"T\").WithArguments(\"EA\"));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic1()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic abstract class A\n{\n public abstract void M() where U : T;\n}\n\npublic class B : A> where V : EG\n{\n public override void M()\n {\n try\n {\n Goo();\n }\n catch (EG)\n {\n }\n catch (V)\n {\n }\n catch (U)\n {\n }\n }\n\n void Goo() { } \n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"V\").WithArguments(\"EG\"),\n // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"U\").WithArguments(\"EG\"));\n }\n\n [Fact]\n public void TypeParameter_DynamicConversions()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic abstract class A\n{\n public abstract void M() where U : T;\n}\n\npublic class B : A> where V : EG\n{\n public override void M()\n {\n V v = default(V);\n U u = default(U);\n\n // implicit\n EG egd = v;\n // implicit\n egd = u;\n\n //explicit\n v = (V)egd;\n //explicit\n u = (U)egd;\n\n //implicit array\n V[] va = null; \n EG[] egda = va;\n\n // explicit array\n va = (V[])egda; \n }\n\n void Goo() { } \n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();\n }\n\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic2()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic abstract class A\n{\n public abstract void M() where U : T;\n}\n\npublic class B : A> where V : EG\n{\n public override void M()\n {\n try\n {\n Goo();\n }\n catch (EG)\n {\n }\n catch (V)\n {\n }\n catch (U)\n {\n }\n }\n\n void Goo() { } \n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"V\").WithArguments(\"EG\"),\n // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"U\").WithArguments(\"EG\"));\n }\n\n [Fact]\n public void CS0161ERR_ReturnExpected()\n {\n var text = @\"\npublic class Test\n{\n public static int Main() // CS0161\n {\n int i = 10;\n if (i < 10)\n {\n return i;\n }\n else\n {\n // uncomment the following line to resolve\n // return 1;\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnExpected, Line = 4, Column = 22 } });\n }\n\n [Fact]\n public void CS0163ERR_SwitchFallThrough()\n {\n var text = @\"\npublic class MyClass\n{\n public static void Main()\n {\n int i = 0;\n\n switch (i) // CS0163\n {\n case 1:\n i++;\n // uncomment one of the following lines to resolve\n // return;\n // break;\n // goto case 3;\n\n case 2:\n i++;\n return;\n\n case 3:\n i = 0;\n return;\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SwitchFallThrough, Line = 10, Column = 10 } });\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation01()\n {\n var text = @\"\nclass MyClass\n{\n public int i;\n}\n\nclass MyClass2\n{\n public static void Main(string [] args)\n {\n int i, j;\n if (args[0] == \"\"test\"\")\n {\n i = 0;\n }\n\n /*\n // to resolve, either initialize the variables when declared\n // or provide for logic to initialize them, as follows:\n else\n {\n i = 1;\n }\n */\n\n j = i; // CS0165, i might be uninitialized\n\n MyClass myClass;\n myClass.i = 0; // CS0165\n // use new as follows\n // MyClass myClass = new MyClass();\n // myClass.i = 0;\n i = j;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 26, Column = 11 } ,\n new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 29, Column = 7 }});\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation02()\n {\n CreateCompilation(\n@\"class C\n{\n static void M(int m)\n {\n int v;\n for (int i = 0; i < m; ++i)\n {\n v = 0;\n }\n M(v);\n int w;\n for (; ; )\n {\n w = 0;\n break;\n }\n M(w);\n for (int x; x < 1; ++x)\n {\n }\n for (int y; m < 1; ++y)\n {\n }\n for (int z; ; )\n {\n M(z);\n }\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"v\").WithArguments(\"v\").WithLocation(10, 11),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(18, 21),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(21, 30),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"z\").WithArguments(\"z\").WithLocation(26, 15));\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation03()\n {\n CreateCompilation(\n@\"class C\n{\n static int F()\n {\n return 0;\n }\n static void M0()\n {\n int a, b, c, d;\n for (a = 1; (b = F()) < 2; c = 3) { d = 4; }\n if (a == 0) { }\n if (b == 0) { }\n if (c == 0) { } // Use of unassigned 'c'\n if (d == 0) { } // Use of unassigned 'd'\n }\n static void M1()\n {\n int x, y;\n for (x = 0; (y = x) < 10; ) { }\n if (y == 0) { } // no error\n }\n static void M2()\n {\n int x, y;\n for (x = 0; x < 10; y = x) { }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M3()\n {\n int x, y;\n for (x = 0; x < 10; ) { y = x; }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M4()\n {\n int x, y;\n for (y = x; (x = 0) < 10; ) { } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M5()\n {\n int x, y;\n for (; (x = 0) < 10; y = x) { }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M6()\n {\n int x, y;\n for (; (x = 0) < 10; ) { y = x; }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M7()\n {\n int x, y;\n for (y = x; F() < 10; x = 0) { } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M8()\n {\n int x, y;\n for (; (y = x) < 10; x = 0) { } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M9()\n {\n int x, y;\n for (; F() < 10; x = 0) { y = x; } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M10()\n {\n int x, y;\n for (y = x; F() < 10; ) { x = 0; } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M11()\n {\n int x, y;\n for (; F() < 10; y = x) { x = 0; }\n if (y == 0) { } // Use of unassigned 'y'\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"c\").WithArguments(\"c\").WithLocation(13, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"d\").WithArguments(\"d\").WithLocation(14, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(26, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(32, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(37, 18),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(44, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(50, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(55, 18),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(61, 21),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(67, 39),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(68, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(73, 18),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(80, 13));\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation04()\n {\n CreateCompilation(\n@\"class C\n{\n static int M()\n {\n int x, y, z;\n try\n {\n x = 0;\n y = 1;\n }\n catch (System.Exception)\n {\n x = 1;\n }\n finally\n {\n z = 1;\n }\n return (x + y + z);\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(19, 21));\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation05()\n {\n // This is a \"negative\" test case; we should *not* be producing a \"use of unassigned\n // local variable\" error here. In an earlier revision we were doing so because we were\n // losing the information about the first argument being \"out\" when the bad call node\n // was created. Later flow analysis then did not know that \"x\" need not be assigned\n // before it was used, and we'd produce a wrong error.\n CreateCompilation(\n@\"class C\n{\n static int N(out int q) { q = 1; return 2;}\n static void M()\n {\n int x = N(out x, 123);\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadArgCount, \"N\").WithArguments(\"N\", \"2\"));\n }\n\n [WorkItem(540860, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540860\")]\n [Fact]\n public void CS0165ERR_UseDefViolation06()\n {\n // Should not generate \"unassigned local variable\" for struct.\n CreateCompilation(\n@\"struct S\n{\n public void M() { }\n}\nclass C\n{\n void M()\n {\n S s;\n s.M();\n }\n}\")\n .VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation07()\n {\n // Make sure flow analysis is hooked up for indexers\n CreateCompilation(\n@\"struct S\n{\n public int this[int x] { get { return 0; } }\n}\nclass C\n{\n public int this[int x] { get { return 0; } }\n}\nclass Test\n{\n static void Main()\n {\n int unassigned1;\n int unassigned2;\n int sink;\n\n C c;\n sink = c[1]; //CS0165\n\n c = new C();\n sink = c[1]; //fine\n sink = c[unassigned1]; //CS0165\n\n S s;\n sink = s[1]; //fine - struct with no fields\n\n s = new S();\n sink = s[1]; //fine\n sink = s[unassigned2]; //CS0165\n }\n}\")\n .VerifyDiagnostics(\n // (18,16): error CS0165: Use of unassigned local variable 'c'\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"c\").WithArguments(\"c\"),\n // (22,18): error CS0165: Use of unassigned local variable 'unassigned1'\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"unassigned1\").WithArguments(\"unassigned1\"),\n // (29,18): error CS0165: Use of unassigned local variable 'unassigned2'\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"unassigned2\").WithArguments(\"unassigned2\"));\n }\n\n [WorkItem(3402, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0170ERR_UseDefViolationField()\n {\n var text = @\"\npublic struct error\n{\n public int i;\n}\n\npublic class MyClass\n{\n public static void Main()\n {\n error e;\n // uncomment the next line to resolve this error\n // e.i = 0;\n System.Console.WriteLine( e.i ); // CS0170 because \n //e.i was never assigned\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationField, Line = 14, Column = 33 } });\n }\n\n [Fact]\n public void CS0171ERR_UnassignedThis()\n {\n var text = @\"\nstruct MyStruct\n{\n MyStruct(int initField) // CS0171\n {\n // i = initField; // uncomment this line to resolve this error\n }\n public int i;\n}\n\nclass MyClass\n{\n public static void Main()\n {\n MyStruct aStruct = new MyStruct();\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (4,4): error CS0171: Field 'MyStruct.i' must be fully assigned before control is returned to the caller\n // MyStruct(int initField) // CS0171\n Diagnostic(ErrorCode.ERR_UnassignedThis, \"MyStruct\").WithArguments(\"MyStruct.i\"),\n // (15,16): warning CS0219: The variable 'aStruct' is assigned but its value is never used\n // MyStruct aStruct = new MyStruct();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"aStruct\").WithArguments(\"aStruct\"),\n // (8,15): warning CS0649: Field 'MyStruct.i' is never assigned to, and will always have its default value 0\n // public int i;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"i\").WithArguments(\"MyStruct.i\", \"0\")\n );\n }\n\n [Fact]\n public void FieldAssignedInReferencedConstructor()\n {\n var text =\n@\"struct S\n{\n private readonly object _x;\n S(object o)\n {\n _x = o;\n }\n S(object x, object y) : this(x ?? y)\n {\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(); // No CS0171 for S._x\n }\n\n [Fact()]\n public void CS0172ERR_AmbigQM()\n {\n var text = @\"\npublic class Square\n{\n public class Circle\n {\n public static implicit operator Circle(Square aa)\n {\n return null;\n }\n\n public static implicit operator Square(Circle aa)\n {\n return null;\n }\n }\n\n public static void Main()\n {\n Circle aa = new Circle();\n Square ii = new Square();\n var o1 = (1 == 1) ? aa : ii; // CS0172\n object o2 = (1 == 1) ? aa : ii; // CS8652\n }\n}\";\n CreateCompilation(text, parseOptions: TestOptions.Regular8).VerifyDiagnostics(\n // (21,16): error CS0172: Type of conditional expression cannot be determined because 'Square.Circle' and 'Square' implicitly convert to one another\n // var o1 = (1 == 1) ? aa : ii; // CS0172\n Diagnostic(ErrorCode.ERR_AmbigQM, \"(1 == 1) ? aa : ii\").WithArguments(\"Square.Circle\", \"Square\").WithLocation(21, 16),\n // (22,19): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between 'Square.Circle' and 'Square'. To use a target-typed conversion, upgrade to language version 9.0 or greater.\n // object o2 = (1 == 1) ? aa : ii; // CS8652\n Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, \"(1 == 1) ? aa : ii\").WithArguments(\"8.0\", \"Square.Circle\", \"Square\", \"9.0\").WithLocation(22, 19)\n );\n }\n\n [Fact]\n public void CS0173ERR_InvalidQM()\n {\n var text = @\"\npublic class C {}\npublic class A {}\n\npublic class MyClass\n{\n public static void F(bool b)\n {\n A a = new A();\n C c = new C();\n var o = b ? a : c; // CS0173\n }\n\n public static void Main()\n {\n F(true);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,15): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C'\n // var o = b ? a : c; // CS0173\n Diagnostic(ErrorCode.ERR_InvalidQM, \"b ? a : c\").WithArguments(\"A\", \"C\").WithLocation(11, 15)\n );\n }\n\n [WorkItem(528331, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528331\")]\n [Fact]\n public void CS0173ERR_InvalidQM_FuncCall()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n var s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1);\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1)\").WithArguments(\"void\").WithLocation(6, 13));\n }\n\n [Fact]\n public void CS0173ERR_InvalidQM_GeneralType()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n A a = new A();\n A b = new A();\n var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert\n }\n}\nclass A\n{\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'A'\n // var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert\n Diagnostic(ErrorCode.ERR_InvalidQM, \"1 > 2 ? a : b\").WithArguments(\"A\", \"A\").WithLocation(8, 17)\n );\n }\n\n [WorkItem(540902, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540902\")]\n [Fact]\n public void CS0173ERR_InvalidQM_foreach()\n {\n var text = @\"\npublic class Test\n{\n public static void Main()\n {\n S[] x = null;\n foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY\n { }\n C[] y= null;\n foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY\n { }\n }\n}\nstruct S { }\nclass C { }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'S[]' and 'int'\n // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY\n Diagnostic(ErrorCode.ERR_InvalidQM, \"true ? x : 1\").WithArguments(\"S[]\", \"int\"),\n // (7,20): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"x\").WithArguments(\"x\"),\n // (11,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'C[]'\n // foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY\n Diagnostic(ErrorCode.ERR_InvalidQM, \"false ? 1 : y\").WithArguments(\"int\", \"C[]\")\n );\n }\n\n // /// Scenarios? \n // [Fact]\n // public void CS0174ERR_NoBaseClass()\n // {\n // var text = @\"\n // \";\n // CreateCompilationWithMscorlib(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoBaseClass, \"?\"));\n // }\n\n [WorkItem(543360, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543360\")]\n [Fact()]\n public void CS0175ERR_BaseIllegal()\n {\n var text = @\"\nusing System;\nclass Base\n{\n public int TestInt = 0;\n}\n\nclass MyClass : Base\n{\n public void BaseTest()\n {\n Console.WriteLine(base); // CS0175\n base = 9; // CS0175\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,27): error CS0175: Use of keyword 'base' is not valid in this context\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\").WithLocation(12, 27),\n // (12,9): error CS0175: Use of keyword 'base' is not valid in this context\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\").WithLocation(13, 9)\n );\n }\n\n [WorkItem(528624, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528624\")]\n [Fact()]\n public void CS0175ERR_BaseIllegal_02()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nclass MyClass : List\n{\n public void BaseTest()\n {\n var x = from i in base select i;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,27): error CS0175: Use of keyword 'base' is not valid in this context\n // var x = from i in base select i;\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\")\n );\n }\n\n [Fact]\n public void CS0176ERR_ObjectProhibited01()\n {\n var source = @\"\nclass A\n{\n class B\n {\n static void Method() { }\n void M()\n {\n this.Method();\n }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,13): error CS0176: Member 'A.B.Method()' cannot be accessed with an instance reference; qualify it with a type name instead\n // this.Method();\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"this.Method\").WithArguments(\"A.B.Method()\").WithLocation(9, 13)\n );\n }\n\n [Fact]\n public void CS0176ERR_ObjectProhibited02()\n {\n var source = @\"\nclass C\n{\n static object field;\n static object Property { get; set; }\n void M(C c)\n {\n Property = field; // no error\n C.Property = C.field; // no error\n this.field = this.Property;\n c.Property = c.field;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,9): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead\n // this.field = this.Property;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"this.field\").WithArguments(\"C.field\"),\n // (9,22): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead\n // this.field = this.Property;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"this.Property\").WithArguments(\"C.Property\"),\n // (10,9): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead\n // c.Property = c.field;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"c.Property\").WithArguments(\"C.Property\"),\n // (10,22): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead\n // c.Property = c.field;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"c.field\").WithArguments(\"C.field\")\n );\n }\n\n [Fact]\n public void CS0176ERR_ObjectProhibited03()\n {\n var source =\n@\"class A\n{\n internal static object F;\n}\nclass B where T : A\n{\n static void M(T t)\n {\n object q = t.F;\n t.ReferenceEquals(q, null);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,20): error CS0176: Member 'A.F' cannot be accessed with an instance reference; qualify it with a type name instead\n // object q = t.F;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"t.F\").WithArguments(\"A.F\").WithLocation(9, 20),\n // (10,9): error CS0176: Member 'object.ReferenceEquals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead\n // t.ReferenceEquals(q, null);\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"t.ReferenceEquals\").WithArguments(\"object.ReferenceEquals(object, object)\").WithLocation(10, 9),\n // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null\n // internal static object F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"A.F\", \"null\").WithLocation(3, 28));\n }\n\n [WorkItem(543361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361\")]\n [Fact]\n public void CS0176ERR_ObjectProhibited04()\n {\n var source = @\"\npublic delegate void D();\nclass Test\n{\n public event D D;\n\n public void TestIdenticalEventName()\n {\n D.CreateDelegate(null, null, null); // CS0176\n }\n}\n\";\n CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics(\n // (9,9): error CS0176: Member 'Delegate.CreateDelegate(Type, object, string)' cannot be accessed with an instance reference; qualify it with a type name instead\n // D.CreateDelegate(null, null, null); // CS0176\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"D.CreateDelegate\").WithArguments(\"System.Delegate.CreateDelegate(System.Type, object, string)\").WithLocation(9, 9)\n );\n }\n\n // Identical to CS0176ERR_ObjectProhibited04, but with event keyword removed (i.e. field instead of field-like event).\n [WorkItem(543361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361\")]\n [Fact]\n public void CS0176ERR_ObjectProhibited05()\n {\n var source = @\"\npublic delegate void D();\nclass Test\n{\n public D D;\n\n public void TestIdenticalEventName()\n {\n D.CreateDelegate(null, null, null); // CS0176\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,14): warning CS0649: Field 'Test.D' is never assigned to, and will always have its default value null\n // public D D;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"D\").WithArguments(\"Test.D\", \"null\")\n );\n }\n\n [Fact]\n public void CS0177ERR_ParamUnassigned01()\n {\n var text =\n@\"class C\n{\n static void M(out int x, out int y, out int z)\n {\n try\n {\n x = 0;\n y = 1;\n }\n catch (System.Exception)\n {\n x = 1;\n }\n finally\n {\n z = 1;\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"M\").WithArguments(\"y\").WithLocation(3, 17));\n }\n\n [WorkItem(528243, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528243\")]\n [Fact]\n public void CS0177ERR_ParamUnassigned02()\n {\n var text =\n@\"class C\n{\n static bool P { get { return false; } }\n static object M(out object x)\n {\n if (P)\n {\n object o = P ? M(out x) : null;\n return o;\n }\n return P ? null : M(out x);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method\n // return o;\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"return o;\").WithArguments(\"x\").WithLocation(9, 13),\n // (11,9): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method\n // return P ? null : M(out x);\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"return P ? null : M(out x);\").WithArguments(\"x\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0185ERR_LockNeedsReference()\n {\n var text = @\"\npublic class MainClass\n{\n public static void Main ()\n {\n lock (1) // CS0185\n // try the following lines instead\n // MainClass x = new MainClass();\n // lock(x)\n {\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LockNeedsReference, Line = 6, Column = 15 } });\n }\n\n [Fact]\n public void CS0186ERR_NullNotValid()\n {\n var text = @\"\nusing System.Collections;\n\nclass MyClass\n{\n static void Main()\n {\n // Each of the following lines generates CS0186:\n foreach (int i in null) { } // CS0186\n foreach (int i in (IEnumerable)null) { }; // CS0186\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 9, Column = 27 } ,\n new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 10, Column = 27 }});\n }\n\n [Fact]\n public void CS0186ERR_NullNotValid02()\n {\n var text = @\"\npublic class Test\n{\n public static void Main(string[] args)\n {\n foreach (var x in default(int[])) { }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NullNotValid, \"default(int[])\"));\n }\n\n [WorkItem(540983, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540983\")]\n [Fact]\n public void CS0188ERR_UseDefViolationThis()\n {\n var text = @\"\nnamespace MyNamespace\n{\n class MyClass\n {\n struct S\n {\n public int a;\n\n void Goo()\n {\n }\n\n S(int i)\n {\n // a = i;\n Goo(); // CS0188\n }\n }\n public static void Main()\n { }\n\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (17,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n // Goo(); // CS0188\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"Goo\").WithArguments(\"this\"),\n // (8,24): warning CS0649: Field 'MyNamespace.MyClass.S.a' is never assigned to, and will always have its default value 0\n // public int a;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"a\").WithArguments(\"MyNamespace.MyClass.S.a\", \"0\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\"), WorkItem(864605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605\")]\n public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ImplicitReceiver()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n\tint value;\n\n public S(int v)\n {\n var b1 = F is Action;\n value = v;\n }\n \n void F()\n {\n \n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"F is Action\").WithLocation(10, 18),\n // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"F\").WithArguments(\"this\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\"), WorkItem(864605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605\")]\n public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ExplicitReceiver()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n\tint value;\n\n public S(int v)\n {\n var b1 = this.F is Action;\n value = v;\n }\n \n void F()\n {\n \n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // var b1 = this.F is Action;\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"this.F is Action\").WithLocation(10, 18),\n // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n // var b1 = this.F is Action;\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"this\").WithArguments(\"this\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\")]\n public void CS0188ERR_UseDefViolationThis_ImplicitReceiverInDynamic()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n dynamic value;\n \n public S(dynamic d)\n {\n /*this.*/ Add(d);\n throw new NotImplementedException();\n }\n \n void Add(int value)\n {\n this.value += value;\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,19): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"Add\").WithArguments(\"this\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\")]\n public void CS0188ERR_UseDefViolationThis_ExplicitReceiverInDynamic()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n dynamic value;\n \n public S(dynamic d)\n {\n this.Add(d);\n throw new NotImplementedException();\n }\n \n void Add(int value)\n {\n this.value += value;\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS0190ERR_ArgsInvalid()\n {\n string source = @\"\nusing System;\npublic class C\n{\n static void M(__arglist)\n {\n ArgIterator ai = new ArgIterator(__arglist); \n }\n static void Main()\n {\n M(__arglist);\n }\n}\";\n var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45);\n comp.VerifyDiagnostics(\n // (11,7): error CS0190: The __arglist construct is valid only within a variable argument method\n // M(__arglist);\n Diagnostic(ErrorCode.ERR_ArgsInvalid, \"__arglist\")\n );\n }\n\n [Fact]\n public void CS4013ERR_SpecialByRefInLambda01()\n {\n // Note that the native compiler does *not* produce an error when you illegally\n // use __arglist inside a lambda, oddly enough. Roslyn does.\n\n string source = @\"\nusing System;\nusing System.Linq;\npublic class C\n{\n delegate int D(RuntimeArgumentHandle r);\n static void M(__arglist)\n {\n D f = null;\n f = x=>f(__arglist);\n f = delegate { return f(__arglist); };\n var q = from x in new int[10] select f(__arglist);\n }\n static void Main()\n {\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(source);\n comp.VerifyDiagnostics(\n // (10,14): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // f = x=>f(__arglist);\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (11,29): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // f = delegate { return f(__arglist); };\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (12,44): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // var q = from x in new int[10] select f(__arglist);\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\")\n );\n }\n\n [Fact]\n public void CS4013ERR_SpecialByRefInLambda02()\n {\n string source = @\"\nusing System;\npublic class C\n{\n static void M(__arglist)\n {\n RuntimeArgumentHandle h = __arglist;\n Action action = ()=> \n { \n RuntimeArgumentHandle h2 = h; // Bad use of h\n ArgIterator args1 = new ArgIterator(h); // Bad use of h\n RuntimeArgumentHandle h3 = h2; // no error; does not create field\n ArgIterator args2 = new ArgIterator(h2); // no error; does not create field\n };\n }\n static void Main()\n {\n }\n}\";\n CreateCompilationWithMscorlib45(source).VerifyEmitDiagnostics(\n // (10,34): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // RuntimeArgumentHandle h2 = h; // Bad use of h\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (11,43): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // ArgIterator args1 = new ArgIterator(h); // Bad use of h\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h\").WithArguments(\"System.RuntimeArgumentHandle\"));\n }\n\n [Fact]\n public void CS4013ERR_SpecialByRefInLambda03()\n {\n string source = @\"\nusing System;\nusing System.Collections.Generic;\npublic class C\n{\n static void N(RuntimeArgumentHandle x) {}\n static IEnumerable M(RuntimeArgumentHandle h1) // Error: hoisted to field\n {\n N(h1);\n yield return 1;\n RuntimeArgumentHandle h2 = default(RuntimeArgumentHandle);\n yield return 2;\n N(h2); // Error: hoisted to field\n yield return 3;\n RuntimeArgumentHandle h3 = default(RuntimeArgumentHandle);\n N(h3); // No error; we don't need to hoist this one to a field\n }\n static void Main()\n {\n }\n}\";\n\n CreateCompilation(source).Emit(new System.IO.MemoryStream()).Diagnostics\n .Verify(\n // (7,51): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // static IEnumerable M(RuntimeArgumentHandle h1) // Error: hoisted to field\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h1\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (13,7): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // N(h2); // Error: hoisted to field\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h2\").WithArguments(\"System.RuntimeArgumentHandle\")\n );\n }\n\n [Fact, WorkItem(538008, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538008\")]\n public void CS0191ERR_AssgReadonly()\n {\n var source =\n@\"class MyClass\n{\n public readonly int TestInt = 6; // OK to assign to readonly field in declaration\n\n public MyClass()\n {\n TestInt = 11; // OK to assign to readonly field in constructor\n TestInt = 12; // OK to assign to readonly field multiple times in constructor\n this.TestInt = 13; // OK to assign with explicit this receiver\n MyClass t = this;\n t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this\n }\n\n public void TestReadOnly()\n {\n TestInt = 19; // CS0191\n }\n\n public static void Main()\n {\n }\n}\n\nclass MyDerived : MyClass\n{\n MyDerived()\n {\n TestInt = 15; // CS0191 - not in declaring class\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (28,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer))\n // TestInt = 15; // CS0191 - not in declaring class\n Diagnostic(ErrorCode.ERR_AssgReadonly, \"TestInt\").WithLocation(28, 9),\n // (11,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer))\n // t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this\n Diagnostic(ErrorCode.ERR_AssgReadonly, \"t.TestInt\").WithLocation(11, 9),\n // (16,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer))\n // TestInt = 19; // CS0191\n Diagnostic(ErrorCode.ERR_AssgReadonly, \"TestInt\").WithLocation(16, 9));\n }\n\n [WorkItem(538009, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538009\")]\n [Fact]\n public void CS0192ERR_RefReadonly()\n {\n var text = @\"\n class MyClass\n{\n public readonly int TestInt = 6;\n static void TestMethod(ref int testInt)\n {\n testInt = 0;\n }\n\n MyClass()\n {\n TestMethod(ref TestInt); // OK\n }\n\n public void PassReadOnlyRef()\n {\n TestMethod(ref TestInt); // CS0192\n }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonly, Line = 17, Column = 24 } });\n }\n\n [Fact]\n public void CS0193ERR_PtrExpected()\n {\n var text = @\"\nusing System;\n\npublic struct Age\n{\n public int AgeYears;\n public int AgeMonths;\n public int AgeDays;\n}\n\npublic class MyClass\n{\n public static void SetAge(ref Age anAge, int years, int months, int days)\n {\n anAge->Months = 3; // CS0193, anAge is not a pointer\n // try the following line instead\n // anAge.AgeMonths = 3;\n }\n\n public static void Main()\n {\n Age MyAge = new Age();\n Console.WriteLine(MyAge.AgeMonths);\n SetAge(ref MyAge, 22, 4, 15);\n Console.WriteLine(MyAge.AgeMonths);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PtrExpected, Line = 15, Column = 7 } });\n }\n\n [CompilerTrait(CompilerFeature.IOperation)]\n [Fact]\n public void CS0196ERR_PtrIndexSingle()\n {\n var text = @\"\nunsafe public class MyClass\n{\n public static void Main ()\n {\n int *i = null;\n int j = 0;\n j = i[1,2]; // CS0196\n // try the following line instead\n // j = i[1];\n }\n}\";\n var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (8,11): error CS0196: A pointer must be indexed by only one value\n // j = i[1,2]; // CS0196\n Diagnostic(ErrorCode.ERR_PtrIndexSingle, \"i[1,2]\"));\n\n\n var tree = compilation.SyntaxTrees.Single();\n var node = tree.GetRoot().DescendantNodes().OfType().First();\n\n Assert.Equal(\"i[1,2]\", node.ToString());\n\n compilation.VerifyOperationTree(node, expectedOperationTree:\n@\"\nIOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1,2]')\n Children(2):\n ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32*, IsInvalid) (Syntax: 'i')\n IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1,2]')\n Children(2):\n ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')\n ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')\n\");\n }\n\n [Fact]\n public void CS0198ERR_AssgReadonlyStatic()\n {\n var text = @\"\npublic class MyClass\n{\n public static readonly int TestInt = 6;\n\n static MyClass()\n {\n TestInt = 7;\n TestInt = 8;\n MyClass.TestInt = 7;\n }\n\n public MyClass()\n {\n TestInt = 11; // CS0198, constructor is not static and readonly field is\n }\n\n private void InstanceMethod()\n {\n TestInt = 12; // CS0198\n }\n\n private void StaticMethod()\n {\n TestInt = 13; // CS0198\n }\n\n public static void Main()\n {\n }\n}\n\nclass MyDerived : MyClass\n{\n static MyDerived()\n {\n MyClass.TestInt = 14; // CS0198, not in declaring class\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[]\n {\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 15, Column = 7 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 20, Column = 8 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 25, Column = 8 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 37, Column = 9 },\n });\n }\n\n [Fact, WorkItem(990, \"https://github.com/dotnet/roslyn/issues/990\")]\n public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01()\n {\n var text =\n@\"public static class Goo\n{\n static Goo()\n {\n Goo.X = 1;\n Goo.Y = 2;\n Goo.Y = 3;\n }\n\n public static readonly int X;\n public static int Y { get; }\n}\";\n CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (6,9): error CS0200: Property or indexer 'Goo.Y' cannot be assigned to -- it is read only\n // Goo.Y = 2;\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"Goo.Y\").WithArguments(\"Goo.Y\").WithLocation(6, 9)\n );\n CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (5,9): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)\n // Goo.X = 1;\n Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, \"Goo.X\").WithLocation(5, 9),\n // (6,9): error CS0200: Property or indexer 'Goo.Y' cannot be assigned to -- it is read only\n // Goo.Y = 2;\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"Goo.Y\").WithArguments(\"Goo.Y\").WithLocation(6, 9)\n );\n }\n\n [Fact, WorkItem(990, \"https://github.com/dotnet/roslyn/issues/990\")]\n public void WriteOfReadonlyStaticMemberOfAnotherInstantiation02()\n {\n var text =\n@\"using System;\nusing System.Threading;\nclass Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(Goo.x);\n Console.WriteLine(Goo.x);\n Console.WriteLine(Goo.x);\n Console.WriteLine(Goo.x);\n }\n}\n\npublic static class Goo\n{\n static Goo()\n {\n Console.WriteLine(\"\"initializing for \"\" + typeof(T));\n Goo.x = typeof(T).Name;\n }\n\n public static readonly string x;\n}\";\n var expectedOutput =\n@\"initializing for System.Int64\ninitializing for System.Int32\n\nInt64\ninitializing for System.String\n\nString\n\";\n // Although we accept this nasty code, it will not verify.\n CompileAndVerify(text, expectedOutput: expectedOutput, verify: Verification.Fails);\n }\n\n [Fact]\n public void CS0199ERR_RefReadonlyStatic()\n {\n var text = @\"\nclass MyClass\n{\n public static readonly int TestInt = 6;\n\n static void TestMethod(ref int testInt)\n {\n testInt = 0;\n }\n\n MyClass()\n {\n TestMethod(ref TestInt); // CS0199, TestInt is static\n }\n\n public static void Main()\n {\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonlyStatic, Line = 13, Column = 24 } });\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp01()\n {\n var source =\n@\"abstract class A\n{\n internal static A P { get { return null; } }\n internal object Q { get; set; }\n public abstract object R { get; }\n}\nclass B : A\n{\n public override object R { get { return null; } }\n}\nclass Program\n{\n static void M(B b)\n {\n B.P.Q = null;\n B.P = null; // CS0200\n b.R = null; // CS0200\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,9): error CS0200: Property or indexer 'A.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"B.P\").WithArguments(\"A.P\").WithLocation(16, 9),\n // (17,9): error CS0200: Property or indexer 'B.R' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.R\").WithArguments(\"B.R\").WithLocation(17, 9));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp02()\n {\n var source =\n@\"class A\n{\n public virtual A P { get; set; }\n public A Q { get { return null; } }\n}\nclass B : A\n{\n public override A P { get { return null; } }\n}\nclass Program\n{\n static void M(B b)\n {\n b.P = null;\n b.Q = null; // CS0200\n b.Q.P = null;\n b.P.Q = null; // CS0200\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (15,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.Q\").WithArguments(\"A.Q\").WithLocation(15, 9),\n // (17,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.P.Q\").WithArguments(\"A.Q\").WithLocation(17, 9));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp03()\n {\n var source =\n@\"class C\n{\n static int P { get { return 0; } }\n int Q { get { return 0; } }\n static void M(C c)\n {\n ++P;\n ++c.Q;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,11): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"P\").WithArguments(\"C.P\").WithLocation(7, 11),\n // (8,11): error CS0200: Property or indexer 'C.Q' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"c.Q\").WithArguments(\"C.Q\").WithLocation(8, 11));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp04()\n {\n var source =\n@\"class C\n{\n object P { get { P = null; return null; } }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,22): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"P\").WithArguments(\"C.P\").WithLocation(3, 22));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp05()\n {\n CreateCompilation(\n@\"class C\n{\n int this[int x] { get { return x; } }\n void M(int b)\n {\n this[0] = b;\n this[1]++;\n this[2] += 1;\n }\n}\")\n .VerifyDiagnostics(\n // (6,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"this[0]\").WithArguments(\"C.this[int]\"),\n // (7,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"this[1]\").WithArguments(\"C.this[int]\"),\n // (8,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"this[2]\").WithArguments(\"C.this[int]\"));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp06()\n {\n var source1 =\n@\"public class A\n{\n public virtual object P { get { return null; } private set { } }\n}\npublic class B : A\n{\n public override object P { get { return null; } }\n}\";\n var compilation1 = CreateCompilation(source1);\n compilation1.VerifyDiagnostics();\n var compilationVerifier = CompileAndVerify(compilation1);\n var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData);\n var source2 =\n@\"class C\n{\n static void M(B b)\n {\n var o = b.P;\n b.P = o;\n }\n}\";\n var compilation2 = CreateCompilation(source2, references: new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (6,9): error CS0200: Property or indexer 'B.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.P\").WithArguments(\"B.P\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0201ERR_IllegalStatement1()\n {\n var text = @\"\npublic class MyList \n{\n public void Add(T x)\n {\n int i = 0;\n if ( (object)x == null)\n {\n checked(i++); // CS0201\n\n // OK\n checked {\n i++; \n }\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,10): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"checked(i++)\"));\n }\n\n [Fact, WorkItem(536863, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863\")]\n public void CS0201ERR_IllegalStatement2()\n {\n var text = @\"\nclass A\n{\n public static int Main()\n {\n (a) => a;\n (a, b) => { };\n int x = 0; int y = 0;\n x + y; x == 1;\n }\n}\";\n CreateCompilation(text, parseOptions: TestOptions.Regular.WithTuplesFeature()).VerifyDiagnostics(\n // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a) => a;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a) => a\").WithLocation(6, 9),\n // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a, b) => { };\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a, b) => { }\").WithLocation(7, 9),\n // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x + y\").WithLocation(9, 9),\n // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x == 1\").WithLocation(9, 16),\n // (4,23): error CS0161: 'A.Main()': not all code paths return a value\n // public static int Main()\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"Main\").WithArguments(\"A.Main()\").WithLocation(4, 23)\n );\n }\n\n [Fact, WorkItem(536863, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863\")]\n public void CS0201ERR_IllegalStatement2WithCSharp6()\n {\n var test = @\"\nclass A\n{\n public static int Main()\n {\n (a) => a;\n (a, b) => { };\n int x = 0; int y = 0;\n x + y; x == 1;\n }\n}\";\n var comp = CreateCompilation(new[] { Parse(test, options: TestOptions.Regular6) }, new MetadataReference[] { });\n comp.VerifyDiagnostics(\n // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a) => a;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a) => a\").WithLocation(6, 9),\n // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a, b) => { };\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a, b) => { }\").WithLocation(7, 9),\n // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x + y\").WithLocation(9, 9),\n // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x == 1\").WithLocation(9, 16),\n // (4,23): error CS0161: 'A.Main()': not all code paths return a value\n // public static int Main()\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"Main\").WithArguments(\"A.Main()\").WithLocation(4, 23)\n );\n }\n\n [Fact]\n public void CS0202ERR_BadGetEnumerator()\n {\n var text = @\"\npublic class C1\n{\n public int Current\n {\n get\n {\n return 0;\n }\n }\n\n public bool MoveNext ()\n {\n return false;\n }\n\n public static implicit operator C1 (int c1)\n {\n return 0;\n }\n}\n\npublic class C2\n{\n public int Current\n {\n get\n {\n return 0;\n }\n }\n\n public bool MoveNext ()\n {\n return false;\n }\n\n public C1[] GetEnumerator ()\n {\n return null;\n }\n}\n\npublic class MainClass\n{\n public static void Main ()\n {\n C2 c2 = new C2();\n\n foreach (C1 x in c2) // CS0202\n {\n System.Console.WriteLine(x.Current);\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadGetEnumerator, Line = 50, Column = 24 } });\n }\n\n // [Fact()]\n // public void CS0204ERR_TooManyLocals()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_TooManyLocals, Line = 8, Column = 13 } }\n // );\n // }\n\n [Fact()]\n public void CS0205ERR_AbstractBaseCall()\n {\n var text =\n@\"abstract class A\n{\n abstract public void M();\n abstract protected object P { get; }\n}\nclass B : A\n{\n public override void M()\n {\n base.M(); // CS0205\n object o = base.P; // CS0205\n }\n protected override object P { get { return null; } }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 10, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 11, Column = 20 });\n }\n\n [Fact]\n public void CS0205ERR_AbstractBaseCall_Override()\n {\n var text =\n@\"\npublic class Base1\n{\n public virtual long Property1 { get { return 0; } set { } }\n}\nabstract public class Base2 : Base1\n{\n public abstract override long Property1 { get; }\n void test1()\n {\n Property1 += 1;\n }\n}\npublic class Derived : Base2\n{\n public override long Property1 { get { return 1; } set { } }\n void test2()\n {\n base.Property1++;\n base.Property1 = 2;\n long x = base.Property1;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1'\n Diagnostic(ErrorCode.ERR_AbstractBaseCall, \"base.Property1\").WithArguments(\"Base2.Property1\"),\n // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1'\n Diagnostic(ErrorCode.ERR_AbstractBaseCall, \"base.Property1\").WithArguments(\"Base2.Property1\"));\n }\n\n [Fact]\n public void CS0206ERR_RefProperty()\n {\n var text =\n@\"class C\n{\n static int P { get; set; }\n object Q { get; set; }\n static void M(ref int i)\n {\n }\n static void M(out object o)\n {\n o = null;\n }\n void M()\n {\n M(ref P); // CS0206\n M(out this.Q); // CS0206\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"P\").WithArguments(\"C.P\"),\n // (15,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"this.Q\").WithArguments(\"C.Q\"));\n }\n\n [Fact]\n public void CS0206ERR_RefProperty_Indexers()\n {\n var text =\n@\"class C\n{\n int this[int x] { get { return x; } set { } }\n static void R(ref int i)\n {\n }\n static void O(out int o)\n {\n o = 0;\n }\n void M()\n {\n R(ref this[0]); // CS0206\n O(out this[0]); // CS0206\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"this[0]\").WithArguments(\"C.this[int]\"),\n // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"this[0]\").WithArguments(\"C.this[int]\"));\n }\n\n [Fact]\n public void CS0208ERR_ManagedAddr01()\n {\n var text = @\"\nclass myClass\n{\n public int a = 98;\n}\n\nstruct myProblemStruct\n{\n string s;\n float f;\n}\n\nstruct myGoodStruct\n{\n int i;\n float f;\n}\n\npublic class MyClass\n{\n unsafe public static void Main()\n {\n // myClass is a class, a managed type.\n myClass s = new myClass(); \n myClass* s2 = &s; // CS0208\n\n // The struct contains a string, a managed type.\n int i = sizeof(myProblemStruct); //CS0208\n \n // The struct contains only value types.\n i = sizeof(myGoodStruct); //OK\n \n }\n}\n\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (25,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass')\n // myClass* s2 = &s; // CS0208\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"myClass*\").WithArguments(\"myClass\"),\n // (25,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass')\n // myClass* s2 = &s; // CS0208\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"&s\").WithArguments(\"myClass\"),\n // (28,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myProblemStruct')\n // int i = sizeof(myProblemStruct); //CS0208\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"sizeof(myProblemStruct)\").WithArguments(\"myProblemStruct\"),\n\n // (9,12): warning CS0169: The field 'myProblemStruct.s' is never used\n // string s;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"s\").WithArguments(\"myProblemStruct.s\"),\n // (10,11): warning CS0169: The field 'myProblemStruct.f' is never used\n // float f;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"f\").WithArguments(\"myProblemStruct.f\"),\n // (15,9): warning CS0169: The field 'myGoodStruct.i' is never used\n // int i;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"i\").WithArguments(\"myGoodStruct.i\"),\n // (16,11): warning CS0169: The field 'myGoodStruct.f' is never used\n // float f;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"f\").WithArguments(\"myGoodStruct.f\"));\n }\n\n [Fact]\n public void CS0208ERR_ManagedAddr02()\n {\n var source =\n@\"enum E { }\ndelegate void D();\nstruct S { }\ninterface I { }\nunsafe class C\n{\n object* _object;\n void* _void;\n bool* _bool;\n char* _char;\n sbyte* _sbyte;\n byte* _byte;\n short* _short;\n ushort* _ushort;\n int* _int;\n uint* _uint;\n long* _long;\n ulong* _ulong;\n decimal* _decimal;\n float* _float;\n double* _double;\n string* _string;\n System.IntPtr* _intptr;\n System.UIntPtr* _uintptr;\n int** _intptr2;\n int?* _nullable;\n dynamic* _dynamic;\n E* e;\n D* d;\n S* s;\n I* i;\n C* c;\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll)\n .GetDiagnostics()\n .Where(d => d.Severity == DiagnosticSeverity.Error)\n .Verify(\n // (22,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')\n // string* _string;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"_string\").WithArguments(\"string\").WithLocation(22, 13),\n // (27,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')\n // dynamic* _dynamic;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"_dynamic\").WithArguments(\"dynamic\").WithLocation(27, 14),\n // (29,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('D')\n // D* d;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"d\").WithArguments(\"D\").WithLocation(29, 8),\n // (31,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('I')\n // I* i;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"i\").WithArguments(\"I\").WithLocation(31, 8),\n // (32,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')\n // C* c;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"c\").WithArguments(\"C\").WithLocation(32, 8),\n // (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object')\n // object* _object;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"_object\").WithArguments(\"object\").WithLocation(7, 13));\n }\n\n [Fact]\n public void CS0209ERR_BadFixedInitType()\n {\n var text = @\"\nclass Point\n{\n public int x, y;\n}\n\npublic class MyClass\n{\n unsafe public static void Main()\n {\n Point pt = new Point();\n\n fixed (int i) // CS0209\n {\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (13,18): error CS0209: The type of a local declared in a fixed statement must be a pointer type\n // fixed (int i) // CS0209\n Diagnostic(ErrorCode.ERR_BadFixedInitType, \"i\"),\n // (13,18): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // fixed (int i) // CS0209\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"i\"),\n\n // (4,15): warning CS0649: Field 'Point.x' is never assigned to, and will always have its default value 0\n // public int x, y;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"x\").WithArguments(\"Point.x\", \"0\"),\n // (4,18): warning CS0649: Field 'Point.y' is never assigned to, and will always have its default value 0\n // public int x, y;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"y\").WithArguments(\"Point.y\", \"0\"));\n }\n\n [Fact]\n public void CS0210ERR_FixedMustInit()\n {\n var text = @\"\nusing System.IO;\nclass Test \n{\n static void Main() \n {\n using (StreamWriter w) // CS0210\n {\n w.WriteLine(\"\"Hello there\"\");\n }\n\n using (StreamWriter x, y) // CS0210, CS0210\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // using (StreamWriter w) // CS0210\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"w\").WithLocation(7, 27),\n // (12,27): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // using (StreamWriter x, y) // CS0210, CS0210\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"x\").WithLocation(12, 27),\n // (12,30): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // using (StreamWriter x, y) // CS0210, CS0210\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"y\").WithLocation(12, 30),\n // (9,10): error CS0165: Use of unassigned local variable 'w'\n // w.WriteLine(\"Hello there\");\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"w\").WithArguments(\"w\").WithLocation(9, 10)\n );\n }\n\n [Fact]\n public void CS0211ERR_InvalidAddrOp()\n {\n var text = @\"\npublic class MyClass\n{\n unsafe public void M()\n {\n int a = 0, b = 0;\n int *i = &(a + b); // CS0211, the addition of two local variables\n // try the following line instead\n // int *i = &a;\n }\n\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,18): error CS0211: Cannot take the address of the given expression\n // int *i = &(a + b); // CS0211, the addition of two local variables\n Diagnostic(ErrorCode.ERR_InvalidAddrOp, \"a + b\"));\n }\n\n [Fact]\n public void CS0212ERR_FixedNeeded()\n {\n var text = @\"\npublic class A {\n public int iField = 5;\n \n unsafe public void M() { \n A a = new A();\n int* ptr = &a.iField; // CS0212 \n }\n\n // OK\n unsafe public void M2() {\n A a = new A();\n fixed (int* ptr = &a.iField) {}\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer\n // int* ptr = &a.iField; // CS0212 \n Diagnostic(ErrorCode.ERR_FixedNeeded, \"&a.iField\"));\n }\n\n [Fact]\n public void CS0213ERR_FixedNotNeeded()\n {\n var text = @\"\npublic class MyClass\n{\n unsafe public static void Main()\n {\n int i = 45;\n fixed (int *j = &i) { } // CS0213\n // try the following line instead\n // int* j = &i;\n\n int[] a = new int[] {1,2,3};\n fixed (int *b = a)\n {\n fixed (int *c = b) { } // CS0213\n // try the following line instead\n // int *c = b;\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,23): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression\n // fixed (int *j = &i) { } // CS0213\n Diagnostic(ErrorCode.ERR_FixedNotNeeded, \"&i\").WithLocation(7, 23),\n // (14,26): error CS9385: The given expression cannot be used in a fixed statement\n // fixed (int *c = b) { } // CS0213\n Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, \"b\").WithLocation(14, 26));\n }\n\n [Fact]\n public void CS0217ERR_BadBoolOp()\n {\n // Note that the wording of this error message has changed.\n\n var text = @\"\npublic class MyClass\n{\n public static bool operator true (MyClass f)\n {\n return false;\n }\n\n public static bool operator false (MyClass f)\n {\n return false;\n }\n\n public static int operator & (MyClass f1, MyClass f2) \n {\n return 0;\n }\n\n public static void Main()\n {\n MyClass f = new MyClass();\n int i = f && f; // CS0217\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (22,15): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('MyClass.operator &(MyClass, MyClass)') must have the same return type and parameter types\n // int i = f && f; // CS0217\n Diagnostic(ErrorCode.ERR_BadBoolOp, \"f && f\").WithArguments(\"MyClass.operator &(MyClass, MyClass)\"));\n }\n\n // CS0220 ERR_CheckedOverflow - see ConstantTests\n\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked01()\n {\n string text =\n@\"class MyClass\n{\n static void F(int x) { }\n static void M()\n {\n F((int)0xFFFFFFFF); // CS0221\n F(unchecked((int)uint.MaxValue));\n F(checked((int)(uint.MaxValue - 1))); // CS0221\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,11): error CS0221: Constant value '4294967295' cannot be converted to a 'int' (use 'unchecked' syntax to override)\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"(int)0xFFFFFFFF\").WithArguments(\"4294967295\", \"int\"),\n // (8,19): error CS0221: Constant value '4294967294' cannot be converted to a 'int' (use 'unchecked' syntax to override)\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"(int)(uint.MaxValue - 1)\").WithArguments(\"4294967294\", \"int\"));\n }\n\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked02()\n {\n string text =\n@\"enum E : byte { A, B = 0xfe, C }\nclass C\n{\n const int F = (int)(E.C + 1); // CS0221\n const int G = (int)unchecked(1 + E.C);\n const int H = (int)checked(E.A - 1); // CS0221\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,25): error CS0031: Constant value '256' cannot be converted to a 'E'\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"E.C + 1\").WithArguments(\"256\", \"E\"),\n // (6,32): error CS0221: Constant value '-1' cannot be converted to a 'E' (use 'unchecked' syntax to override)\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"E.A - 1\").WithArguments(\"-1\", \"E\"));\n }\n\n [WorkItem(1119609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609\")]\n [Fact(Skip = \"1119609\")]\n public void CS0221ERR_ConstOutOfRangeChecked03()\n {\n var text =\n@\"public class MyClass\n{\n decimal x1 = (decimal)double.PositiveInfinity; //CS0221\n decimal x2 = (decimal)double.NegativeInfinity; //CS0221\n decimal x3 = (decimal)double.NaN; //CS0221\n decimal x4 = (decimal)double.MaxValue; //CS0221\n\n public static void Main() {}\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (3,18): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal'\n // decimal x1 = (decimal)double.PositiveInfinity; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.PositiveInfinity\").WithArguments(\"Infinity\", \"decimal\"),\n // (4,18): error CS0031: Constant value '-Infinity' cannot be converted to a 'decimal'\n // decimal x2 = (decimal)double.NegativeInfinity; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.NegativeInfinity\").WithArguments(\"-Infinity\", \"decimal\"),\n // (5,18): error CS0031: Constant value 'NaN' cannot be converted to a 'decimal'\n // decimal x3 = (decimal)double.NaN; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.NaN\").WithArguments(\"NaN\", \"decimal\"),\n // (6,18): error CS0031: Constant value '1.79769313486232E+308' cannot be converted to a 'decimal'\n // decimal x4 = (decimal)double.MaxValue; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.MaxValue\").WithArguments(\"1.79769313486232E+308\", \"decimal\"),\n // (3,13): warning CS0414: The field 'MyClass.x1' is assigned but its value is never used\n // decimal x1 = (decimal)double.PositiveInfinity; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x1\").WithArguments(\"MyClass.x1\"),\n // (4,13): warning CS0414: The field 'MyClass.x2' is assigned but its value is never used\n // decimal x2 = (decimal)double.NegativeInfinity; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x2\").WithArguments(\"MyClass.x2\"),\n // (5,13): warning CS0414: The field 'MyClass.x3' is assigned but its value is never used\n // decimal x3 = (decimal)double.NaN; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x3\").WithArguments(\"MyClass.x3\"),\n // (6,13): warning CS0414: The field 'MyClass.x4' is assigned but its value is never used\n // decimal x4 = (decimal)double.MaxValue; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x4\").WithArguments(\"MyClass.x4\"));\n }\n\n [Fact]\n public void CS0226ERR_IllegalArglist()\n {\n var text = @\"\npublic class C\n {\n public static int Main ()\n {\n __arglist(1,\"\"This is a string\"\"); // CS0226\n return 0;\n }\n }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_IllegalArglist, @\"__arglist(1,\"\"This is a string\"\")\"));\n }\n\n // [Fact()]\n // public void CS0228ERR_NoAccessibleMember()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoAccessibleMember, Line = 31, Column = 17 } }\n // );\n // }\n\n [Fact]\n public void CS0229ERR_AmbigMember()\n {\n var text = @\"\ninterface IList\n{\n int Count\n {\n get;\n set;\n }\n\n void Counter();\n}\n\ninterface Icounter\n{\n double Count\n {\n get;\n set;\n }\n}\n\ninterface IListCounter : IList , Icounter {}\n\nclass MyClass\n{\n void Test(IListCounter x)\n {\n x.Count = 1; // CS0229\n // Try one of the following lines instead:\n // ((IList)x).Count = 1;\n // or\n // ((Icounter)x).Count = 1;\n }\n\n public static void Main() {}\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigMember, Line = 28, Column = 11 } });\n }\n\n [Fact]\n public void CS0233ERR_SizeofUnsafe()\n {\n var text = @\"\nusing System;\nusing System.Runtime.InteropServices;\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct S\n{\n public int a;\n}\n\npublic class MyClass\n{\n public static void Main()\n {\n S myS = new S();\n Console.WriteLine(sizeof(S)); // CS0233\n // Try the following line instead:\n // Console.WriteLine(Marshal.SizeOf(myS));\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,27): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)\n // Console.WriteLine(sizeof(S)); // CS0233\n Diagnostic(ErrorCode.ERR_SizeofUnsafe, \"sizeof(S)\").WithArguments(\"S\"),\n\n // (15,11): warning CS0219: The variable 'myS' is assigned but its value is never used\n // S myS = new S();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"myS\").WithArguments(\"myS\"));\n }\n\n [Fact]\n public void CS0236ERR_FieldInitRefNonstatic()\n {\n var text = @\"\npublic class MyClass\n{\n int[] instanceArray;\n static int[] staticArray;\n\n static int staticField = 1;\n const int constField = 1;\n\n int a;\n int b = 1;\n int c = b; //CS0236\n int d = this.b; //CS0027\n int e = InstanceMethod(); //CS0236\n int f = this.InstanceMethod(); //CS0027\n int g = StaticMethod();\n int h = MyClass.StaticMethod();\n int i = GenericInstanceMethod(1); //CS0236\n int j = this.GenericInstanceMethod(1); //CS0027\n int k = GenericStaticMethod(1);\n int l = MyClass.GenericStaticMethod(1);\n int m = InstanceProperty; //CS0236\n int n = this.InstanceProperty; //CS0027\n int o = StaticProperty;\n int p = MyClass.StaticProperty;\n int q = instanceArray[0]; //CS0236\n int r = this.instanceArray[0]; //CS0027\n int s = staticArray[0];\n int t = MyClass.staticArray[0];\n int u = staticField;\n int v = MyClass.staticField;\n int w = constField;\n int x = MyClass.constField;\n\n MyClass()\n {\n a = b;\n }\n\n int InstanceMethod()\n {\n return a;\n }\n\n static int StaticMethod()\n {\n return 1;\n }\n\n T GenericInstanceMethod(T t)\n {\n return t;\n }\n\n static T GenericStaticMethod(T t)\n {\n return t;\n }\n\n int InstanceProperty { get { return a; } }\n\n static int StaticProperty { get { return 1; } }\n\n public static void Main()\n {\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (12,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.b'\n // int c = b; //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"b\").WithArguments(\"MyClass.b\").WithLocation(12, 13),\n // (13,13): error CS0027: Keyword 'this' is not available in the current context\n // int d = this.b; //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(13, 13),\n // (14,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceMethod()'\n // int e = InstanceMethod(); //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"InstanceMethod\").WithArguments(\"MyClass.InstanceMethod()\").WithLocation(14, 13),\n // (15,13): error CS0027: Keyword 'this' is not available in the current context\n // int f = this.InstanceMethod(); //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(15, 13),\n // (18,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.GenericInstanceMethod(int)'\n // int i = GenericInstanceMethod(1); //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"GenericInstanceMethod\").WithArguments(\"MyClass.GenericInstanceMethod(int)\").WithLocation(18, 13),\n // (19,13): error CS0027: Keyword 'this' is not available in the current context\n // int j = this.GenericInstanceMethod(1); //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(19, 13),\n // (22,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceProperty'\n // int m = InstanceProperty; //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"InstanceProperty\").WithArguments(\"MyClass.InstanceProperty\").WithLocation(22, 13),\n // (23,13): error CS0027: Keyword 'this' is not available in the current context\n // int n = this.InstanceProperty; //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(23, 13),\n // (26,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.instanceArray'\n // int q = instanceArray[0]; //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"instanceArray\").WithArguments(\"MyClass.instanceArray\").WithLocation(26, 13),\n // (27,13): error CS0027: Keyword 'this' is not available in the current context\n // int r = this.instanceArray[0]; //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(27, 13),\n // (4,11): warning CS0649: Field 'MyClass.instanceArray' is never assigned to, and will always have its default value null\n // int[] instanceArray;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"instanceArray\").WithArguments(\"MyClass.instanceArray\", \"null\").WithLocation(4, 11),\n // (5,18): warning CS0649: Field 'MyClass.staticArray' is never assigned to, and will always have its default value null\n // static int[] staticArray;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"staticArray\").WithArguments(\"MyClass.staticArray\", \"null\").WithLocation(5, 18),\n // (33,9): warning CS0414: The field 'MyClass.x' is assigned but its value is never used\n // int x = MyClass.constField;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x\").WithArguments(\"MyClass.x\").WithLocation(33, 9),\n // (32,9): warning CS0414: The field 'MyClass.w' is assigned but its value is never used\n // int w = constField;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"w\").WithArguments(\"MyClass.w\").WithLocation(32, 9)\n );\n }\n\n [Fact]\n public void CS0236ERR_FieldInitRefNonstaticMethodGroups()\n {\n var text = @\"\ndelegate void F();\npublic class MyClass\n{\n F a = Static;\n F b = MyClass.Static;\n F c = Static;\n F d = MyClass.Static;\n F e = Instance;\n F f = this.Instance;\n F g = Instance;\n F h = this.Instance;\n\n static void Static() { }\n static void Static() { }\n\n void Instance() { }\n void Instance() { }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(\n text,\n new ErrorDescription[]\n {\n new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 9, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 10, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 11, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 12, Column = 11 },\n });\n }\n\n [WorkItem(541501, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501\")]\n [Fact]\n public void CS0236ERR_FieldInitRefNonstaticProperty()\n {\n CreateCompilation(\n@\"\nenum ProtectionLevel\n{\n Privacy = 0\n}\n \nclass F\n{\n const ProtectionLevel p = ProtectionLevel.Privacy; // CS0236\n \n int ProtectionLevel { get { return 0; } }\n}\n\")\n .VerifyDiagnostics(\n // (9,29): error CS0236: A field initializer cannot reference the non-static field, method, or property 'F.ProtectionLevel'\n // const ProtectionLevel p = ProtectionLevel.Privacy; // CS0120\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"ProtectionLevel\").WithArguments(\"F.ProtectionLevel\"));\n }\n\n [WorkItem(541501, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501\")]\n [Fact]\n public void CS0236ERR_FieldInitRefNonstatic_ObjectInitializer()\n {\n CreateCompilation(\n@\"\npublic class Goo\n{\n public int i;\n public string s;\n}\n\npublic class MemberInitializerTest\n{\n private int i =10;\n private string s = \"\"abc\"\";\n private Goo f = new Goo{i = i, s = s};\n\n public static void Main()\n {\n }\n}\n\")\n .VerifyDiagnostics(\n // (12,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.i'\n // private Goo f = new Goo{i = i, s = s};\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"i\").WithArguments(\"MemberInitializerTest.i\").WithLocation(12, 33),\n // (12,40): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.s'\n // private Goo f = new Goo{i = i, s = s};\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"s\").WithArguments(\"MemberInitializerTest.s\").WithLocation(12, 40));\n }\n\n [Fact]\n public void CS0236ERR_FieldInitRefNonstatic_AnotherInitializer()\n {\n CreateCompilation(\n@\"\nclass TestClass\n{\n int P1 { get; }\n\n int y = (P1 = 123);\n int y1 { get; } = (P1 = 123);\n\n static void Main()\n {\n }\n}\n\")\n .VerifyDiagnostics(\n // (6,14): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1'\n // int y = (P1 = 123);\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"P1\").WithArguments(\"TestClass.P1\").WithLocation(6, 14),\n // (7,24): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1'\n // int y1 { get; } = (P1 = 123);\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"P1\").WithArguments(\"TestClass.P1\").WithLocation(7, 24)\n );\n }\n\n\n [Fact]\n public void CS0242ERR_VoidError()\n {\n var text = @\"\nclass TestClass\n{\n public unsafe void Test()\n {\n void* p = null;\n p++; //CS0242\n p += 2; //CS0242\n void* q = p + 1; //CS0242\n long diff = q - p; //CS0242\n var v = *p;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,9): error CS0242: The operation in question is undefined on void pointers\n // p++; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"p++\"),\n // (8,9): error CS0242: The operation in question is undefined on void pointers\n // p += 2; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"p += 2\"),\n // (9,19): error CS0242: The operation in question is undefined on void pointers\n // void* q = p + 1; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"p + 1\"),\n // (10,21): error CS0242: The operation in question is undefined on void pointers\n // long diff = q - p; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"q - p\"),\n // (11,17): error CS0242: The operation in question is undefined on void pointers\n // var v = *p;\n Diagnostic(ErrorCode.ERR_VoidError, \"*p\"));\n }\n\n [Fact]\n public void CS0244ERR_PointerInAsOrIs()\n {\n var text = @\"\nclass UnsafeTest\n{\n unsafe static void SquarePtrParam (int* p)\n {\n bool b = p is object; // CS0244 p is pointer\n }\n\n unsafe public static void Main()\n {\n int i = 5;\n SquarePtrParam (&i);\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,16): error CS0244: Neither 'is' nor 'as' is valid on pointer types\n // bool b = p is object; // CS0244 p is pointer\n Diagnostic(ErrorCode.ERR_PointerInAsOrIs, \"p is object\"));\n }\n\n [Fact]\n public void CS0245ERR_CallingFinalizeDeprecated()\n {\n var text = @\"\nclass MyClass // : IDisposable\n{\n /*\n public void Dispose()\n {\n // cleanup code goes here\n }\n */\n\n void m()\n {\n this.Finalize(); // CS0245\n // this.Dispose();\n }\n\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,7): error CS0245: Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.\n Diagnostic(ErrorCode.ERR_CallingFinalizeDeprecated, \"this.Finalize()\"));\n }\n\n [WorkItem(540722, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540722\")]\n [Fact]\n public void CS0246ERR_SingleTypeNameNotFound05()\n {\n CreateCompilation(@\"\nnamespace nms\n{\n public class Mine\n {\n private static int retval = 5;\n public static int Main()\n {\n try { }\n catch (e) { }\n return retval;\n }\n };\n}\n\")\n .VerifyDiagnostics(\n // (10,20): error CS0246: The type or namespace name 'e' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"e\").WithArguments(\"e\"));\n }\n\n [WorkItem(528446, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528446\")]\n [Fact]\n public void CS0246ERR_SingleTypeNameNotFoundNoCS8000()\n {\n CreateCompilation(@\"\nclass Test\n{\n void Main()\n {\n var sum = new j();\n }\n}\n\")\n .VerifyDiagnostics(\n // (11,20): error CS0246: The type or namespace name 'j' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"j\").WithArguments(\"j\"));\n }\n\n [Fact]\n public void CS0247ERR_NegativeStackAllocSize()\n {\n var text = @\"\npublic class MyClass\n{\n unsafe public static void Main()\n {\n int *p = stackalloc int [-30]; // CS0247\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,32): error CS0247: Cannot use a negative size with stackalloc\n // int *p = stackalloc int [-30]; // CS0247\n Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, \"-30\"));\n }\n\n [Fact]\n public void CS0248ERR_NegativeArraySize()\n {\n var text = @\"\nclass MyClass\n{\n public static void Main()\n {\n int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number\n int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes\n int[] myArray3 = new int[3000000000u]; // slightly different code path for uint array sizes\n var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}};\n var myArray5 = new object[-1L] {null};\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,33): error CS0248: Cannot create an array with a negative size\n // int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-3\").WithLocation(6, 33),\n // (7,34): error CS0248: Cannot create an array with a negative size\n // int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-5000000000\").WithLocation(7, 34),\n // (9,35): error CS0248: Cannot create an array with a negative size\n // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}};\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-2\").WithLocation(9, 35),\n // (9,42): error CS0248: Cannot create an array with a negative size\n // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}};\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-1\").WithLocation(9, 42),\n // (10,35): error CS0248: Cannot create an array with a negative size\n // var myArray5 = new object[-1L] {null};\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-1L\").WithLocation(10, 35),\n // (10,35): error CS0150: A constant value is expected\n // var myArray5 = new object[-1L] {null};\n Diagnostic(ErrorCode.ERR_ConstantExpected, \"-1L\").WithLocation(10, 35));\n }\n\n [WorkItem(528912, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528912\")]\n [Fact]\n public void CS0250ERR_CallingBaseFinalizeDeprecated()\n {\n var text = @\"\nclass B\n{\n}\n\nclass C : B\n{\n ~C()\n {\n base.Finalize(); // CS0250\n }\n\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor.\n Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, \"base.Finalize()\"));\n }\n\n [Fact]\n public void CS0254ERR_BadCastInFixed()\n {\n var text = @\"\nclass Point\n{\n public uint x, y;\n}\n\nclass FixedTest\n{\n unsafe static void SquarePtrParam (int* p)\n {\n *p *= *p;\n }\n\n unsafe public static void Main()\n {\n Point pt = new Point();\n pt.x = 5;\n pt.y = 6;\n\n fixed (int* p = (int*)&pt.x) // CS0254\n // try the following line instead\n // fixed (uint* p = &pt.x)\n {\n SquarePtrParam ((int*)p);\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (20,23): error CS9385: The given expression cannot be used in a fixed statement\n // fixed (int* p = (int*)&pt.x) // CS0254\n Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, \"(int*)&pt.x\").WithLocation(20, 23));\n }\n\n [Fact]\n public void CS0255ERR_StackallocInFinally()\n {\n var text = @\"\nunsafe class Test\n{\n void M()\n {\n try\n {\n // Something \n }\n finally\n {\n int* fib = stackalloc int[100];\n }\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (12,24): error CS0255: stackalloc may not be used in a catch or finally block\n // int* fib = stackalloc int[100];\n Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, \"stackalloc int[100]\").WithLocation(12, 24));\n }\n\n [Fact]\n public void CS0255ERR_StackallocInCatch()\n {\n var text = @\"\nunsafe class Test\n{\n void M()\n {\n try\n {\n // Something \n }\n catch\n {\n int* fib = stackalloc int[100];\n }\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (12,24): error CS0255: stackalloc may not be used in a catch or finally block\n // int* fib = stackalloc int[100];\n Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, \"stackalloc int[100]\").WithLocation(12, 24));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast01()\n {\n var text = @\"\nclass MyClass\n{\n public static void Main()\n {\n object obj = \"\"MyString\"\";\n // Cannot implicitly convert 'object' to 'MyClass'\n MyClass myClass = obj; // CS0266\n // Try this line instead\n // MyClass c = ( MyClass )obj;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConvCast, Line = 8, Column = 27 } });\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast02()\n {\n var source =\n@\"class C\n{\n const int f = 0L;\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,19): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // const int f = 0L;\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"0L\").WithArguments(\"long\", \"int\").WithLocation(3, 19));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast03()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n const short s = 1L;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,25): error CS0266: Cannot implicitly convert type 'long' to 'short'. An explicit conversion exists (are you missing a cast?)\n // const short s = 1L;\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1L\").WithArguments(\"long\", \"short\").WithLocation(5, 25),\n // (5,21): warning CS0219: The variable 's' is assigned but its value is never used\n // const short s = 1L;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"s\").WithArguments(\"s\").WithLocation(5, 21));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast04()\n {\n var source =\n@\"enum E { A = 1 }\nclass C\n{\n E f = 2; // CS0266\n E g = E.A;\n void M()\n {\n f = E.A;\n g = 'c'; // CS0266\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,11): error CS0266: Cannot implicitly convert type 'int' to 'E'. An explicit conversion exists (are you missing a cast?)\n // E f = 2; // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"2\").WithArguments(\"int\", \"E\").WithLocation(4, 11),\n // (9,13): error CS0266: Cannot implicitly convert type 'char' to 'E'. An explicit conversion exists (are you missing a cast?)\n // g = 'c'; // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"'c'\").WithArguments(\"char\", \"E\").WithLocation(9, 13),\n // (4,7): warning CS0414: The field 'C.f' is assigned but its value is never used\n // E f = 2; // CS0266\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"f\").WithArguments(\"C.f\").WithLocation(4, 7),\n // (5,7): warning CS0414: The field 'C.g' is assigned but its value is never used\n // E g = E.A;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"g\").WithArguments(\"C.g\").WithLocation(5, 7));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast05()\n {\n var source =\n@\"enum E : byte\n{\n A = 'a', // CS0266\n B = 0xff,\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,9): error CS0266: Cannot implicitly convert type 'char' to 'byte'. An explicit conversion exists (are you missing a cast?)\n // A = 'a', // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"'a'\").WithArguments(\"char\", \"byte\").WithLocation(3, 9));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast06()\n {\n var source =\n@\"enum E\n{\n A = 1,\n B = 1L // CS0266\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // B = 1L // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1L\").WithArguments(\"long\", \"int\").WithLocation(4, 9));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast07()\n {\n // No errors\n var source = \"enum E { A, B = A }\";\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast08()\n {\n // No errors\n var source =\n@\"enum E { A = 1, B }\nenum F { X = E.A + 1, Y }\n\";\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast09()\n {\n var source =\n@\"enum E\n{\n A = F.A,\n B = F.B,\n C = G.A,\n D = G.B,\n}\nenum F : short { A = 1, B }\nenum G : long { A = 1, B }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // C = G.A,\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"G.A\").WithArguments(\"long\", \"int\").WithLocation(5, 9),\n // (6,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // D = G.B,\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"G.B\").WithArguments(\"long\", \"int\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast10()\n {\n var source =\n@\"class C\n{\n public const int F = D.G + 1;\n}\nclass D\n{\n public const int G = E.H + 1;\n}\nclass E\n{\n public const int H = 1L;\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (11,26): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // public const int H = 1L;\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1L\").WithArguments(\"long\", \"int\").WithLocation(11, 26));\n }\n\n [Fact()]\n public void CS0266ERR_NoImplicitConvCast11()\n {\n string text = @\"class Program\n{\n static void Main(string[] args)\n {\n bool? b = true;\n int result = b ? 0 : 1; // Compiler error\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"b\").WithArguments(\"bool?\", \"bool\"));\n }\n\n [WorkItem(541718, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718\")]\n [Fact]\n public void CS0266ERR_NoImplicitConvCast12()\n {\n string text = @\"\nclass C1\n{\n public static void Main()\n {\n var cube = new int[Number.One][];\n }\n}\nenum Number\n{\n One,\n Two\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,28): error CS0266: Cannot implicitly convert type 'Number' to 'int'. An explicit conversion exists (are you missing a cast?)\n // var cube = new int[Number.One][];\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"Number.One\").WithArguments(\"Number\", \"int\").WithLocation(6, 28));\n }\n\n [WorkItem(541718, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718\")]\n [Fact]\n public void CS0266ERR_NoImplicitConvCast13()\n {\n string text = @\"\nclass C1\n{\n public static void Main()\n {\n double x = 5;\n int[] arr4 = new int[x];// Invalid\n\n float y = 5;\n int[] arr5 = new int[y];// Invalid\n\n decimal z = 5;\n int[] arr6 = new int[z];// Invalid\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (7,30): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[] arr4 = new int[x];// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"x\").WithArguments(\"double\", \"int\").WithLocation(7, 30),\n // (10,30): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[] arr5 = new int[y];// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"y\").WithArguments(\"float\", \"int\").WithLocation(10, 30),\n // (13,30): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[] arr6 = new int[z];// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"z\").WithArguments(\"decimal\", \"int\").WithLocation(13, 30));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast14()\n {\n string source = @\"\nclass C\n{\n public unsafe void M(int* p, object o)\n {\n _ = p[o]; // error with span on 'o'\n _ = p[0]; // ok\n }\n}\n\";\n CreateCompilation(source, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(\n // (6,15): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)\n // _ = p[o]; // error with span on 'o'\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"o\").WithArguments(\"object\", \"int\").WithLocation(6, 15));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast15()\n {\n string source = @\"\nclass C\n{\n public void M(object o)\n {\n int[o] x;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)\n // int[o];\n Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, \"[o]\").WithLocation(6, 12),\n // (6,13): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[o];\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"o\").WithArguments(\"object\", \"int\").WithLocation(6, 13),\n // (6,16): warning CS0168: The variable 'x' is declared but never used\n // int[o] x;\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"x\").WithArguments(\"x\").WithLocation(6, 16));\n }\n\n [Fact]\n public void CS0269ERR_UseDefViolationOut()\n {\n var text = @\"\nclass C\n{\n public static void F(out int i)\n {\n try\n {\n // Assignment occurs, but compiler can't verify it\n i = 1;\n }\n catch\n {\n }\n\n int k = i; // CS0269\n i = 1;\n }\n\n public static void Main()\n {\n int myInt;\n F(out myInt);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationOut, Line = 15, Column = 17 } });\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter01()\n {\n var source =\n@\"class C\n{\n internal static object P { private get; set; }\n public C Q { protected get { return null; } set { } }\n}\nclass P\n{\n static void M(C c)\n {\n object o = C.P;\n M(c.Q);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,20): error CS0271: The property or indexer 'C.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"C.P\").WithArguments(\"C.P\").WithLocation(10, 20),\n // (11,11): error CS0271: The property or indexer 'C.Q' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"c.Q\").WithArguments(\"C.Q\").WithLocation(11, 11));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter02()\n {\n var source =\n@\"class A\n{\n public virtual object P { protected get; set; }\n}\nclass B : A\n{\n public override object P { set { } }\n void M()\n {\n object o = P; // no error\n }\n}\nclass C\n{\n void M(B b)\n {\n object o = b.P; // CS0271\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,20): error CS0271: The property or indexer 'B.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"b.P\").WithArguments(\"B.P\").WithLocation(17, 20));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter03()\n {\n var source =\n@\"namespace N1\n{\n class A\n {\n void M(N2.B b)\n {\n object o = b.P;\n }\n }\n}\nnamespace N2\n{\n class B : N1.A\n {\n public object P { protected get; set; }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,24): error CS0271: The property or indexer 'N2.B.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"b.P\").WithArguments(\"N2.B.P\").WithLocation(7, 24));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter04()\n {\n var source =\n@\"class A\n{\n static public object P { protected get; set; }\n static internal object Q { private get; set; }\n static void M()\n {\n object o = B.Q; // no error\n o = A.Q; // no error\n }\n}\nclass B : A\n{\n static void M()\n {\n object o = B.P; // no error\n o = P; // no error\n o = Q; // CS0271\n }\n}\nclass C\n{\n static void M()\n {\n object o = B.P; // CS0271\n o = A.Q; // CS0271\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"Q\").WithArguments(\"A.Q\").WithLocation(17, 13),\n // (24,20): error CS0271: The property or indexer 'A.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"B.P\").WithArguments(\"A.P\").WithLocation(24, 20),\n // (25,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"A.Q\").WithArguments(\"A.Q\").WithLocation(25, 13));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter05()\n {\n CreateCompilation(\n@\"class A\n{\n public object this[int x] { protected get { return null; } set { } }\n internal object this[string s] { private get { return null; } set { } }\n void M()\n {\n object o = new B()[\"\"hello\"\"]; // no error\n o = new A()[\"\"hello\"\"]; // no error\n }\n}\nclass B : A\n{\n void M()\n {\n object o = new B()[0]; // no error\n o = this[0]; // no error\n o = this[\"\"hello\"\"]; // CS0271\n }\n}\nclass C\n{\n void M()\n {\n object o = new B()[0]; // CS0271\n o = new A()[\"\"hello\"\"]; // CS0271\n }\n}\")\n .VerifyDiagnostics(\n // (17,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, @\"this[\"\"hello\"\"]\").WithArguments(\"A.this[string]\"),\n // (24,20): error CS0271: The property or indexer 'A.this[int]' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"new B()[0]\").WithArguments(\"A.this[int]\"),\n // (25,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, @\"new A()[\"\"hello\"\"]\").WithArguments(\"A.this[string]\"));\n }\n\n [Fact]\n public void CS0272ERR_InaccessibleSetter01()\n {\n var source =\n@\"namespace N\n{\n class C\n {\n internal object P { get; private set; }\n static public C Q { get { return null; } protected set { } }\n }\n class P\n {\n static void M(C c)\n {\n c.P = c;\n C.Q = c;\n }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (12,13): error CS0272: The property or indexer 'N.C.P' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"c.P\").WithArguments(\"N.C.P\").WithLocation(12, 13),\n // (13,13): error CS0272: The property or indexer 'N.C.Q' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"C.Q\").WithArguments(\"N.C.Q\").WithLocation(13, 13));\n }\n\n [Fact]\n public void CS0272ERR_InaccessibleSetter02()\n {\n var source =\n@\"namespace N1\n{\n abstract class A\n {\n public virtual object P { get; protected set; }\n }\n}\nnamespace N2\n{\n class B : N1.A\n {\n public override object P { get { return null; } }\n void M()\n {\n P = null; // no error\n }\n }\n}\nclass C\n{\n void M(N2.B b)\n {\n b.P = null; // CS0272\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (23,9): error CS0272: The property or indexer 'N2.B.P' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"b.P\").WithArguments(\"N2.B.P\").WithLocation(23, 9));\n }\n\n [Fact]\n public void CS0272ERR_InaccessibleSetter03()\n {\n CreateCompilation(\n@\"namespace N1\n{\n abstract class A\n {\n public virtual object this[int x] { get { return null; } protected set { } }\n }\n}\nnamespace N2\n{\n class B : N1.A\n {\n public override object this[int x] { get { return null; } }\n void M()\n {\n this[0] = null; // no error\n }\n }\n}\nclass C\n{\n void M(N2.B b)\n {\n b[0] = null; // CS0272\n }\n}\n\")\n .VerifyDiagnostics(\n // (23,9): error CS0272: The property or indexer 'N2.B.this[int]' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"b[0]\").WithArguments(\"N2.B.this[int]\"));\n }\n\n [Fact]\n public void CS0283ERR_BadConstType()\n {\n // Test for both ERR_BadConstType and an error for RHS to ensure\n // the RHS is not reported multiple times (when calculating the\n // constant value for the symbol and also when binding).\n var source =\n@\"struct S\n{\n static void M(object o)\n {\n const S s = 2;\n M(s);\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,15): error CS0283: The type 'S' cannot be declared const\n // const S s = 2;\n Diagnostic(ErrorCode.ERR_BadConstType, \"S\").WithArguments(\"S\").WithLocation(5, 15),\n // (5,21): error CS0029: Cannot implicitly convert type 'int' to 'S'\n // const S s = 2;\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"2\").WithArguments(\"int\", \"S\").WithLocation(5, 21));\n }\n\n [Fact]\n public void CS0304ERR_NoNewTyvar01()\n {\n var source =\n@\"struct S where U : new()\n{\n void M()\n {\n object o;\n o = new T();\n o = new U();\n o = new V();\n }\n}\nclass C\n where T : struct\n where U : class\n{\n void M()\n where V : struct\n where W : class, new()\n {\n object o;\n o = new T();\n o = new U();\n o = new V();\n o = new W();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,13): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new T()\").WithArguments(\"T\").WithLocation(6, 13),\n // (8, 13): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new V()\").WithArguments(\"V\").WithLocation(8, 13),\n // (21,13): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new U()\").WithArguments(\"U\").WithLocation(21, 13));\n }\n\n [WorkItem(542377, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542377\")]\n [Fact]\n public void CS0304ERR_NoNewTyvar02()\n {\n var source =\n@\"struct S { }\nclass C { }\nabstract class A\n{\n public abstract U F() where U : T;\n}\nclass B1 : A\n{\n public override U F() { return new U(); }\n}\nclass B2 : A\n{\n public override U F() { return new U(); }\n}\nclass B3 : A\n{\n public override U F() { return new U(); }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,39): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new U()\").WithArguments(\"U\").WithLocation(17, 39));\n }\n\n [WorkItem(542547, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542547\")]\n [Fact]\n public void CS0305ERR_BadArity()\n {\n var text = @\"\npublic class NormalType\n{\n public static int M1(T1 p1, T1 p2) { return 0; }\n public static int Main()\n {\n M1(10, 11);\n return -1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,17): error CS1031: Type expected\n Diagnostic(ErrorCode.ERR_TypeExpected, \">\"),\n // (7,9): error CS0305: Using the generic method 'NormalType.M1(T1, T1)' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"M1\").WithArguments(\"NormalType.M1(T1, T1)\", \"method\", \"1\"));\n }\n\n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied01()\n {\n var text =\n@\"class A { }\nclass B\n{\n private B() { }\n}\ndelegate void D();\nenum E { }\nstruct S { }\nclass C where T : new()\n{\n static void M() where V : new()\n {\n M>();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n }\n static void M()\n where V : new()\n where W : new()\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"B\").WithLocation(14, 9),\n // (15,9): error CS0310: 'D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"D\").WithLocation(15, 9),\n // (21,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"U\").WithLocation(21, 9),\n // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"B\").WithLocation(22, 9),\n // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"W\", \"B\").WithLocation(22, 9),\n // (23,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"W\", \"U\").WithLocation(23, 9),\n // (25,9): error CS0310: 'T[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"T[]\").WithLocation(25, 9));\n }\n\n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied02()\n {\n var text =\n@\"class A { }\nclass B\n{\n internal B() { }\n}\nclass C where T : new()\n{\n internal static void M() where U : new() { }\n internal static void E(D d) { } // Error: missing constraint on E to satisfy constraint on D\n}\ndelegate T D() where T : new();\nstatic class E\n{\n internal static void M(this object o) where T : new() { }\n internal static void F(D d) where T : new() { }\n}\nclass F where U : new()\n{\n}\nabstract class G { }\nclass H : G { }\ninterface I { }\nstruct S\n{\n private S(object o) { }\n static void M()\n {\n C.M();\n C.M();\n C.M();\n C.M();\n C.M();\n C.M();\n C.M();\n E.F(S.F);\n E.F(S.F);\n E.F(S.F>);\n E.F(S.F>);\n var o = new object();\n o.M();\n o.M();\n o = new F();\n o = new F();\n }\n static T F() { return default(T); }\n}\";\n\n // Note that none of these errors except the first one are reported by the native compiler, because\n // it does not report additional errors after an error is found in a formal parameter of a method.\n\n CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (9,36): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D'\n // internal static void E(D d) { } // Error: missing constraint on E to satisfy constraint on D\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"d\").WithArguments(\"D\", \"T\", \"U\").WithLocation(9, 36),\n // (29,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"U\", \"B\").WithLocation(29, 14),\n // (30,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"C\", \"T\", \"B\").WithLocation(30, 11),\n // (31,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"C\", \"T\", \"B\").WithLocation(31, 11),\n // (31,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"U\", \"B\").WithLocation(31, 14),\n // (32,11): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"G\").WithArguments(\"C\", \"T\", \"G\").WithLocation(32, 11),\n // (33,14): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"U\", \"G\").WithLocation(33, 14),\n // (34,11): error CS0310: 'I' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"I\").WithArguments(\"C\", \"T\", \"I\").WithLocation(34, 11),\n // (36,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.F(D)'\n // E.F(S.F);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"F\").WithArguments(\"E.F(D)\", \"T\", \"B\").WithLocation(36, 11),\n // (38,19): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // E.F(S.F>);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"C\", \"T\", \"B\").WithLocation(38, 19),\n\n // This invocation of E.F(S.F>) is an extremely interesting one. \n\n // First off, obviously the type argument for S.F is prima facie wrong, so we give an error for that above.\n // But what about the overload resolution problem in error recovery? Even though the argument is bad we still\n // might want to try to get an overload resolution result. Thus we must infer a type for T in E.F(D). \n // We must do overload resolution on an invocation S.F>(). Overload resolution succeeds; it has no reason\n // to fail. (Overload resolution would fail if a formal parameter type of S.F>() did not satisfy one of its\n // constraints, but there are no formal parameters. Also, there are no constraints at all on T in S.F.)\n //\n // Thus T in D is inferred to be C, and thus T in E.F is inferred to be C. \n //\n // Now we check to see whether E.F>(D>) is applicable. It is inapplicable because\n // B fails to meet the constraints of T in C. (C does not fail to meet the constraints\n // of T in D because C has a public default parameterless ctor.)\n //\n // Therefore E.F(S.F>) fails overload resolution. Why? Because B is not valid for T in C.\n // (We cannot say that the constraints on T in E.F is unmet because again, C meets the\n // constraint; it has a ctor.) So that is the error we report.\n //\n // This is arguably a \"cascading\" error; we have already reported an error for C when the \n // argument was bound. Normally we avoid reporting \"cascading\" errors in overload resolution by\n // saying that an erroneous argument is implicitly convertible to any formal parameter type;\n // thus we avoid an erroneous expression from causing overload resolution to make every\n // candidate method inapplicable. (Though it might cause overload resolution to fail by making\n // every candidate method applicable, causing an ambiguity!) But the overload resolution \n // error here is not caused by an argument *conversion* in the first place; the overload\n // resolution error is caused because *the deduced formal parameter type is illegal.*\n //\n // We might want to put some gear in place to suppress this cascading error. It is not\n // entirely clear what that machinery might look like.\n\n // (38,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // E.F(S.F>);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"F\").WithArguments(\"C\", \"T\", \"B\").WithLocation(38, 11),\n\n // (41,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.M(object)'\n // o.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"E.M(object)\", \"T\", \"B\").WithLocation(41, 11),\n // (42,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'F'\n // o = new F();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"F\", \"U\", \"B\").WithLocation(42, 22));\n }\n\n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied03()\n {\n var text =\n@\"class A { }\nclass B\n{\n private B() { }\n}\nclass C where U : struct\n{\n internal static void M(V v) where V : new() { }\n void M()\n {\n A a = default(A);\n M(a);\n a.E();\n B b = default(B);\n M(b);\n b.E();\n T t = default(T);\n M(t);\n t.E();\n U u1 = default(U);\n M(u1);\n u1.E();\n U? u2 = null;\n M(u2);\n u2.E();\n }\n}\nstatic class S\n{\n internal static void E(this T t) where T : new() { }\n}\";\n CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (15,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M(V)'\n // M(b);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M(V)\", \"V\", \"B\").WithLocation(15, 9),\n // (16,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E(T)'\n // b.E();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"E\").WithArguments(\"S.E(T)\", \"T\", \"B\").WithLocation(16, 11),\n // (18,9): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M(V)'\n // M(t);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M(V)\", \"V\", \"T\").WithLocation(18, 9),\n // (19,11): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E(T)'\n // t.E();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"E\").WithArguments(\"S.E(T)\", \"T\", \"T\").WithLocation(19, 11)\n);\n }\n\n /// \n /// Constraint errors within aliases.\n /// \n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied04()\n {\n var text =\n@\"using NA = N.A;\nusing NB = N.B;\nusing CA = N.C;\nusing CB = N.C;\nnamespace N\n{\n using CAD = C.D;\n using CBD = C.D;\n class A { } // public (default) .ctor\n class B { private B() { } } // private .ctor\n class C where T : new()\n {\n internal static void M() where U : new() { }\n internal class D\n {\n private D() { } // private .ctor\n internal static void M() where U : new() { }\n }\n }\n class E\n {\n static void M()\n {\n C.M();\n C.M();\n C.D>.M();\n C.D.M();\n C.D.M();\n CA.M();\n CB.M();\n CAD.M();\n CBD.M();\n C.M();\n C.M();\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,7): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // using CB = N.C;\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CB\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(4, 7),\n // (8,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // using CBD = C.D;\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CBD\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(8, 11),\n // (24,20): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.M()\", \"U\", \"N.B\").WithLocation(24, 20),\n // (25,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"NB\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(25, 15),\n // (26,15): error CS0310: 'C.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.D>.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"C.D\").WithArguments(\"N.C\", \"T\", \"N.C.D\").WithLocation(26, 15),\n // (27,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.D.M()'\n // C.D.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.D.M()\", \"U\", \"N.B\").WithLocation(27, 22),\n // (28,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.D.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"N.B\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(28, 15),\n // (29,16): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // CA.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.M()\", \"U\", \"N.B\").WithLocation(29, 16),\n // (31,17): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.D.M()'\n // CAD.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.D.M()\", \"U\", \"N.B\").WithLocation(31, 17),\n // (33,15): error CS0310: 'C.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CAD\").WithArguments(\"N.C\", \"T\", \"N.C.D\").WithLocation(33, 15),\n // (34,15): error CS0310: 'C.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CBD\").WithArguments(\"N.C\", \"T\", \"N.C.D\").WithLocation(34, 15));\n }\n\n /// \n /// Constructors with optional and params args\n /// should not be considered parameterless.\n /// \n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied05()\n {\n var text =\n@\"class A\n{\n public A() { }\n}\nclass B\n{\n public B(object o = null) { }\n}\nclass C\n{\n public C(params object[] args) { }\n}\nclass D where T : new()\n{\n static void M()\n {\n D.M();\n D.M();\n D.M();\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"D\", \"T\", \"B\").WithLocation(18, 11),\n // (19,11): error CS0310: 'C' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"C\").WithArguments(\"D\", \"T\", \"C\").WithLocation(19, 11));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType01()\n {\n var source =\n@\"class A { }\nclass B { }\nclass C where T : A { }\nclass D\n{\n static void M() where T : A { }\n static void M()\n {\n object o = new C();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,26): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C'. There is no implicit reference conversion from 'B' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"B\").WithArguments(\"C\", \"A\", \"T\", \"B\").WithLocation(9, 26),\n // (10,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'D.M()'. There is no implicit reference conversion from 'B' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"M\").WithArguments(\"D.M()\", \"A\", \"T\", \"B\").WithLocation(10, 9));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType02()\n {\n var source =\n@\"class C where U : T\n{\n void M() where V : C { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,12): error CS0311: The type 'V' cannot be used as type parameter 'U' in the generic type or method 'C'. There is no implicit reference conversion from 'V' to 'T'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"V\").WithArguments(\"C\", \"T\", \"U\", \"V\").WithLocation(3, 12));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType03()\n {\n var source =\n@\"interface I where T : I> { }\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,13): error CS0311: The type 'I' cannot be used as type parameter 'T' in the generic type or method 'I'. There is no implicit reference conversion from 'I' to 'I>>'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"T\").WithArguments(\"I\", \"I>>\", \"T\", \"I\").WithLocation(1, 13));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType04()\n {\n var source =\n@\"interface IA { }\ninterface IB where T : IA { }\nclass C\n where T1 : IB\n where T2 : IB\n where T3 : IB[]>, IA\n{\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,9): error CS0311: The type 'object[]' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no implicit reference conversion from 'object[]' to 'IA'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"T1\").WithArguments(\"IB\", \"IA\", \"T\", \"object[]\").WithLocation(3, 9),\n // (3,13): error CS0311: The type 'T2' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no boxing conversion or type parameter conversion from 'T2' to 'IA'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T2\").WithArguments(\"IB\", \"IA\", \"T\", \"T2\").WithLocation(3, 13),\n // (3,17): error CS0311: The type 'IB[]' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no implicit reference conversion from 'IB[]' to 'IA[]>'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"T3\").WithArguments(\"IB\", \"IA[]>\", \"T\", \"IB[]\").WithLocation(3, 17));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType05()\n {\n var source =\n@\"namespace N\n{\n class C where U : T\n {\n static object F()\n {\n return null;\n }\n static object G() where V : T\n {\n return null;\n }\n static void M()\n {\n object o;\n o = C.F();\n o = N.C.G();\n }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,24): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'C'. There is no implicit reference conversion from 'object' to 'int'.\n // o = C.F();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"object\").WithArguments(\"N.C\", \"int\", \"U\", \"object\").WithLocation(16, 24),\n // (17,31): error CS0311: The type 'string' cannot be used as type parameter 'V' in the generic type or method 'C.G()'. There is no implicit reference conversion from 'string' to 'int'.\n // o = N.C.G();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"G\").WithArguments(\"N.C.G()\", \"int\", \"V\", \"string\").WithLocation(17, 31));\n }\n\n [Fact]\n public void CS0312ERR_GenericConstraintNotSatisfiedNullableEnum()\n {\n var source =\n@\"class A where T : U { }\nclass B\n{\n static void M() where U : T { }\n static void M()\n {\n object o = new A();\n B.M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,26): error CS0312: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A'. The nullable type 'int?' does not satisfy the constraint of 'int'.\n // object o = new A();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, \"int?\").WithArguments(\"A\", \"int\", \"T\", \"int?\").WithLocation(7, 26),\n // (8,16): error CS0312: The type 'int?' cannot be used as type parameter 'U' in the generic type or method 'B.M()'. The nullable type 'int?' does not satisfy the constraint of 'int'.\n // B.M();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, \"M\").WithArguments(\"B.M()\", \"int\", \"U\", \"int?\").WithLocation(8, 16));\n }\n\n [Fact]\n public void CS0313ERR_GenericConstraintNotSatisfiedNullableInterface()\n {\n var source =\n@\"interface I { }\nstruct S : I { }\nclass A where T : I { }\nclass B\n{\n static void M() where T : I { }\n static void M()\n {\n object o = new A();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,26): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'A'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, \"S?\").WithArguments(\"A\", \"I\", \"T\", \"S?\").WithLocation(9, 26),\n // (10,9): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'B.M()'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, \"M\").WithArguments(\"B.M()\", \"I\", \"T\", \"S?\").WithLocation(10, 9));\n }\n\n [Fact]\n public void CS0314ERR_GenericConstraintNotSatisfiedTyVar01()\n {\n var source =\n@\"class A { }\nclass B where T : A { }\nclass C where T : struct\n{\n static void M() where U : A { }\n static void M()\n {\n object o = new B();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,26): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B'. There is no boxing conversion or type parameter conversion from 'T' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T\").WithArguments(\"B\", \"A\", \"T\", \"T\").WithLocation(8, 26),\n // (9,9): error CS0314: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'C.M()'. There is no boxing conversion or type parameter conversion from 'T' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"M\").WithArguments(\"C.M()\", \"A\", \"U\", \"T\").WithLocation(9, 9));\n }\n\n [Fact]\n public void CS0314ERR_GenericConstraintNotSatisfiedTyVar02()\n {\n var source =\n@\"class C where U : T\n{\n void M() where V : C { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,12): error CS0314: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'C'. There is no boxing conversion or type parameter conversion from 'U' to 'V'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"V\").WithArguments(\"C\", \"V\", \"U\", \"U\").WithLocation(3, 12));\n }\n\n [Fact]\n public void CS0314ERR_GenericConstraintNotSatisfiedTyVar03()\n {\n var source =\n@\"interface IA where T : IB { }\ninterface IB where T : IA { }\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no boxing conversion or type parameter conversion from 'T' to 'IA'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T\").WithArguments(\"IB\", \"IA\", \"T\", \"T\").WithLocation(1, 14),\n // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IA'. There is no boxing conversion or type parameter conversion from 'T' to 'IB'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T\").WithArguments(\"IA\", \"IB\", \"T\", \"T\").WithLocation(2, 14));\n }\n\n [Fact]\n public void CS0315ERR_GenericConstraintNotSatisfiedValType()\n {\n var source =\n@\"class A { }\nclass B where T : A { }\nstruct S { }\nclass C\n{\n static void M() where U : A { }\n static void M()\n {\n object o = new B();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,26): error CS0315: The type 'S' cannot be used as type parameter 'T' in the generic type or method 'B'. There is no boxing conversion from 'S' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, \"S\").WithArguments(\"B\", \"A\", \"T\", \"S\").WithLocation(9, 26),\n // (10,9): error CS0315: The type 'double?' cannot be used as type parameter 'U' in the generic type or method 'C.M()'. There is no boxing conversion from 'double?' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, \"M\").WithArguments(\"C.M()\", \"A\", \"U\", \"double\").WithLocation(10, 9));\n }\n\n [Fact]\n public void CS0316ERR_DuplicateGeneratedName()\n {\n var text = @\"\npublic class Test\n{\n public int this[int value] // CS0316\n {\n get { return 1; }\n set { }\n }\n\n public int this[char @value] // CS0316\n {\n get { return 1; }\n set { }\n }\n\n public int this[string value] // no error since no setter\n {\n get { return 1; }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,26): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name\n // public int this[char @value] // CS0316\n Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, \"@value\").WithArguments(\"value\").WithLocation(10, 26),\n // (4,25): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name\n // public int this[int value] // CS0316\n Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, \"value\").WithArguments(\"value\").WithLocation(4, 25));\n }\n\n [Fact]\n public void CS0403ERR_TypeVarCantBeNull()\n {\n var source =\n@\"interface I { }\nclass A { }\nclass B\n where T2 : class\n where T3 : struct\n where T4 : new()\n where T5 : I\n where T6 : A\n where T7 : T1\n{\n static void M()\n {\n T1 t1 = null;\n T2 t2 = null;\n T3 t3 = null;\n T4 t4 = null;\n T5 t5 = null;\n T6 t6 = null;\n T7 t7 = null;\n }\n static T1 F1() { return null; }\n static T2 F2() { return null; }\n static T3 F3() { return null; }\n static T4 F4() { return null; }\n static T5 F5() { return null; }\n static T6 F6() { return null; }\n static T7 F7() { return null; }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,17): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead.\n // T1 t1 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T1\"),\n // (15,17): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead.\n // T3 t3 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T3\"),\n // (16,17): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead.\n // T4 t4 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T4\"),\n // (17,17): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead.\n // T5 t5 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T5\"),\n // (19,17): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead.\n // T7 t7 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T7\"),\n // (14,12): warning CS0219: The variable 't2' is assigned but its value is never used\n // T2 t2 = null;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"t2\").WithArguments(\"t2\"),\n // (18,12): warning CS0219: The variable 't6' is assigned but its value is never used\n // T6 t6 = null;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"t6\").WithArguments(\"t6\"),\n // (21,29): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead.\n // static T1 F1() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T1\"),\n // (23,29): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead.\n // static T3 F3() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T3\"),\n // (24,29): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead.\n // static T4 F4() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T4\"),\n // (25,29): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead.\n // static T5 F5() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T5\"),\n // (27,29): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead.\n // static T7 F7() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T7\")\n );\n }\n\n [WorkItem(539901, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539901\")]\n [Fact]\n public void CS0407ERR_BadRetType_01()\n {\n var text = @\"\npublic delegate int MyDelegate();\n\nclass C\n{\n MyDelegate d;\n\n public C()\n {\n d = new MyDelegate(F); // OK: F returns int\n d = new MyDelegate(G); // CS0407 - G doesn't return int\n }\n\n public int F()\n {\n return 1;\n }\n\n public void G()\n {\n }\n\n public static void Main()\n {\n C c1 = new C();\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(\n // (11,28): error CS0407: 'void C.G()' has the wrong return type\n // d = new MyDelegate(G); // CS0407 - G doesn't return int\n Diagnostic(ErrorCode.ERR_BadRetType, \"G\").WithArguments(\"C.G()\", \"void\").WithLocation(11, 28)\n );\n CreateCompilation(text).VerifyDiagnostics(\n // (11,28): error CS0407: 'void C.G()' has the wrong return type\n // d = new MyDelegate(G); // CS0407 - G doesn't return int\n Diagnostic(ErrorCode.ERR_BadRetType, \"G\").WithArguments(\"C.G()\", \"void\").WithLocation(11, 28)\n );\n }\n\n [WorkItem(925899, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925899\")]\n [Fact]\n public void CS0407ERR_BadRetType_02()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n public static void Main()\n {\n var oo = new Func(x => 1);\n \n var os = new Func(oo);\n var ss = new Func(oo);\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(\n // (10,43): error CS0407: 'object System.Func.Invoke(object)' has the wrong return type\n // var os = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(10, 43),\n // (11,43): error CS0407: 'object System.Func.Invoke(object)' has the wrong return type\n // var ss = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(11, 43)\n );\n CreateCompilation(text).VerifyDiagnostics(\n // (10,43): error CS0407: 'object Func.Invoke(object)' has the wrong return type\n // var os = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(10, 43),\n // (11,43): error CS0407: 'object Func.Invoke(object)' has the wrong return type\n // var ss = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(11, 43)\n );\n }\n\n [WorkItem(539924, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539924\")]\n [Fact]\n public void CS0407ERR_BadRetType_03()\n {\n var text = @\"\ndelegate DerivedClass MyDerivedDelegate(DerivedClass x);\npublic class BaseClass\n{\n public static BaseClass DelegatedMethod(BaseClass x)\n {\n System.Console.WriteLine(\"\"Base\"\");\n return x;\n }\n}\npublic class DerivedClass : BaseClass\n{\n public static DerivedClass DelegatedMethod(DerivedClass x)\n {\n System.Console.WriteLine(\"\"Derived\"\");\n return x;\n }\n static void Main(string[] args)\n {\n MyDerivedDelegate goo1 = null;\n goo1 += BaseClass.DelegatedMethod;\n goo1 += DerivedClass.DelegatedMethod;\n goo1(new DerivedClass());\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (21,17): error CS0407: 'BaseClass BaseClass.DelegatedMethod(BaseClass)' has the wrong return type\n Diagnostic(ErrorCode.ERR_BadRetType, \"BaseClass.DelegatedMethod\").WithArguments(\"BaseClass.DelegatedMethod(BaseClass)\", \"BaseClass\"));\n }\n\n [WorkItem(3401, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0411ERR_CantInferMethTypeArgs01()\n {\n var text = @\"\nclass C\n{\n public void F(T t) where T : C \n {\n }\n\n public static void Main()\n {\n C c = new C();\n c.F(null); // CS0411\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantInferMethTypeArgs, Line = 11, Column = 11 } });\n }\n\n [WorkItem(2099, \"https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2099\")]\n [Fact(Skip = \"529560\")]\n public void CS0411ERR_CantInferMethTypeArgs02()\n {\n var text = @\"\npublic class MemberInitializerTest\n{\n delegate void D();\n public static void GenericMethod() { }\n public static void Run()\n {\n var genD = (D)GenericMethod;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,20): error CS0030: The type arguments for method 'MemberInitializerTest.GenericMethod()' cannot be inferred from the usage. Try specifying the type arguments explicitly.\n // var genD = (D)GenericMethod;\n Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, \"(D)GenericMethod\").WithArguments(\"MemberInitializerTest.GenericMethod()\")\n );\n }\n\n [Fact]\n public void CS0412ERR_LocalSameNameAsTypeParam()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n // Parameter name is the same as method type parameter name\n public void G(int T) // CS0412\n {\n }\n public void F()\n {\n // Method local variable name is the same as method type\n // parameter name\n double T = 0.0; // CS0412\n Console.WriteLine(T);\n }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 7, Column = 26 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 14, Column = 16 } });\n }\n\n [Fact]\n public void CS0413ERR_AsWithTypeVar()\n {\n var source =\n@\"interface I { }\nclass A { }\nclass B\n where T2 : class\n where T3 : struct\n where T4 : new()\n where T5 : I\n where T6 : A\n where T7 : T1\n{\n static void M(object o)\n {\n o = o as T1;\n o = o as T2;\n o = o as T3;\n o = o as T4;\n o = o as T5;\n o = o as T6;\n o = o as T7;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,13): error CS0413: The type parameter 'T1' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T1\").WithArguments(\"T1\").WithLocation(13, 13),\n // (15,13): error CS0413: The type parameter 'T3' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T3\").WithArguments(\"T3\").WithLocation(15, 13),\n // (16,13): error CS0413: The type parameter 'T4' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T4\").WithArguments(\"T4\").WithLocation(16, 13),\n // (17,13): error CS0413: The type parameter 'T5' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T5\").WithArguments(\"T5\").WithLocation(17, 13),\n // (19,13): error CS0413: The type parameter 'T7' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T7\").WithArguments(\"T7\").WithLocation(19, 13));\n }\n\n [Fact]\n public void CS0417ERR_NewTyvarWithArgs01()\n {\n var source =\n@\"struct S where T : new()\n{\n T F(object o)\n {\n return new T(o);\n }\n U G(object o)\n where U : new()\n where V : struct\n {\n return new U(new V(o));\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,16): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new T(o)\").WithArguments(\"T\").WithLocation(5, 16),\n // (11,16): error CS0417: 'U': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new U(new V(o))\").WithArguments(\"U\").WithLocation(11, 16),\n // (11,22): error CS0417: 'V': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new V(o)\").WithArguments(\"V\").WithLocation(11, 22));\n }\n\n [Fact]\n public void CS0417ERR_NewTyvarWithArgs02()\n {\n var source =\n@\"class C\n{\n public C() { }\n public C(object o) { }\n static void M() where T : C, new()\n {\n new T();\n new T(null);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,9): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new T(null)\").WithArguments(\"T\").WithLocation(8, 9));\n }\n\n [Fact]\n public void CS0428ERR_MethGrpToNonDel()\n {\n var text = @\"\nnamespace ConsoleApplication1\n{\n class Program\n {\n delegate int Del1();\n delegate object Del2();\n\n static void Main(string[] args)\n {\n ExampleClass ec = new ExampleClass();\n int i = ec.Method1;\n Del1 d1 = ec.Method1;\n i = ec.Method1();\n ec = ExampleClass.Method2;\n Del2 d2 = ExampleClass.Method2;\n ec = ExampleClass.Method2();\n }\n }\n\n public class ExampleClass\n {\n public int Method1() { return 1; }\n public static ExampleClass Method2() { return null; }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 12, Column = 24 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 15, Column = 31 }});\n }\n\n [Fact, WorkItem(528649, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528649\")]\n public void CS0431ERR_ColColWithTypeAlias()\n {\n var text = @\"\nusing AliasC = C;\nclass C\n{\n public class Goo { }\n}\nclass Test\n{\n class C { }\n static int Main()\n {\n AliasC::Goo goo = new AliasC::Goo();\n return 0;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, \"AliasC\").WithArguments(\"AliasC\"),\n Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, \"AliasC\").WithArguments(\"AliasC\"));\n }\n\n [WorkItem(3402, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0445ERR_UnboxNotLValue()\n {\n var text = @\"\nnamespace ConsoleApplication1\n{\n // CS0445.CS\n class UnboxingTest\n {\n public static void Main()\n {\n Point p = new Point();\n p.x = 1;\n p.y = 5;\n object obj = p;\n\n // Generates CS0445:\n ((Point)obj).x = 2;\n }\n }\n\n public struct Point\n {\n public int x;\n public int y;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnboxNotLValue, Line = 15, Column = 13 } });\n }\n\n [Fact]\n public void CS0446ERR_AnonMethGrpInForEach()\n {\n var text = @\"\nclass Tester \n{\n static void Main() \n {\n int[] intArray = new int[5];\n foreach (int i in M) { } // CS0446\n }\n static void M() { }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethGrpInForEach, Line = 7, Column = 27 } });\n }\n\n [Fact]\n [WorkItem(36203, \"https://github.com/dotnet/roslyn/issues/36203\")]\n public void CS0452_GenericConstraintError_HasHigherPriorityThanMethodOverloadError()\n {\n var code = @\"\nclass Code\n{\n void GenericMethod(int i) where T: class => throw null;\n void GenericMethod(string s) => throw null;\n\n void IncorrectMethodCall()\n {\n GenericMethod(1);\n }\n}\";\n CreateCompilation(code).VerifyDiagnostics(\n // (9,9): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Code.GenericMethod(int)'\n Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, \"GenericMethod\").WithArguments(\"Code.GenericMethod(int)\", \"T\", \"int\").WithLocation(9, 9));\n }\n\n [Fact]\n public void CS0457ERR_AmbigUDConv()\n {\n var text = @\"\npublic class A { }\n\npublic class G0 { }\npublic class G1 : G0 { }\n\npublic class H0 {\n public static implicit operator G0(H0 h) {\n return new G0();\n }\n}\npublic class H1 : H0 {\n public static implicit operator G1(H1 h) {\n return new G1();\n }\n}\n\npublic class Test \n{\n public static void F0(G0 g) { }\n public static void Main() \n {\n H1 h1a = new H1();\n F0(h1a); // CS0457\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (24,10): error CS0457: Ambiguous user defined conversions 'H1.implicit operator G1(H1)' and 'H0.implicit operator G0(H0)' when converting from 'H1' to 'G0'\n Diagnostic(ErrorCode.ERR_AmbigUDConv, \"h1a\").WithArguments(\"H1.implicit operator G1(H1)\", \"H0.implicit operator G0(H0)\", \"H1\", \"G0\"));\n }\n\n [WorkItem(22306, \"https://github.com/dotnet/roslyn/issues/22306\")]\n [Fact]\n public void AddrOnReadOnlyLocal()\n {\n var text = @\"\nclass A\n{\n public unsafe void M1()\n {\n int[] ints = new int[] { 1, 2, 3 };\n foreach (int i in ints)\n {\n int *j = &i; \n }\n\n fixed (int *i = &_i)\n {\n int **j = &i; \n }\n }\n\n private int _i = 0;\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0463ERR_DecConstError()\n {\n var text = @\"\nusing System; \nclass MyClass \n{\n public static void Main() \n {\n const decimal myDec = 79000000000000000000000000000.0m + 79000000000000000000000000000.0m; // CS0463\n Console.WriteLine(myDec.ToString());\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DecConstError, Line = 7, Column = 31 } });\n }\n\n [WorkItem(543272, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543272\")]\n [Fact]\n public void CS0463ERR_DecConstError_02()\n {\n var text = @\"\nclass MyClass \n{\n public static void Main() \n {\n decimal x1 = decimal.MaxValue + 1; // CS0463\n decimal x2 = decimal.MaxValue + decimal.One; // CS0463\n decimal x3 = decimal.MinValue - decimal.One; // CS0463\n decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463\n decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 \n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x1 = decimal.MaxValue + 1; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MaxValue + 1\"),\n // (7,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x2 = decimal.MaxValue + decimal.One; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MaxValue + decimal.One\"),\n // (8,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x3 = decimal.MinValue - decimal.One; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MinValue - decimal.One\"),\n // (9,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MinValue + decimal.MinusOne\"),\n // (10,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 \n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MaxValue - decimal.MinValue\"));\n }\n\n [Fact()]\n public void CS0471ERR_TypeArgsNotAllowedAmbig()\n {\n var text = @\"\nclass Test\n{\n public void F(bool x, bool y) {}\n public void F1()\n {\n int a = 1, b = 2, c = 3;\n F(a(3)); // CS0471\n // To resolve, try the following instead:\n // F((a(3));\n }\n}\n\n\";\n //Dev11 used to give 'The {1} '{0}' is not a generic method. If you intended an expression list, use parentheses around the &lt; expression.'\n //Roslyn will be satisfied with something less helpful.\n\n var noWarns = new Dictionary();\n noWarns.Add(MessageProvider.Instance.GetIdForErrorCode(219), ReportDiagnostic.Suppress);\n\n CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(noWarns)).VerifyDiagnostics(\n // (8,13): error CS0118: 'b' is a variable but is used like a type\n // F(a(3)); // CS0471\n Diagnostic(ErrorCode.ERR_BadSKknown, \"b\").WithArguments(\"b\", \"variable\", \"type\"),\n // (8,16): error CS0118: 'c' is a variable but is used like a type\n // F(a(3)); // CS0471\n Diagnostic(ErrorCode.ERR_BadSKknown, \"c\").WithArguments(\"c\", \"variable\", \"type\"),\n // (8,11): error CS0307: The variable 'a' cannot be used with type arguments\n // F(a(3)); // CS0471\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"a\").WithArguments(\"a\", \"variable\"));\n }\n\n [Fact]\n public void CS0516ERR_RecursiveConstructorCall()\n {\n var text = @\"\nnamespace x\n{\n public class clx\n {\n public clx() : this() // CS0516\n {\n }\n\n public static void Main()\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0516: Constructor 'x.clx.clx()' cannot call itself\n Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, \"this\").WithArguments(\"x.clx.clx()\"));\n }\n\n [WorkItem(751825, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751825\")]\n [Fact]\n public void Repro751825()\n {\n var text = @\"\npublic class A : A\n{\n public A() : base() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (2,18): error CS0308: The non-generic type 'A' cannot be used with type arguments\n // public class A : A\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"A\").WithArguments(\"A\", \"type\"),\n // (4,18): error CS0516: Constructor 'A.A()' cannot call itself\n // public A() : base() { }\n Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, \"base\").WithArguments(\"A.A()\"));\n }\n\n [WorkItem(366, \"https://github.com/dotnet/roslyn/issues/366\")]\n [Fact]\n public void IndirectConstructorCycle()\n {\n var text = @\"\npublic class A\n{\n public A() : this(1) {}\n public A(int x) : this(string.Empty) {}\n public A(string s) : this(1) {}\n public A(long l) : this(double.MaxValue) {}\n public A(double d) : this(char.MaxValue) {}\n public A(char c) : this(long.MaxValue) {}\n public A(short s) : this() {}\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,24): error CS0768: Constructor 'A.A(string)' cannot call itself through another constructor\n // public A(string s) : this(1) {}\n Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, \": this(1)\").WithArguments(\"A.A(string)\").WithLocation(6, 24),\n // (9,22): error CS0768: Constructor 'A.A(char)' cannot call itself through another constructor\n // public A(char c) : this(long.MaxValue) {}\n Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, \": this(long.MaxValue)\").WithArguments(\"A.A(char)\").WithLocation(9, 22)\n );\n }\n\n [Fact]\n public void CS0517ERR_ObjectCallingBaseConstructor()\n {\n var text = @\"namespace System\n{\n public class Void { } //just need the type to be defined\n\n public class Object\n {\n public Object() : base() { }\n }\n}\n\";\n CreateEmptyCompilation(text).VerifyDiagnostics(\n // (7,16): error CS0517: 'object' has no base class and cannot call a base constructor\n Diagnostic(ErrorCode.ERR_ObjectCallingBaseConstructor, \"Object\").WithArguments(\"object\"));\n }\n\n [Fact]\n public void CS0522ERR_StructWithBaseConstructorCall()\n {\n var text = @\"\npublic class clx\n{\n public clx(int i)\n {\n }\n\n public static void Main()\n {\n }\n}\n\npublic struct cly\n{\n public cly(int i):base(0) // CS0522\n // try the following line instead\n // public cly(int i)\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,11): error CS0522: 'cly': structs cannot call base class constructors\n Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, \"cly\").WithArguments(\"cly\"));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow01()\n {\n var source =\n@\"enum E\n{\n A = int.MaxValue - 1,\n B,\n C, // CS0543\n D,\n E = C,\n F,\n G = B,\n H, // CS0543\n I\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,5): error CS0543: 'E.C': the enumerator value is too large to fit in its type\n // C, // CS0543\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"C\").WithArguments(\"E.C\").WithLocation(5, 5),\n // (10,5): error CS0543: 'E.H': the enumerator value is too large to fit in its type\n // H, // CS0543\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"H\").WithArguments(\"E.H\").WithLocation(10, 5));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow02()\n {\n var source =\n@\"namespace N\n{\n enum E : byte { A = 255, B, C }\n enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D }\n enum G : int { X = int.MinValue, Y = X - 1, Z }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,30): error CS0543: 'E.B': the enumerator value is too large to fit in its type\n // enum E : byte { A = 255, B, C }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"B\").WithArguments(\"N.E.B\").WithLocation(3, 30),\n // (5,42): error CS0220: The operation overflows at compile time in checked mode\n // enum G : int { X = int.MinValue, Y = X - 1, Z }\n Diagnostic(ErrorCode.ERR_CheckedOverflow, \"X - 1\").WithLocation(5, 42),\n // (4,57): error CS0543: 'F.D': the enumerator value is too large to fit in its type\n // enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"D\").WithArguments(\"N.F.D\").WithLocation(4, 57));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow03()\n {\n var source =\n@\"enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K }\nenum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K }\nenum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K }\nenum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K }\nenum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H }\nenum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H }\nenum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H }\nenum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,84): error CS0543: 'S32.J': the enumerator value is too large to fit in its type\n // enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S32.J\").WithLocation(3, 84),\n // (4,87): error CS0543: 'S64.J': the enumerator value is too large to fit in its type\n // enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S64.J\").WithLocation(4, 87),\n // (7,61): error CS0543: 'U32.G': the enumerator value is too large to fit in its type\n // enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U32.G\").WithLocation(7, 61),\n // (6,65): error CS0543: 'U16.G': the enumerator value is too large to fit in its type\n // enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U16.G\").WithLocation(6, 65),\n // (5,60): error CS0543: 'U8.G': the enumerator value is too large to fit in its type\n // enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U8.G\").WithLocation(5, 60),\n // (2,90): error CS0543: 'S16.J': the enumerator value is too large to fit in its type\n // enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S16.J\").WithLocation(2, 90),\n // (1,89): error CS0543: 'S8.J': the enumerator value is too large to fit in its type\n // enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S8.J\").WithLocation(1, 89),\n // (8,63): error CS0543: 'U64.G': the enumerator value is too large to fit in its type\n // enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U64.G\").WithLocation(8, 63));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow04()\n {\n string source = string.Format(\n@\"enum A {0}\nenum B : byte {1}\nenum C : byte {2}\nenum D : sbyte {3}\",\n CreateEnumValues(300, \"E\"),\n CreateEnumValues(256, \"E\"),\n CreateEnumValues(300, \"E\"),\n CreateEnumValues(300, \"E\", sbyte.MinValue));\n\n CreateCompilation(source).VerifyDiagnostics(\n // (3,1443): error CS0543: 'C.E256': the enumerator value is too large to fit in its type\n // enum C : byte { E0, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"E256\").WithArguments(\"C.E256\").WithLocation(3, 1443),\n // (4,1451): error CS0543: 'D.E256': the enumerator value is too large to fit in its type\n // enum D : sbyte { E0 = -128, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"E256\").WithArguments(\"D.E256\").WithLocation(4, 1451));\n }\n\n // Create string \"{ E0, E1, ..., En }\"\n private static string CreateEnumValues(int count, string prefix, int? initialValue = null)\n {\n var builder = new System.Text.StringBuilder(\"{ \");\n for (int i = 0; i < count; i++)\n {\n builder.Append(prefix);\n builder.Append(i);\n if ((i == 0) && (initialValue != null))\n {\n builder.AppendFormat(\" = {0}\", initialValue.Value);\n }\n builder.Append(\", \");\n }\n builder.Append(\" }\");\n return builder.ToString();\n }\n\n // CS0570 --> Symbols\\OverriddenOrHiddenMembersTests.cs\n\n [Fact]\n public void CS0571ERR_CantCallSpecialMethod01()\n {\n var source =\n@\"class C\n{\n protected virtual object P { get; set; }\n static object Q { get; set; }\n void M(D d)\n {\n this.set_P(get_Q());\n D.set_Q(d.get_P());\n ((this.get_P))();\n }\n}\nclass D : C\n{\n protected override object P { get { return null; } set { } }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,20): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor\n // this.set_P(get_Q());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_Q\").WithArguments(\"C.Q.get\").WithLocation(7, 20),\n // (7,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor\n // this.set_P(get_Q());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_P\").WithArguments(\"C.P.set\").WithLocation(7, 14),\n // (8,19): error CS0571: 'D.P.get': cannot explicitly call operator or accessor\n // D.set_Q(d.get_P());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_P\").WithArguments(\"D.P.get\").WithLocation(8, 19),\n // (8,11): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor\n // D.set_Q(d.get_P());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_Q\").WithArguments(\"C.Q.set\").WithLocation(8, 11),\n // (9,16): error CS0571: 'C.P.get': cannot explicitly call operator or accessor\n // ((this.get_P))();\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_P\").WithArguments(\"C.P.get\").WithLocation(9, 16));\n\n // CONSIDER: Dev10 reports 'C.P.get' for the fourth error. Roslyn reports 'D.P.get'\n // because it is in the more-derived type and because Binder.LookupMembersInClass\n // calls MergeHidingLookups(D.P.get, C.P.get) with both arguments non-viable\n // (i.e. keeps current, since new value isn't better).\n }\n\n [Fact]\n public void CS0571ERR_CantCallSpecialMethod02()\n {\n var source =\n@\"using System;\nnamespace A.B\n{\n class C\n {\n object P { get; set; }\n static object Q { get { return 0; } set { } }\n void M(C c)\n {\n Func f = get_P;\n f = C.get_Q;\n Action a = c.set_P;\n a = set_Q;\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,30): error CS0571: 'C.P.get': cannot explicitly call operator or accessor\n // Func f = get_P;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_P\").WithArguments(\"A.B.C.P.get\").WithLocation(10, 30),\n // (11,19): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor\n // f = C.get_Q;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_Q\").WithArguments(\"A.B.C.Q.get\").WithLocation(11, 19),\n // (12,34): error CS0571: 'C.P.set': cannot explicitly call operator or accessor\n // Action a = c.set_P;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_P\").WithArguments(\"A.B.C.P.set\").WithLocation(12, 34),\n // (13,17): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor\n // a = set_Q;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_Q\").WithArguments(\"A.B.C.Q.set\").WithLocation(13, 17));\n }\n\n /// \n /// No errors should be reported if method with\n /// accessor name is defined in different class.\n /// \n [Fact]\n public void CS0571ERR_CantCallSpecialMethod03()\n {\n var source =\n@\"class A\n{\n public object get_P() { return null; }\n}\nclass B : A\n{\n public object P { get; set; }\n void M()\n {\n object o = this.P;\n o = this.get_P();\n }\n}\nclass C\n{\n void M(B b)\n {\n object o = b.P;\n o = b.get_P();\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact()]\n public void CS0571ERR_CantCallSpecialMethod04()\n {\n var compilation = CreateCompilation(\n@\"public class MyClass\n{\n public static MyClass operator ++(MyClass c)\n {\n return null;\n }\n public static void M()\n {\n op_Increment(null); // CS0571\n }\n}\n\").VerifyDiagnostics(\n // (9,9): error CS0571: 'MyClass.operator ++(MyClass)': cannot explicitly call operator or accessor\n // op_Increment(null); // CS0571\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Increment\").WithArguments(\"MyClass.operator ++(MyClass)\"));\n }\n\n [Fact]\n public void CS0571ERR_CantCallSpecialMethod05()\n {\n var source =\n@\"\nusing System;\npublic class C\n{\n public static void M()\n {\n IntPtr.op_Addition(default(IntPtr), 0);\n IntPtr.op_Subtraction(default(IntPtr), 0);\n IntPtr.op_Equality(default(IntPtr), default(IntPtr));\n IntPtr.op_Inequality(default(IntPtr), default(IntPtr));\n IntPtr.op_Explicit(0);\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,16): error CS0571: 'IntPtr.operator +(IntPtr, int)': cannot explicitly call operator or accessor\n // IntPtr.op_Addition(default(IntPtr), 0);\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Addition\").WithArguments(\"System.IntPtr.operator +(System.IntPtr, int)\").WithLocation(7, 16),\n // (8,16): error CS0571: 'IntPtr.operator -(IntPtr, int)': cannot explicitly call operator or accessor\n // IntPtr.op_Subtraction(default(IntPtr), 0);\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Subtraction\").WithArguments(\"System.IntPtr.operator -(System.IntPtr, int)\").WithLocation(8, 16),\n // (9,16): error CS0571: 'IntPtr.operator ==(IntPtr, IntPtr)': cannot explicitly call operator or accessor\n // IntPtr.op_Equality(default(IntPtr), default(IntPtr));\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Equality\").WithArguments(\"System.IntPtr.operator ==(System.IntPtr, System.IntPtr)\").WithLocation(9, 16),\n // (10,16): error CS0571: 'IntPtr.operator !=(IntPtr, IntPtr)': cannot explicitly call operator or accessor\n // IntPtr.op_Inequality(default(IntPtr), default(IntPtr));\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Inequality\").WithArguments(\"System.IntPtr.operator !=(System.IntPtr, System.IntPtr)\").WithLocation(10, 16),\n // (11,16): error CS0571: 'IntPtr.explicit operator IntPtr(int)': cannot explicitly call operator or accessor\n // IntPtr.op_Explicit(0);\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Explicit\").WithArguments(\"System.IntPtr.explicit operator System.IntPtr(int)\").WithLocation(11, 16));\n }\n\n [Fact]\n public void CS0572ERR_BadTypeReference()\n {\n var text = @\"\nusing System;\nclass C\n{\n public class Inner\n {\n public static int v = 9;\n }\n}\n\nclass D : C\n{\n public static void Main()\n {\n C cValue = new C();\n Console.WriteLine(cValue.Inner.v); // CS0572\n // try the following line instead\n // Console.WriteLine(C.Inner.v);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadTypeReference, Line = 16, Column = 32 } });\n }\n\n [Fact]\n public void CS0574ERR_BadDestructorName()\n {\n var test = @\"\nnamespace x\n{\n public class iii\n {\n ~iiii(){}\n public static void Main()\n {\n }\n }\n}\n\";\n\n CreateCompilation(test).VerifyDiagnostics(\n // (6,10): error CS0574: Name of destructor must match name of type\n // ~iiii(){}\n Diagnostic(ErrorCode.ERR_BadDestructorName, \"iiii\").WithLocation(6, 10));\n }\n\n [WorkItem(541951, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951\")]\n [Fact]\n public void CS0611ERR_ArrayElementCantBeRefAny()\n {\n var text = @\"\npublic class Test\n{\n public System.TypedReference[] x;\n public System.RuntimeArgumentHandle[][] y;\n}\n\";\n var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45);\n comp.VerifyDiagnostics(\n // (4,12): error CS0611: Array elements cannot be of type 'System.TypedReference'\n // public System.TypedReference[] x;\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"System.TypedReference\").WithArguments(\"System.TypedReference\").WithLocation(4, 12),\n // (5,12): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle'\n // public System.RuntimeArgumentHandle[][] y;\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"System.RuntimeArgumentHandle\").WithArguments(\"System.RuntimeArgumentHandle\").WithLocation(5, 12));\n }\n\n [WorkItem(541951, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951\")]\n [Fact]\n public void CS0611ERR_ArrayElementCantBeRefAny_1()\n {\n var text =\n@\"using System;\nclass C\n{\n static void M()\n {\n var x = new[] { new ArgIterator() };\n var y = new[] { new TypedReference() };\n var z = new[] { new RuntimeArgumentHandle() };\n }\n}\";\n var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45);\n comp.VerifyDiagnostics(\n // (6,17): error CS0611: Array elements cannot be of type 'System.ArgIterator'\n // var x = new[] { new ArgIterator() };\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"new[] { new ArgIterator() }\").WithArguments(\"System.ArgIterator\").WithLocation(6, 17),\n // (7,17): error CS0611: Array elements cannot be of type 'System.TypedReference'\n // var y = new[] { new TypedReference() };\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"new[] { new TypedReference() }\").WithArguments(\"System.TypedReference\").WithLocation(7, 17),\n // (8,17): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle'\n // var z = new[] { new RuntimeArgumentHandle() };\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"new[] { new RuntimeArgumentHandle() }\").WithArguments(\"System.RuntimeArgumentHandle\").WithLocation(8, 17));\n }\n\n [Fact, WorkItem(546062, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062\")]\n public void CS0619ERR_DeprecatedSymbolStr()\n {\n var text = @\"\nusing System;\nnamespace a\n{\n [Obsolete]\n class C1 { }\n\n [Obsolete(\"\"Obsolescence message\"\", true)]\n interface I1 { }\n\n public class CI1 : I1 { }\n\n public class MainClass\n {\n public static void Main()\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,24): error CS0619: 'a.I1' is obsolete: 'Obsolescence message'\n // public class CI1 : I1 { }\n Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, \"I1\").WithArguments(\"a.I1\", \"Obsolescence message\")\n );\n }\n\n [Fact]\n public void CS0622ERR_ArrayInitToNonArrayType()\n {\n var text = @\"\npublic class Test\n{\n public static void Main ()\n {\n Test t = { new Test() }; // CS0622\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitToNonArrayType, Line = 6, Column = 18 } });\n }\n\n [Fact]\n public void CS0623ERR_ArrayInitInBadPlace()\n {\n var text = @\"\nclass X\n{\n public void goo(int a)\n {\n int[] x = { { 4 } }; //CS0623\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitInBadPlace, Line = 6, Column = 21 } });\n }\n\n [Fact]\n public void CS0631ERR_IllegalRefParam()\n {\n var compilation = CreateCompilation(\n@\"interface I\n{\n object this[ref object index] { get; set; }\n}\nclass C\n{\n internal object this[object x, out object y] { get { y = null; return null; } }\n}\nstruct S\n{\n internal object this[out int x, out int y] { set { x = 0; y = 0; } }\n}\");\n compilation.VerifyDiagnostics(\n // (3,17): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"ref\").WithLocation(3, 17),\n // (7,36): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"out\").WithLocation(7, 36),\n // (11,26): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"out\").WithLocation(11, 26),\n // (11,37): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"out\").WithLocation(11, 37));\n }\n\n [WorkItem(529305, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529305\")]\n [Fact()]\n public void CS0664ERR_LiteralDoubleCast()\n {\n var text = @\"\nclass Example\n{\n static void Main()\n {\n // CS0664, because 1.0 is interpreted as a double:\n decimal d1 = 1.0;\n float f1 = 2.0;\n }\n}\";\n var compilation = CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (7,22): error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type\n // decimal d1 = 1.0;\n Diagnostic(ErrorCode.ERR_LiteralDoubleCast, \"1.0\").WithArguments(\"M\", \"decimal\").WithLocation(7, 22),\n // (8,20): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type\n // float f1 = 2.0;\n Diagnostic(ErrorCode.ERR_LiteralDoubleCast, \"2.0\").WithArguments(\"F\", \"float\").WithLocation(8, 20),\n // (7,17): warning CS0219: The variable 'd1' is assigned but its value is never used\n // decimal d1 = 1.0;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"d1\").WithArguments(\"d1\").WithLocation(7, 17),\n // (8,15): warning CS0219: The variable 'f1' is assigned but its value is never used\n // float f1 = 2.0;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"f1\").WithArguments(\"f1\").WithLocation(8, 15));\n }\n\n [Fact]\n public void CS0670ERR_FieldCantHaveVoidType()\n {\n CreateCompilation(@\"\nclass C \n{\n void x = default(void); \n}\").VerifyDiagnostics(\n // (4,22): error CS1547: Keyword 'void' cannot be used in this context\n Diagnostic(ErrorCode.ERR_NoVoidHere, \"void\"),\n // (4,5): error CS0670: Field cannot have void type\n Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, \"void\"));\n }\n\n [Fact]\n public void CS0670ERR_FieldCantHaveVoidType_Var()\n {\n CreateCompilationWithMscorlib45(@\"\nvar x = default(void); \n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,17): error CS1547: Keyword 'void' cannot be used in this context\n Diagnostic(ErrorCode.ERR_NoVoidHere, \"void\"),\n // (2,1): error CS0670: Field cannot have void type\n Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, \"var\"));\n }\n\n [WorkItem(538016, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538016\")]\n [Fact]\n public void CS0687ERR_AliasQualAsExpression()\n {\n var text = @\"\nusing M = Test;\nusing System;\n\npublic class Test\n{\n public static int x = 77;\n\n public static void Main() \n {\n Console.WriteLine(M::x); // CS0687\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, \"M\").WithArguments(\"M\")\n );\n }\n\n [Fact]\n public void CS0704ERR_LookupInTypeVariable()\n {\n var text =\n@\"using System;\nclass A\n{\n internal class B : Attribute { }\n internal class C { }\n}\nclass D where T : A\n{\n class E : T.B { }\n interface I where U : T.B { }\n [T.B]\n static object M()\n {\n T.C b1 = new T.C();\n T.B b2 = null;\n b1 = default(T.B);\n object o = typeof(T.C);\n o = o as T.B;\n return b1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,15): error CS0704: Cannot do member lookup in 'T' because it is a type parameter class E : T.B { }\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (10,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // interface I where U : T.B { }\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (11,6): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // [T.B]\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (14,9): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // T.C b1 = new T.C();\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.C\").WithArguments(\"T\"),\n // (14,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // T.C b1 = new T.C();\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.C\").WithArguments(\"T\"),\n // (15,9): error CS0307: The type parameter 'T' cannot be used with type arguments\n // T.B b2 = null;\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"T\").WithArguments(\"T\", \"type parameter\"),\n // (16,22): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // b1 = default(T.B);\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (17,27): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // object o = typeof(T.C);\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.C\").WithArguments(\"T\"),\n // (18,18): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // o = o as T.B;\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\")\n );\n }\n\n [Fact]\n public void CS0712ERR_InstantiatingStaticClass()\n {\n var text = @\"\npublic static class SC\n{\n}\n\npublic class CMain\n{\n public static void Main()\n {\n SC sc = new SC(); // CS0712\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_InstantiatingStaticClass, Line = 10, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_VarDeclIsStaticClass, Line = 10, Column = 9 }});\n }\n\n [Fact]\n public void CS0716ERR_ConvertToStaticClass()\n {\n var text = @\"\npublic static class SC\n{\n static void F() { }\n}\n\npublic class Test\n{\n public static void Main()\n {\n object o = new object();\n System.Console.WriteLine((SC)o); // CS0716\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ConvertToStaticClass, Line = 12, Column = 34 } });\n }\n\n [Fact]\n [WorkItem(36203, \"https://github.com/dotnet/roslyn/issues/36203\")]\n public void CS0718_StaticClassError_HasHigherPriorityThanMethodOverloadError()\n {\n var code = @\"\nstatic class StaticClass { }\n\nclass Code\n{\n void GenericMethod(int i) => throw null;\n void GenericMethod(string s) => throw null;\n\n void IncorrectMethodCall()\n {\n GenericMethod(1);\n }\n}\";\n CreateCompilation(code).VerifyDiagnostics(\n // (11,9): error CS0718: 'StaticClass': static types cannot be used as type arguments\n Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, \"GenericMethod\").WithArguments(\"StaticClass\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0723ERR_VarDeclIsStaticClass_Locals()\n {\n CreateCompilation(\n@\"static class SC\n{\n static void M()\n {\n SC sc = null; // CS0723\n N(sc);\n var sc2 = new SC();\n }\n static void N(object o)\n {\n }\n}\").VerifyDiagnostics(\n // (5,9): error CS0723: Cannot declare a variable of static type 'SC'\n Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, \"SC\").WithArguments(\"SC\"),\n // (7,19): error CS0712: Cannot create an instance of the static class 'SC'\n Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, \"new SC()\").WithArguments(\"SC\"),\n // (7,9): error CS0723: Cannot declare a variable of static type 'SC'\n Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, \"var\").WithArguments(\"SC\"));\n }\n\n [Fact]\n public void CS0723ERR_VarDeclIsStaticClass_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nstatic class SC {} \n\nvar sc2 = new SC();\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (4,5): error CS0723: Cannot declare a variable of static type 'SC'\n Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, \"sc2\").WithArguments(\"SC\"),\n // (4,11): error CS0712: Cannot create an instance of the static class 'SC'\n Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, \"new SC()\").WithArguments(\"SC\"));\n }\n\n [Fact]\n public void CS0724ERR_BadEmptyThrowInFinally()\n {\n var text = @\"\nusing System;\n\nclass X\n{\n static void Test()\n {\n try\n {\n throw new Exception();\n }\n catch\n {\n try\n {\n }\n finally\n {\n throw; // CS0724\n }\n }\n }\n\n static void Main()\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\").WithLocation(19, 17));\n }\n\n [Fact, WorkItem(1040213, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040213\")]\n public void CS0724ERR_BadEmptyThrowInFinally_Nesting()\n {\n var text = @\"\nusing System;\n\nclass X\n{\n static void Test(bool b)\n {\n try\n {\n throw new Exception();\n }\n catch\n {\n try\n {\n }\n finally\n {\n if (b) throw; // CS0724\n\n try\n {\n throw; // CS0724\n }\n catch\n {\n throw; // OK\n }\n finally\n {\n throw; // CS0724\n }\n }\n }\n }\n\n static void Main()\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"));\n }\n\n [Fact]\n public void CS0747ERR_InvalidInitializerElementInitializer()\n {\n var text = @\"\nusing System.Collections.Generic;\n\npublic class C\n{\n public static int Main()\n {\n var t = new List { Capacity = 2, 1 }; // CS0747\n return 1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, \"1\"));\n }\n\n [Fact]\n public void CS0762ERR_PartialMethodToDelegate()\n {\n var text = @\"\npublic delegate void TestDel();\n\n public partial class C\n {\n partial void Part();\n\n public static int Main()\n {\n C c = new C();\n TestDel td = new TestDel(c.Part); // CS0762\n return 1;\n }\n\n }\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodToDelegate, Line = 11, Column = 38 } });\n }\n\n [Fact]\n public void CS0765ERR_PartialMethodInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq.Expressions;\n\npublic delegate void dele();\n\npublic class ConClass\n{\n [Conditional(\"\"CONDITION\"\")]\n public static void TestMethod() { }\n}\n\npublic partial class PartClass : IEnumerable\n{\n List list = new List();\n\n partial void Add(int x);\n\n public IEnumerator GetEnumerator()\n {\n for (int i = 0; i < list.Count; i++)\n yield return list[i];\n }\n\n static void Main()\n {\n Expression> testExpr1 = () => new PartClass { 1, 2 }; // CS0765\n Expression testExpr2 = () => ConClass.TestMethod(); // CS0765\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (30,71): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees\n // Expression> testExpr1 = () => new PartClass { 1, 2 }; // CS0765\n Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, \"1\"),\n // (30,74): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees\n // Expression> testExpr1 = () => new PartClass { 1, 2 }; // CS0765\n Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, \"2\"),\n // (31,44): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees\n // Expression testExpr2 = () => ConClass.TestMethod(); // CS0765\n Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, \"ConClass.TestMethod()\"));\n }\n\n [Fact]\n public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Local()\n {\n CreateCompilation(@\"\nclass Test\n{\n public static void Main()\n {\n var m = Main;\n var d = s => -1; // CS8917\n var e = (string s) => 0;\n var p = null;//CS0815\n var del = delegate(string a) { return -1; };\n var v = M(); // CS0815\n }\n static void M() {}\n}\").VerifyDiagnostics(\n // (7,17): error CS8917: The delegate type could not be inferred.\n // var d = s => -1; // CS8917\n Diagnostic(ErrorCode.ERR_CannotInferDelegateType, \"s => -1\").WithLocation(7, 17),\n // (9,13): error CS0815: Cannot assign to an implicitly-typed variable\n // var p = null;//CS0815\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"p = null\").WithArguments(\"\").WithLocation(9, 13),\n // (11,13): error CS0815: Cannot assign void to an implicitly-typed variable\n // var v = M(); // CS0815\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"v = M()\").WithArguments(\"void\").WithLocation(11, 13));\n }\n\n [Fact]\n public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Field()\n {\n CreateCompilationWithMscorlib45(@\"\nstatic void M() {}\n\nvar m = M; \nvar d = s => -1; \nvar e = (string s) => 0;\nvar p = null; \nvar del = delegate(string a) { return -1; };\nvar v = M(); \n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (5,9): error CS8917: The delegate type could not be inferred.\n // var d = s => -1; \n Diagnostic(ErrorCode.ERR_CannotInferDelegateType, \"s => -1\").WithLocation(5, 9),\n // (7,5): error CS0815: Cannot assign to an implicitly-typed variable\n // var p = null; \n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"p = null\").WithArguments(\"\").WithLocation(7, 5),\n // (9,1): error CS0670: Field cannot have void type\n // var v = M(); \n Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, \"var\").WithLocation(9, 1));\n }\n\n [Fact]\n public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer()\n {\n var text = @\"\nclass A\n{\n public static int Main()\n {\n var a; // CS0818\n return -1;\n }\n}\";\n // In the native compiler we skip post-initial-binding error analysis if there was\n // an error during the initial binding, so we report only that the \"var\" declaration \n // is bad. We do not report warnings like \"variable b is assigned but never used\". \n // In Roslyn we do flow analysis even if the initial binding pass produced an error,\n // so we have extra errors here.\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, Line = 6, Column = 13 },\n new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVar, Line = 6, Column = 13, IsWarning = true }});\n }\n\n [Fact]\n public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvar a; // CS0818\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (1,5): error CS0818: Implicitly-typed variables must be initialized\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, \"a\"));\n }\n\n [Fact]\n public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Locals()\n {\n var text = @\"\nclass A\n{\n public static int Main()\n {\n var a = 3, b = 2; // CS0819\n return -1;\n }\n}\n\";\n // In the native compiler we skip post-initial-binding error analysis if there was\n // an error during the initial binding, so we report only that the \"var\" declaration \n // is bad. We do not report warnings like \"variable b is assigned but never used\". \n // In Roslyn we do flow analysis even if the initial binding pass produced an error,\n // so we have extra errors here.\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, Line = 6, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 13, IsWarning = true },\n new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 20, IsWarning = true }});\n }\n\n [Fact]\n public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvar goo = 4, bar = 4.5;\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,1): error CS0819: Implicitly-typed fields cannot have multiple declarators\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, \"var\"));\n }\n\n [Fact]\n public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer()\n {\n var text = @\"\nclass G\n{\n public static int Main()\n {\n var a = { 1, 2, 3 }; //CS0820\n return -1;\n }\n}\";\n // In the native compilers this code produces two errors, both \n // \"you can't assign an array initializer to an implicitly typed local\" and\n // \"you can only use an array initializer to assign to an array type\". \n // It seems like the first error ought to prevent the second. In Roslyn\n // we only produce the first error.\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, Line = 6, Column = 13 }});\n }\n\n [Fact]\n public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvar y = { 1, 2, 3 };\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (1,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, \"y = { 1, 2, 3 }\"));\n }\n\n [Fact]\n public void CS0821ERR_ImplicitlyTypedLocalCannotBeFixed()\n {\n var text = @\"\nclass A\n{\n static int x;\n\n public static int Main()\n {\n unsafe\n {\n fixed (var p = &x) { }\n }\n return -1;\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (10,24): error CS0821: Implicitly-typed local variables cannot be fixed\n // fixed (var p = &x) { }\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, \"p = &x\"));\n }\n\n [Fact]\n public void CS0822ERR_ImplicitlyTypedLocalCannotBeConst()\n {\n var text = @\"\nclass A\n{\n public static void Main()\n {\n const var x = 0; // CS0822.cs\n const var y = (int?)null + x;\n }\n}\";\n // In the dev10 compiler, the second line reports both that \"const var\" is illegal \n // and that the initializer must be a valid constant. This seems a bit odd, so\n // in Roslyn we just report the first error. Let the user sort out whether they\n // meant it to be a constant or a variable, and then we can tell them if its a\n // bad constant.\n\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,15): error CS0822: Implicitly-typed variables cannot be constant\n // const var x = 0; // CS0822.cs\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, \"var x = 0\").WithLocation(6, 15),\n // (7,15): error CS0822: Implicitly-typed variables cannot be constant\n // const var y = (int?)null + x;\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, \"var y = (int?)null + x\").WithLocation(7, 15),\n // (7,23): warning CS0458: The result of the expression is always 'null' of type 'int?'\n // const var y = (int?)null + x;\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"(int?)null + x\").WithArguments(\"int?\").WithLocation(7, 23)\n );\n }\n\n [Fact]\n public void CS0822ERR_ImplicitlyTypedVariableCannotBeConst_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nconst var x = 0; // CS0822.cs\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,7): error CS0822: Implicitly-typed variables cannot be constant\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, \"var\"));\n }\n\n [Fact]\n public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvoid goo(var arg) { }\nvar goo(int arg) { return 2; }\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (1,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code\n Diagnostic(ErrorCode.ERR_TypeVarNotFound, \"var\"),\n // (2,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code\n Diagnostic(ErrorCode.ERR_TypeVarNotFound, \"var\"));\n }\n\n [Fact]\n public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields2()\n {\n CreateCompilationWithMscorlib45(@\"\nT goo() { return default(T); }\ngoo();\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,5): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code\n Diagnostic(ErrorCode.ERR_TypeVarNotFound, \"var\"));\n }\n\n [Fact()]\n public void CS0826ERR_ImplicitlyTypedArrayNoBestType()\n {\n var text = @\"\npublic class C\n{\n delegate void D();\n public static void M1() {}\n public static void M2(int x) {}\n public static int M3() { return 1; }\n public static int M4(int x) { return x; }\n\n public static int Main()\n {\n var z = new[] { 1, \"\"str\"\" }; // CS0826\n\n char c = 'c';\n short s1 = 0;\n short s2 = -0;\n short s3 = 1;\n short s4 = -1;\n \n var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826\n\n var a = new [] {}; // CS0826\n\n byte b = 3;\n var arr = new [] {b, c}; // CS0826\n\n var a1 = new [] {null}; // CS0826\n var a2 = new [] {null, null, null}; // CS0826\n\n D[] l1 = new [] {x=>x+1}; // CS0826\n D[] l2 = new [] {x=>x+1, x=>{return x + 1;}, (int x)=>x+1, (int x)=>{return x + 1;}, (x, y)=>x + y, ()=>{return 1;}}; // CS0826\n\n D[] d1 = new [] {delegate {}}; // CS0826\n D[] d2 = new [] {delegate {}, delegate (){}, delegate {return 1;}, delegate {return;}, delegate(int x){}, delegate(int x){return x;}, delegate(int x, int y){return x + y;}}; // CS0826\n\n var m = new [] {M1, M2, M3, M4}; // CS0826\n\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 12, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 20, Column = 22 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 22, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 25, Column = 19 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 27, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 28, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 30, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 31, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 33, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 34, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 36, Column = 17 }});\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { p1 = null }; // CS0828\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_2()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new { p1 = Main }; // CS0828\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_3()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new { p1 = Main() }; // CS0828\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_4()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new { p1 = ()=>3 }; // CS0828\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_5()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new \n { \n p1 = delegate { return 1; } // CS0828\n }; \n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 8, Column = 13 } });\n }\n\n [Fact]\n public void CS0831ERR_ExpressionTreeContainsBaseAccess()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class A\n{\n public virtual int BaseMethod() { return 1; }\n}\npublic class C : A\n{\n public override int BaseMethod() { return 2; }\n public int Test(C c)\n {\n Expression> e = () => base.BaseMethod(); // CS0831\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (14,41): error CS0831: An expression tree may not contain a base access\n // Expression> e = () => base.BaseMethod(); // CS0831\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, \"base\")\n );\n }\n\n [Fact]\n public void CS0832ERR_ExpressionTreeContainsAssignment()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class C\n{\n public static int Main()\n {\n Expression> e1 = x => x += 5; // CS0843\n Expression> e2 = x => x = 5; // CS0843\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (9,46): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e1 = x => x += 5; // CS0843\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"x += 5\"),\n // (10,46): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e2 = x => x = 5; // CS0843\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"x = 5\")\n );\n }\n\n [Fact]\n public void CS0833ERR_AnonymousTypeDuplicatePropertyName()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { p1 = 1, p1 = 2 }; // CS0833\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } });\n }\n\n [Fact]\n public void CS0833ERR_AnonymousTypeDuplicatePropertyName_2()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { C.Prop, Prop = 2 }; // CS0833\n return 1;\n }\n static string Prop { get; set; }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } });\n }\n\n [Fact]\n public void CS0833ERR_AnonymousTypeDuplicatePropertyName_3()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { C.Prop, Prop = 2 }; // CS0833 + CS0828\n return 1;\n }\n static string Prop() { return null; }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 }});\n }\n\n [Fact]\n public void CS0834ERR_StatementLambdaToExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class C\n{\n public static void Main()\n {\n Expression> e = x => { return x; }; // CS0834\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (9,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree\n // Expression> e = x => { return x; }; // CS0834\n Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, \"x => { return x; }\")\n );\n }\n\n [Fact]\n public void CS0835ERR_ExpressionTreeMustHaveDelegate()\n {\n var text = @\"\nusing System.Linq.Expressions;\n\npublic class Myclass\n{\n public static int Main()\n {\n Expression e = x => x + 1; // CS0835\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { LinqAssemblyRef },\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExpressionTreeMustHaveDelegate, Line = 8, Column = 29 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable()\n {\n var text = @\"\nusing System;\n[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]\npublic class MyClass : Attribute\n{\n public MyClass(object obj)\n {\n }\n}\n\n[MyClass(new { })] // CS0836\npublic class ClassGoo\n{\n}\n\npublic class Test\n{\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 11, Column = 10 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable2()\n {\n var text = @\"\npublic class Test\n{\n const object x = new { };\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 4, Column = 22 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable3()\n {\n var text = @\"\npublic class Test\n{\n static object y = new { };\n private object x = new { };\n public static int Main()\n {\n return 0;\n }\n}\n\";\n // NOTE: Actually we assert that #836 is NOT generated\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable4()\n {\n var text = @\"\npublic class Test\n{\n public static int Main(object x = new { })\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueMustBeConstant, Line = 4, Column = 39 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable5()\n {\n var text = @\"\nusing System;\n[AttributeUsage(AttributeTargets.All)]\npublic class MyClass : Attribute\n{\n public MyClass(object obj)\n {\n }\n}\n\npublic class Test\n{\n [MyClass(new { })] // CS0836\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable6()\n {\n var text = @\"\nusing System;\n[AttributeUsage(AttributeTargets.All)]\npublic class MyClass : Attribute\n{\n public MyClass(object obj)\n {\n }\n}\n\npublic class Test\n{\n [MyClass(new { })] // CS0836\n static object y = new { };\n\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } });\n }\n\n [Fact]\n public void CS0837ERR_LambdaInIsAs()\n {\n var text = @\"\nnamespace TestNamespace\n{\n public delegate void Del();\n\n class Test\n {\n static int Main()\n {\n bool b1 = (() => { }) is Del; // CS0837\n bool b2 = delegate() { } is Del;// CS0837\n Del d1 = () => { } as Del; // CS0837\n Del d2 = delegate() { } as Del; // CS0837\n return 1;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b1 = (() => { }) is Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"(() => { }) is Del\").WithLocation(10, 23),\n // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } is Del\").WithLocation(11, 23),\n // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"is\").WithArguments(\"is\").WithLocation(11, 38),\n // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"() => { } as Del\").WithLocation(12, 22),\n // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(12, 32),\n // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } as Del\").WithLocation(13, 22),\n // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(13, 37)\n );\n CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(5)).VerifyDiagnostics(\n // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b1 = (() => { }) is Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"(() => { }) is Del\").WithLocation(10, 23),\n // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } is Del\").WithLocation(11, 23),\n // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"is\").WithArguments(\"is\").WithLocation(11, 38),\n // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"() => { } as Del\").WithLocation(12, 22),\n // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(12, 32),\n // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } as Del\").WithLocation(13, 22),\n // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(13, 37)\n );\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration01()\n {\n CreateCompilation(\n@\"class C\n{\n static void M()\n {\n j = 5; // CS0841\n int j; // To fix, move this line up.\n }\n}\n\")\n // The native compiler just produces the \"var used before decl\" error; the Roslyn\n // compiler runs the flow checking pass even if the initial binding failed. We \n // might consider turning off flow checking if the initial binding failed, and\n // removing the warning here.\n\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"j\").WithArguments(\"j\"),\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"j\").WithArguments(\"j\"));\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration02()\n {\n CreateCompilation(\n@\"class C\n{\n static void M()\n {\n int a = b, b = 0, c = a;\n for (int x = y, y = 0; ; )\n {\n }\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"b\").WithArguments(\"b\"),\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"y\").WithArguments(\"y\"));\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration03()\n {\n // It is a bit unfortunate that we produce \"can't use variable before decl\" here\n // when the variable is being used after the decl. Perhaps we should generate\n // a better error?\n\n CreateCompilation(\n@\"class C\n{\n static int N(out int q) { q = 1; return 2;}\n static void M()\n {\n var x = N(out x);\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"x\").WithArguments(\"x\"));\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration04()\n {\n var systemRef = Net451.System;\n CreateCompilationWithMscorlib40AndSystemCore(\n@\"using System.Collections.Generic;\nclass Base\n{\n int i;\n}\nclass Derived : Base\n{\n int j;\n}\nclass C\n{\n public static void Main()\n {\n HashSet set1 = new HashSet();\n\n foreach (Base b in set1)\n {\n Derived d = b as Derived;\n Base b = null;\n }\n }\n}\n\", new List { systemRef })\n .VerifyDiagnostics(\n // (18,25): error CS0841: Cannot use local variable 'b' before it is declared\n // Derived d = b as Derived;\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"b\").WithArguments(\"b\"),\n // (19,18): error CS0136: A local or parameter named 'b' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // Base b = null;\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"b\").WithArguments(\"b\"),\n // (4,9): warning CS0169: The field 'Base.i' is never used\n // int i;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"i\").WithArguments(\"Base.i\"),\n // (8,9): warning CS0169: The field 'Derived.j' is never used\n // int j;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"j\").WithArguments(\"Derived.j\"));\n }\n\n /// \n /// No errors using statics before declaration.\n /// \n [Fact]\n public void StaticUsedBeforeDeclaration()\n {\n var text =\n@\"class C\n{\n static int F = G + 2;\n static int G = F + 1;\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);\n }\n\n [Fact]\n public void CS0843ERR_UnassignedThisAutoProperty()\n {\n var text = @\"\nstruct S\n{\n public int AIProp { get; set; }\n public S(int i) { } //CS0843\n}\n\nclass Test\n{\n static int Main()\n {\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnassignedThisAutoProperty, Line = 5, Column = 12 } });\n }\n\n [Fact]\n public void CS0844ERR_VariableUsedBeforeDeclarationAndHidesField()\n {\n var text = @\"\npublic class MyClass\n{\n int num;\n public void TestMethod()\n {\n num = 5; // CS0844\n int num = 6;\n System.Console.WriteLine(num);\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (7,9): error CS0844: Cannot use local variable 'num' before it is declared. The declaration of the local variable hides the field 'MyClass.num'.\n // num = 5; // CS0844\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, \"num\").WithArguments(\"num\", \"MyClass.num\"),\n // (4,9): warning CS0169: The field 'MyClass.num' is never used\n // int num;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"num\").WithArguments(\"MyClass.num\")\n );\n }\n\n [Fact]\n public void CS0845ERR_ExpressionTreeContainsBadCoalesce()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n Expression> e = () => null ?? \"\"x\"\"; // CS0845\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (11,48): error CS0845: An expression tree lambda may not contain a coalescing operator with a null literal left-hand side\n // Expression> e = () => null ?? \"x\"; // CS0845\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, \"null\")\n );\n }\n\n [WorkItem(3717, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0846ERR_ArrayInitializerExpected()\n {\n var text = @\"public class Myclass\n{\n public static void Main()\n {\n int[,] a = new int[,] { 1 }; // error\n } \n} \n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitializerExpected, Line = 5, Column = 33 } });\n }\n\n [Fact]\n public void CS0847ERR_ArrayInitializerIncorrectLength()\n {\n var text = @\"\npublic class Program\n{\n public static void Main(string[] args)\n {\n int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected\n int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected\n ar0[0] = ar1[0];\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,31): error CS0847: An array initializer of length '0' is expected\n // int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected\n Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, \"{0}\").WithArguments(\"0\").WithLocation(6, 31),\n // (7,31): error CS0847: An array initializer of length '3' is expected\n // int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected\n Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, \"{}\").WithArguments(\"3\").WithLocation(7, 31));\n }\n\n [Fact]\n public void CS0853ERR_ExpressionTreeContainsNamedArgument01()\n {\n var text = @\"\nusing System.Linq.Expressions;\nnamespace ConsoleApplication3\n{\n class Program\n {\n delegate string dg(int x);\n static void Main(string[] args)\n {\n Expression myET = x => Index(minSessions:5);\n }\n public static string Index(int minSessions = 0)\n {\n return minSessions.ToString();\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,40): error CS0853: An expression tree may not contain a named argument specification\n // Expression myET = x => Index(minSessions:5);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, \"Index(minSessions:5)\").WithLocation(10, 40)\n );\n }\n\n [WorkItem(545063, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545063\")]\n [Fact]\n public void CS0853ERR_ExpressionTreeContainsNamedArgument02()\n {\n var text = @\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n \nclass A\n{\n static void Main()\n {\n Expression> f = () => new List { 1 } [index: 0];\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,41): error CS0853: An expression tree may not contain a named argument specification\n // Expression> f = () => new List { 1 } [index: 0];\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, \"new List { 1 } [index: 0]\").WithLocation(10, 41)\n );\n }\n\n [Fact]\n public void CS0854ERR_ExpressionTreeContainsOptionalArgument01()\n {\n var text = @\"\nusing System.Linq.Expressions;\nnamespace ConsoleApplication3\n{\n class Program\n {\n delegate string dg(int x);\n static void Main(string[] args)\n {\n Expression myET = x => Index();\n }\n public static string Index(int minSessions = 0)\n {\n return minSessions.ToString();\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,40): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n // Expression myET = x => Index();\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"Index()\").WithLocation(10, 40)\n );\n }\n\n [Fact]\n public void CS0854ERR_ExpressionTreeContainsOptionalArgument02()\n {\n var text =\n@\"using System;\nusing System.Linq.Expressions;\nclass A\n{\n internal object this[int x, int y = 2]\n {\n get { return null; }\n }\n}\nclass B\n{\n internal object this[int x, int y = 2]\n {\n set { }\n }\n}\nclass C\n{\n static void M(A a, B b)\n {\n Expression> e1;\n e1 = () => a[0];\n e1 = () => a[1, 2];\n Expression e2;\n e2 = () => b[3] = null;\n e2 = () => b[4, 5] = null;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (22,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"a[0]\").WithLocation(22, 20),\n // (25,20): error CS0832: An expression tree may not contain an assignment operator\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"b[3] = null\").WithLocation(25, 20),\n // (25,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"b[3]\").WithLocation(25, 20),\n // (26,20): error CS0832: An expression tree may not contain an assignment operator\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"b[4, 5] = null\").WithLocation(26, 20));\n }\n\n [Fact]\n public void CS0854ERR_ExpressionTreeContainsOptionalArgument03()\n {\n var text =\n@\"using System;\nusing System.Collections;\nusing System.Linq.Expressions;\n\npublic class Collection : IEnumerable\n{\n public void Add(int i, int j = 0) { }\n\n public IEnumerator GetEnumerator()\n {\n throw new NotImplementedException();\n }\n}\n\npublic class C {\n public void M() {\n Expression> expr =\n () => new Collection { 1 }; // 1\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,36): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n // () => new Collection { 1 }; // 1\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"1\").WithLocation(18, 36));\n }\n\n [Fact]\n public void CS0855ERR_ExpressionTreeContainsIndexedProperty()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\nPublic Interface I\n Property P(index As Object) As Integer\n Property Q(Optional index As Object = Nothing) As Integer\nEnd Interface\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1);\n var source2 =\n@\"using System;\nusing System.Linq.Expressions;\nclass C\n{\n static void M(I i)\n {\n Expression> e1;\n e1 = () => i.P[1];\n e1 = () => i.get_P(2); // no error\n e1 = () => i.Q;\n e1 = () => i.Q[index:3];\n Expression e2;\n e2 = () => i.P[4] = 0;\n e2 = () => i.set_P(5, 6); // no error\n }\n}\";\n var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (8,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.P[1]\").WithLocation(8, 20),\n // (10,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.Q\").WithLocation(10, 20),\n // (11,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.Q[index:3]\").WithLocation(11, 20),\n // (13,20): error CS0832: An expression tree may not contain an assignment operator\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"i.P[4] = 0\").WithLocation(13, 20),\n // (13,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.P[4]\").WithLocation(13, 20));\n }\n\n [Fact]\n [CompilerTrait(CompilerFeature.IOperation)]\n [WorkItem(23004, \"https://github.com/dotnet/roslyn/issues/23004\")]\n public void CS0856ERR_IndexedPropertyRequiresParams01()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\nPublic Interface I\n Property P(x As Object, Optional y As Object = Nothing) As Object\n Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(x As Object, Optional y As Object = Nothing) As Object\n Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object\n Property S(ParamArray args As Integer()) As Object\nEnd Interface\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1);\n var source2 =\n@\"class C\n{\n static void M(I i)\n {\n object o;\n o = i.P; // CS0856 (Dev11)\n o = i.Q;\n i.R = o; // CS0856\n i.R[1] = o; // CS1501\n o = i.S; // CS0856 (Dev11)\n i.S = o; // CS0856 (Dev11)\n }\n}\";\n var compilation2 = CreateCompilation(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (8,9): error CS0856: Indexed property 'I.R' has non-optional arguments which must be provided\n Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, \"i.R\").WithArguments(\"I.R\").WithLocation(8, 9),\n // (9,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'I.R[int, int, int]'\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"i.R[1]\").WithArguments(\"y\", \"I.R[int, int, int]\").WithLocation(9, 9));\n\n var tree = compilation2.SyntaxTrees.Single();\n var node = tree.GetRoot().DescendantNodes().OfType().First();\n\n Assert.Equal(\"i.R[1]\", node.ToString());\n\n compilation2.VerifyOperationTree(node, expectedOperationTree:\n@\"\nIInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'i.R[1]')\n Children(2):\n IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: I, IsInvalid) (Syntax: 'i')\n ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')\n\");\n }\n\n [Fact]\n public void CS0856ERR_IndexedPropertyRequiresParams02()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\nPublic Class A\n Protected ReadOnly Property P(Optional o As Object = Nothing) As Object\n Get\n Return Nothing\n End Get\n End Property\n Public ReadOnly Property P(i As Integer) As Object\n Get\n Return Nothing\n End Get\n End Property\nEnd Class\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1);\n var source2 =\n@\"class C\n{\n static object F(A a)\n {\n return a.P;\n }\n}\";\n var compilation2 = CreateCompilation(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (5,16): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided\n Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, \"a.P\").WithArguments(\"A.P\").WithLocation(5, 16));\n }\n\n [Fact]\n public void CS0857ERR_IndexedPropertyMustHaveAllOptionalParams()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\n\nPublic Interface IA\n Property P(x As Object, Optional y As Object = Nothing) As Object\n Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(x As Object, Optional y As Object = Nothing) As Object\n Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object\n Property S(ParamArray args As Integer()) As Object\nEnd Interface\nPublic Class A\n Implements IA\n Property P(x As Object, Optional y As Object = Nothing) As Object Implements IA.P\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.P\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.Q\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property Q(x As Object, Optional y As Object = Nothing) As Object Implements IA.Q\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Implements IA.R\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property S(ParamArray args As Integer()) As Object Implements IA.S\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\nEnd Class\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes);\n var source2 =\n@\"class B\n{\n static void M()\n {\n IA a;\n a = new IA() { P = null }; // CS0857 (Dev11)\n a = new IA() { Q = null };\n a = new IA() { R = null }; // CS0857\n a = new IA() { S = null }; // CS0857 (Dev11)\n }\n}\";\n var compilation2 = CreateCompilation(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (8,24): error CS0857: Indexed property 'IA.R' must have all arguments optional\n Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, \"R\").WithArguments(\"IA.R\").WithLocation(8, 24));\n }\n\n [Fact]\n public void CS1059ERR_IncrementLvalueExpected01()\n {\n var text =\n@\"enum E { A, B }\nclass C\n{\n static void M()\n {\n ++E.A; // CS1059\n E.A++; // CS1059\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 6, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 7, Column = 9 });\n }\n\n [Fact]\n public void CS1059ERR_IncrementLvalueExpected02()\n {\n var text =\n@\"class C\n{\n const int field = 0;\n static void M()\n {\n const int local = 0;\n ++local;\n local++;\n --field;\n field--;\n ++(local + 3);\n (local + 3)++;\n --2;\n 2--;\n\n dynamic d = null;\n (d + 1)++;\n --(d + 1);\n d++++;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local\"),\n // (8,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local\"),\n // (9,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"field\"),\n // (10,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"field\"),\n // (11,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local + 3\"),\n // (12,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local + 3\"),\n // (13,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"2\"),\n // (14,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"2\"),\n // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"d + 1\"),\n // (18,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"d + 1\"),\n // (19,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"d++\"));\n }\n\n [Fact]\n public void CS1059ERR_IncrementLvalueExpected03()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n ++this; // CS1059\n this--; // CS1059\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n // ++this; // CS1059\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"this\").WithArguments(\"this\"),\n // (7,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n // this--; // CS1059\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension01()\n {\n var text = @\"\npublic class TestClass1\n{\n public void WriteSomething(string s)\n {\n System.Console.WriteLine(s);\n }\n}\n\npublic class TestClass2\n{\n public void DisplaySomething(string s)\n {\n System.Console.WriteLine(s);\n }\n}\n\npublic class TestTheClasses\n{\n public static void Main()\n {\n TestClass1 tc1 = new TestClass1();\n TestClass2 tc2 = new TestClass2();\n if (tc1 == null | tc2 == null) {}\n tc1.DisplaySomething(\"\"Hello\"\"); // CS1061\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 25, Column = 13 } });\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension02()\n {\n var source =\n@\"enum E { }\nclass C\n{\n static void M(E e)\n {\n object o = e.value__;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,22): error CS1061: 'E' does not contain a definition for 'value__' and no extension method 'value__' accepting a first argument of type 'E' could be found (are you missing a using directive or an assembly reference?)\n // object o = e.value__;\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"value__\").WithArguments(\"E\", \"value__\").WithLocation(6, 22));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension03()\n {\n CreateCompilation(\n@\"class A\n{\n}\nclass B\n{\n void M()\n {\n this.F();\n this.P = this.Q;\n }\n static void M(A a)\n {\n a.F();\n a.P = a.Q;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"F\").WithArguments(\"A\", \"F\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"P\").WithArguments(\"A\", \"P\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Q\").WithArguments(\"A\", \"Q\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"F\").WithArguments(\"B\", \"F\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"P\").WithArguments(\"B\", \"P\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Q\").WithArguments(\"B\", \"Q\"));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension04()\n {\n CreateCompilation(\n@\"using System.Collections.Generic;\nclass C\n{\n static void M(List list)\n {\n object o = list.Item;\n list.Item = o;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Item\").WithArguments(\"System.Collections.Generic.List\", \"Item\").WithLocation(6, 25),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Item\").WithArguments(\"System.Collections.Generic.List\", \"Item\").WithLocation(7, 14));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension05()\n {\n CreateCompilationWithMscorlib40AndSystemCore(\n@\"using System.Linq;\n\nclass Test\n{\n static void Main()\n {\n var q = 1.Select(z => z);\n }\n}\n\")\n .VerifyDiagnostics(\n // (7,17): error CS1061: 'int' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)\n // var q = 1.Select(z => z);\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Select\").WithArguments(\"int\", \"Select\").WithLocation(7, 19));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension06()\n {\n var source =\n@\"interface I { }\nstatic class C\n{\n static void M(object o)\n {\n o.M1(o, o);\n o.M2(o, o);\n }\n static void M1(this I o, object arg) { }\n static void M2(this I o, params object[] args) { }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (6,9): error CS1501: No overload for method 'M1' takes 2 arguments\n Diagnostic(ErrorCode.ERR_BadArgCount, \"M1\").WithArguments(\"M1\", \"2\").WithLocation(6, 11),\n // (7,9): error CS1061: 'object' does not contain a definition for 'M2' and no extension method 'M2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"M2\").WithArguments(\"object\", \"M2\").WithLocation(7, 11));\n }\n\n [Fact]\n public void CS1113ERR_ValueTypeExtDelegate01()\n {\n var source =\n@\"class C\n{\n public void M() { }\n}\ninterface I\n{\n void M();\n}\nenum E\n{\n}\nstruct S\n{\n public void M() { }\n}\nstatic class SC\n{\n static void Test(C c, I i, E e, S s, double d)\n {\n System.Action cm = c.M; // OK -- instance method\n System.Action cm1 = c.M1; // OK -- extension method on ref type\n System.Action im = i.M; // OK -- instance method\n System.Action im2 = i.M2; // OK -- extension method on ref type\n System.Action em3 = e.M3; // BAD -- extension method on value type\n System.Action sm = s.M; // OK -- instance method\n System.Action sm4 = s.M4; // BAD -- extension method on value type\n System.Action dm5 = d.M5; // BAD -- extension method on value type\n }\n\n static void M1(this C c) { }\n static void M2(this I i) { }\n static void M3(this E e) { }\n static void M4(this S s) { }\n static void M5(this double d) { }\n}\";\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (24,29): error CS1113: Extension methods 'SC.M3(E)' defined on value type 'E' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"e.M3\").WithArguments(\"SC.M3(E)\", \"E\").WithLocation(24, 29),\n // (26,29): error CS1113: Extension methods 'SC.M4(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M4\").WithArguments(\"SC.M4(S)\", \"S\").WithLocation(26, 29),\n // (27,29): error CS1113: Extension methods 'SC.M5(double)' defined on value type 'double' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"d.M5\").WithArguments(\"SC.M5(double)\", \"double\").WithLocation(27, 29));\n }\n\n [Fact]\n public void CS1113ERR_ValueTypeExtDelegate02()\n {\n var source =\n@\"delegate void D();\ninterface I { }\nstruct S { }\nclass C\n{\n static void M(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)\n where T2 : class\n where T3 : struct\n where T4 : I\n where T5 : C\n {\n D d;\n d = i.M1;\n d = i.M2;\n d = s.M1;\n d = s.M2;\n d = t1.M1;\n d = t1.M2;\n d = t2.M1;\n d = t2.M2;\n d = t3.M1;\n d = t3.M2;\n d = t4.M1;\n d = t4.M2;\n d = t5.M1;\n d = t5.M2;\n }\n}\nstatic class E\n{\n internal static void M1(this T t) { }\n internal static void M2(this T t) { }\n}\";\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (13,13): error CS1113: Extension methods 'E.M1(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M1\").WithArguments(\"E.M1(int)\", \"int\").WithLocation(13, 13),\n // (14,13): error CS1113: Extension methods 'E.M2(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M2\").WithArguments(\"E.M2(int)\", \"int\").WithLocation(14, 13),\n // (15,13): error CS1113: Extension methods 'E.M1(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M1\").WithArguments(\"E.M1(S)\", \"S\").WithLocation(15, 13),\n // (16,13): error CS1113: Extension methods 'E.M2(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M2\").WithArguments(\"E.M2(S)\", \"S\").WithLocation(16, 13),\n // (17,13): error CS1113: Extension methods 'E.M1(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M1\").WithArguments(\"E.M1(T1)\", \"T1\").WithLocation(17, 13),\n // (18,13): error CS1113: Extension methods 'E.M2(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M2\").WithArguments(\"E.M2(T1)\", \"T1\").WithLocation(18, 13),\n // (21,13): error CS1113: Extension methods 'E.M1(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M1\").WithArguments(\"E.M1(T3)\", \"T3\").WithLocation(21, 13),\n // (22,13): error CS1113: Extension methods 'E.M2(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M2\").WithArguments(\"E.M2(T3)\", \"T3\").WithLocation(22, 13),\n // (23,13): error CS1113: Extension methods 'E.M1(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M1\").WithArguments(\"E.M1(T4)\", \"T4\").WithLocation(23, 13),\n // (24,13): error CS1113: Extension methods 'E.M2(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M2\").WithArguments(\"E.M2(T4)\", \"T4\").WithLocation(24, 13));\n }\n\n [WorkItem(528758, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528758\")]\n [Fact(Skip = \"528758\")]\n public void CS1113ERR_ValueTypeExtDelegate03()\n {\n var source =\n@\"delegate void D();\ninterface I { }\nstruct S { }\nclass C\n{\n static void M(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)\n where T2 : class\n where T3 : struct\n where T4 : I\n where T5 : C\n {\n F(i.M1);\n F(i.M2);\n F(s.M1);\n F(s.M2);\n F(t1.M1);\n F(t1.M2);\n F(t2.M1);\n F(t2.M2);\n F(t3.M1);\n F(t3.M2);\n F(t4.M1);\n F(t4.M2);\n F(t5.M1);\n F(t5.M2);\n }\n static void F(D d) { }\n}\nstatic class E\n{\n internal static void M1(this T t) { }\n internal static void M2(this T t) { }\n}\";\n CreateCompilation(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (12,11): error CS1113: Extension methods 'E.M1(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M1\").WithArguments(\"E.M1(int)\", \"int\").WithLocation(12, 11),\n // (13,11): error CS1113: Extension methods 'E.M2(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M2\").WithArguments(\"E.M2(int)\", \"int\").WithLocation(13, 11),\n // (14,11): error CS1113: Extension methods 'E.M1(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M1\").WithArguments(\"E.M1(S)\", \"S\").WithLocation(14, 11),\n // (15,11): error CS1113: Extension methods 'E.M2(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M2\").WithArguments(\"E.M2(S)\", \"S\").WithLocation(15, 11),\n // (16,11): error CS1113: Extension methods 'E.M1(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M1\").WithArguments(\"E.M1(T1)\", \"T1\").WithLocation(16, 11),\n // (17,11): error CS1113: Extension methods 'E.M2(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M2\").WithArguments(\"E.M2(T1)\", \"T1\").WithLocation(17, 11),\n // (20,11): error CS1113: Extension methods 'E.M1(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M1\").WithArguments(\"E.M1(T3)\", \"T3\").WithLocation(20, 11),\n // (21,11): error CS1113: Extension methods 'E.M2(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M2\").WithArguments(\"E.M2(T3)\", \"T3\").WithLocation(21, 11),\n // (22,11): error CS1113: Extension methods 'E.M1(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M1\").WithArguments(\"E.M1(T4)\", \"T4\").WithLocation(22, 11),\n // (23,11): error CS1113: Extension methods 'E.M2(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M2\").WithArguments(\"E.M2(T4)\", \"T4\").WithLocation(23, 11));\n }\n\n [Fact]\n public void CS1501ERR_BadArgCount()\n {\n var text = @\"\nusing System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n ExampleClass ec = new ExampleClass();\n ec.ExampleMethod(10, 20);\n }\n }\n\n class ExampleClass\n {\n public void ExampleMethod()\n {\n Console.WriteLine(\"\"Zero parameters\"\");\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgCount, Line = 11, Column = 16 } });\n }\n\n [Fact]\n public void CS1502ERR_BadArgTypes()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public a(char i)\n {\n }\n\n public static void Main()\n {\n a aa = new a(2222); // CS1502 & CS1503\n if (aa == null) {}\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 12, Column = 24 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 12, Column = 26 }});\n }\n\n [Fact]\n public void CS1502ERR_BadArgTypes_ConstructorInitializer()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public a() : this(\"\"string\"\") //CS1502, CS1503\n {\n }\n\n public a(char i)\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n //// (6,22): error CS1502: The best overloaded method match for 'x.a.a(char)' has some invalid arguments\n //Diagnostic(ErrorCode.ERR_BadArgTypes, \"this\").WithArguments(\"x.a.a(char)\"), //specifically omitted by roslyn\n // (6,27): error CS1503: Argument 1: cannot convert from 'string' to 'char'\n Diagnostic(ErrorCode.ERR_BadArgType, \"\\\"string\\\"\").WithArguments(\"1\", \"string\", \"char\"));\n }\n\n [Fact]\n public void CS1503ERR_BadArgType01()\n {\n var source =\n@\"namespace X\n{\n public class C\n {\n public C(int i, char c)\n {\n }\n static void M()\n {\n new C(1, 2); // CS1502 & CS1503\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,22): error CS1503: Argument 2: cannot convert from 'int' to 'char'\n // new C(1, 2); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"2\").WithArguments(\"2\", \"int\", \"char\").WithLocation(10, 22));\n }\n\n [Fact]\n public void CS1503ERR_BadArgType02()\n {\n var source =\n@\"enum E1 { A, B, C }\nenum E2 { X, Y, Z }\nclass C\n{\n static void F(int i) { }\n static void G(E1 e) { }\n static void M()\n {\n F(E1.A); // CS1502 & CS1503\n F((E2)E1.B); // CS1502 & CS1503\n F((int)E1.C);\n G(E2.X); // CS1502 & CS1503\n G((E1)E2.Y);\n G((int)E2.Z); // CS1502 & CS1503\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,11): error CS1503: Argument 1: cannot convert from 'E1' to 'int'\n // F(E1.A); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"E1.A\").WithArguments(\"1\", \"E1\", \"int\").WithLocation(9, 11),\n // (10,11): error CS1503: Argument 1: cannot convert from 'E2' to 'int'\n // F((E2)E1.B); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"(E2)E1.B\").WithArguments(\"1\", \"E2\", \"int\").WithLocation(10, 11),\n // (12,11): error CS1503: Argument 1: cannot convert from 'E2' to 'E1'\n // G(E2.X); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"E2.X\").WithArguments(\"1\", \"E2\", \"E1\").WithLocation(12, 11),\n // (14,11): error CS1503: Argument 1: cannot convert from 'int' to 'E1'\n // G((int)E2.Z); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"(int)E2.Z\").WithArguments(\"1\", \"int\", \"E1\").WithLocation(14, 11));\n }\n\n [WorkItem(538939, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538939\")]\n [Fact]\n public void CS1503ERR_BadArgType03()\n {\n var source =\n@\"class C\n{\n static void F(out int i)\n {\n i = 0;\n }\n static void M(long arg)\n {\n F(out arg); // CS1503\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,15): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'\n // F(out arg); // CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"arg\").WithArguments(\"1\", \"out long\", \"out int\").WithLocation(9, 15));\n }\n\n [Fact]\n public void CS1503ERR_BadArgType_MixedMethodsAndTypes()\n {\n var text = @\"\nclass A\n{\n public static void Goo(int x) { }\n}\nclass B : A\n{\n public class Goo { }\n}\nclass C : B\n{\n public static void Goo(string x) { }\n\n static void Main()\n {\n ((Goo))(1);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 8, Column = 16, IsWarning = true },\n new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 22, IsWarning = true },\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 16, Column = 5 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 16, Column = 13 }\n });\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_01()\n {\n var text =\n@\"class C\n{\n void M(ref int i)\n {\n M(ref 2); // CS1510, can't pass a number as a ref parameter\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_RefLvalueExpected, Line = 5, Column = 15 });\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_02()\n {\n var text =\n@\"class C\n{\n void M()\n {\n var a = new System.Action(ref x => x = 1);\n var b = new System.Action(ref (x,y) => x = 1);\n var c = new System.Action(ref delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,44): error CS1510: A ref or out argument must be an assignable variable\n // var a = new System.Action(ref x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(5, 44),\n // (6,49): error CS1510: A ref or out argument must be an assignable variable\n // var b = new System.Action(ref (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(6, 49),\n // (7,44): error CS1510: A ref or out argument must be an assignable variable\n // var c = new System.Action(ref delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(7, 44));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_03()\n {\n var text =\n@\"class C\n{\n void M()\n {\n var a = new System.Action(out x => x = 1);\n var b = new System.Action(out (x,y) => x = 1);\n var c = new System.Action(out delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,44): error CS1510: A ref or out argument must be an assignable variable\n // var a = new System.Action(out x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(5, 44),\n // (6,49): error CS1510: A ref or out argument must be an assignable variable\n // var b = new System.Action(out (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(6, 49),\n // (7,44): error CS1510: A ref or out argument must be an assignable variable\n // var c = new System.Action(out delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(7, 44));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_04()\n {\n var text =\n@\"class C\n{\n void Goo(ref System.Action t) {}\n void Goo(ref System.Action t) {}\n void M()\n {\n Goo(ref x => x = 1);\n Goo(ref (x,y) => x = 1);\n Goo(ref delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(ref x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(7, 22),\n // (8,27): error CS1510: A ref or out argument must be an assignable variable\n // Goo(ref (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(8, 27),\n // (9,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(ref delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(9, 22));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_05()\n {\n var text =\n@\"class C\n{\n void Goo(out System.Action t) {t = null;}\n void Goo(out System.Action t) {t = null;}\n void M()\n {\n Goo(out x => x = 1);\n Goo(out (x,y) => x = 1);\n Goo(out delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(out x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(7, 22),\n // (8,27): error CS1510: A ref or out argument must be an assignable variable\n // Goo(out (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(8, 27),\n // (9,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(out delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(9, 22));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_Strict()\n {\n var text =\n@\"class C\n{\n void D(int i) {}\n void M()\n {\n System.Action del = D;\n\n var a = new System.Action(ref D);\n var b = new System.Action(out D);\n var c = new System.Action(ref del);\n var d = new System.Action(out del);\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (8,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group'\n // var a = new System.Action(ref D);\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"D\").WithArguments(\"D\", \"method group\").WithLocation(8, 44),\n // (9,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group'\n // var b = new System.Action(out D);\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"D\").WithArguments(\"D\", \"method group\").WithLocation(9, 44),\n // (10,44): error CS0149: Method name expected\n // var c = new System.Action(ref del);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"del\").WithLocation(10, 44),\n // (11,44): error CS0149: Method name expected\n // var d = new System.Action(out del);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"del\").WithLocation(11, 44));\n }\n\n [Fact]\n public void CS1511ERR_BaseInStaticMeth()\n {\n var text = @\"\npublic class A\n{\n public int j = 0;\n}\n\nclass C : A\n{\n public void Method()\n {\n base.j = 3; // base allowed here\n }\n\n public static int StaticMethod()\n {\n base.j = 3; // CS1511\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInStaticMeth, Line = 16, Column = 7 } });\n }\n\n [Fact]\n public void CS1511ERR_BaseInStaticMeth_Combined()\n {\n var text = @\"\nusing System;\n\nclass CLS\n{\n static CLS() { var x = base.ToString(); }\n static object FLD = base.ToString();\n static object PROP { get { return base.ToString(); } }\n static object METHOD() { return base.ToString(); }\n}\n\nclass A : Attribute\n{\n public object P;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,25): error CS1511: Keyword 'base' is not available in a static method\n // static object FLD = base.ToString();\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (6,28): error CS1511: Keyword 'base' is not available in a static method\n // static CLS() { var x = base.ToString(); }\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (8,39): error CS1511: Keyword 'base' is not available in a static method\n // static object PROP { get { return base.ToString(); } }\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (9,37): error CS1511: Keyword 'base' is not available in a static method\n // static object METHOD() { return base.ToString(); }\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null\n // public object P;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"P\").WithArguments(\"A.P\", \"null\")\n );\n }\n\n [Fact]\n public void CS1512ERR_BaseInBadContext()\n {\n var text = @\"\nusing System;\n\nclass Base { }\n\nclass CMyClass : Base\n{\n private String xx = base.ToString(); // CS1512\n \n public static void Main()\n {\n CMyClass z = new CMyClass();\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 8, Column = 25 } });\n }\n\n [Fact]\n public void CS1512ERR_BaseInBadContext_AttributeArgument()\n {\n var text = @\"\nusing System;\n\n[assembly: A(P = base.ToString())]\n\npublic class A : Attribute\n{\n public object P;\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 4, Column = 18 } });\n }\n\n [Fact]\n public void CS1520ERR_MemberNeedsType_02()\n {\n CreateCompilation(\n@\"class Program\n{\n Main() {}\n Helper() {}\n \\u0050rogram(int x) {}\n}\")\n .VerifyDiagnostics(\n // (3,5): error CS1520: Method must have a return type\n // Main() {}\n Diagnostic(ErrorCode.ERR_MemberNeedsType, \"Main\"),\n // (4,5): error CS1520: Method must have a return type\n // Helper() {}\n Diagnostic(ErrorCode.ERR_MemberNeedsType, \"Helper\").WithLocation(4, 5)\n );\n }\n\n [Fact]\n public void CS1525ERR_InvalidExprTerm()\n {\n CreateCompilation(\n@\"public class MyClass {\n\n public static int Main() {\n bool b = string is string;\n return 1;\n }\n\n}\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"string\").WithArguments(\"string\"));\n }\n\n [WorkItem(543167, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543167\")]\n [Fact]\n public void CS1525ERR_InvalidExprTerm_1()\n {\n CreateCompilation(\n@\"class D\n{\n public static void Main()\n { \n var s = 1?;\n }\n}\n\")\n .VerifyDiagnostics(\n // (5,19): error CS1525: Invalid expression term ';'\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \";\").WithArguments(\";\"),\n // (5,19): error CS1003: Syntax error, ':' expected\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_SyntaxError, \";\").WithArguments(\":\", \";\"),\n // (5,19): error CS1525: Invalid expression term ';'\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \";\").WithArguments(\";\"),\n // (5,17): error CS0029: Cannot implicitly convert type 'int' to 'bool'\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"1\").WithArguments(\"int\", \"bool\")\n );\n }\n\n [Fact]\n public void CS1525ERR_InvalidExprTerm_ConditionalOperator()\n {\n CreateCompilation(\n@\"class Program\n{\n static void Main(string[] args)\n {\n int x = 1;\n int y = 1;\n System.Console.WriteLine(((x == y)) ?); // Invalid\n System.Console.WriteLine(((x == y)) ? (x++)); // Invalid\n System.Console.WriteLine(((x == y)) ? (x++) : (x++) : ((((y++))))); // Invalid\n System.Console.WriteLine(((x == y)) ? : :); \t// Invalid\n }\n}\n\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, \")\").WithArguments(\")\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \")\").WithArguments(\":\", \")\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \")\").WithArguments(\")\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \")\").WithArguments(\":\", \")\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \")\").WithArguments(\")\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \":\").WithArguments(\",\", \":\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \"(\").WithArguments(\",\", \"(\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \":\").WithArguments(\":\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \":\").WithArguments(\":\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \":\").WithArguments(\",\", \":\"));\n }\n\n [WorkItem(528657, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528657\")]\n [Fact]\n public void CS0106ERR_BadMemberFlag()\n {\n CreateCompilation(\n@\"new class MyClass\n{\n}\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadMemberFlag, \"MyClass\").WithArguments(\"new\"));\n }\n\n [Fact]\n public void CS1540ERR_BadProtectedAccess01()\n {\n var text = @\"\nnamespace CS1540\n{\n class Program1\n {\n static void Main()\n {\n Employee.PreparePayroll();\n }\n }\n\n class Person\n {\n protected virtual void CalculatePay() \n {\n }\n }\n\n class Manager : Person\n {\n protected override void CalculatePay() \n {\n }\n }\n\n class Employee : Person\n {\n public static void PreparePayroll()\n {\n Employee emp1 = new Employee();\n Person emp2 = new Manager();\n Person emp3 = new Employee();\n emp1.CalculatePay(); \n emp2.CalculatePay();\n emp3.CalculatePay();\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 34, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 35, Column = 18 }});\n }\n\n [Fact]\n public void CS1540ERR_BadProtectedAccess02()\n {\n var text =\n@\"class A\n{\n protected object F;\n protected void M()\n {\n }\n protected object P { get; set; }\n public object Q { get; protected set; }\n public object R { protected get; set; }\n public object S { private get; set; }\n}\nclass B : A\n{\n void M(object o)\n {\n // base.\n base.M();\n base.P = base.F;\n base.Q = null;\n M(base.R);\n M(base.S);\n // a.\n A a = new A();\n a.M();\n a.P = a.F;\n a.Q = null;\n M(a.R);\n M(a.S);\n // G().\n G().M();\n G().P = G().F;\n G().Q = null;\n M(G().R);\n M(G().S);\n // no qualifier\n M();\n P = F;\n Q = null;\n M(R);\n M(S);\n // this.\n this.M();\n this.P = this.F;\n this.Q = null;\n M(this.R);\n M(this.S);\n // ((A)this).\n ((A)this).M();\n ((A)this).P = ((A)this).F;\n ((A)this).Q = null;\n M(((A)this).R);\n M(((A)this).S);\n }\n static A G()\n {\n return null;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (21,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(base.S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"base.S\").WithArguments(\"A.S\"),\n // (24,11): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.M();\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"M\").WithArguments(\"A.M()\", \"A\", \"B\"),\n // (25,11): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.P = a.F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"P\").WithArguments(\"A.P\", \"A\", \"B\"),\n // (25,17): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.P = a.F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"F\").WithArguments(\"A.F\", \"A\", \"B\"),\n // (26,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.Q = null;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"a.Q\").WithArguments(\"A.Q\", \"A\", \"B\"),\n // (27,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // M(a.R);\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"a.R\").WithArguments(\"A.R\", \"A\", \"B\"),\n // (28,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(a.S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"a.S\").WithArguments(\"A.S\"),\n // (30,13): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().M();\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"M\").WithArguments(\"A.M()\", \"A\", \"B\"),\n // (31,13): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().P = G().F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"P\").WithArguments(\"A.P\", \"A\", \"B\"),\n // (31,21): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().P = G().F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"F\").WithArguments(\"A.F\", \"A\", \"B\"),\n // (32,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().Q = null;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"G().Q\").WithArguments(\"A.Q\", \"A\", \"B\"),\n // (33,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // M(G().R);\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"G().R\").WithArguments(\"A.R\", \"A\", \"B\"),\n // (34,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(G().S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"G().S\").WithArguments(\"A.S\"),\n // (40,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"S\").WithArguments(\"A.S\"),\n // (46,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(this.S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"this.S\").WithArguments(\"A.S\"),\n // (48,19): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).M();\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"M\").WithArguments(\"A.M()\", \"A\", \"B\"),\n // (49,19): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).P = ((A)this).F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"P\").WithArguments(\"A.P\", \"A\", \"B\"),\n // (49,33): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).P = ((A)this).F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"F\").WithArguments(\"A.F\", \"A\", \"B\"),\n // (50,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).Q = null;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"((A)this).Q\").WithArguments(\"A.Q\", \"A\", \"B\"),\n // (51,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // M(((A)this).R);\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"((A)this).R\").WithArguments(\"A.R\", \"A\", \"B\"),\n // (52,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(((A)this).S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"((A)this).S\").WithArguments(\"A.S\"),\n // (3,22): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null\n // protected object F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"A.F\", \"null\")\n );\n }\n\n [WorkItem(540271, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540271\")]\n [Fact]\n public void CS0122ERR_BadAccessProtectedCtor()\n {\n // It is illegal to access any \"protected\" instance method with a \"this\" that is not of the \n // current class's type. Oddly enough, that includes constructors. It is legal to call\n // a protected ctor via \": base()\" because then the \"this\" is of the derived type. But\n // in a derived class you cannot call \"new MyBase()\" if the ctor is protected.\n //\n // The native compiler produces the error CS1540 whether the offending method is a regular\n // method or a ctor:\n //\n // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; \n // the qualifier must be of type 'Derived' (or derived from it)\n //\n // Though technically correct, this is a very confusing error message for this scenario;\n // one does not typically think of the constructor as being a method that is \n // called with an implicit \"this\" of a particular receiver type, even though of course\n // that is exactly what it is.\n //\n // The better error message here is to simply say that the best possible ctor cannot\n // be accessed because it is not accessible. That's what Roslyn does.\n //\n // CONSIDER: We might consider making up a new error message for this situation.\n\n // \n // CS0122: 'Base.Base' is inaccessible due to its protection level\n\n var text = @\"namespace CS0122\n{\n public class Base\n {\n protected Base() {}\n }\n\n public class Derived : Base\n {\n void M()\n {\n Base b = new Base(); \n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, \"Base\").WithArguments(\"CS0122.Base.Base()\"));\n }\n\n // CS1545ERR_BindToBogusProp2 --> Symbols\\Source\\EventTests.cs\n // CS1546ERR_BindToBogusProp1 --> Symbols\\Source\\PropertyTests.cs\n\n [WorkItem(528658, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528658\")]\n [Fact()]\n public void CS1560ERR_FileNameTooLong()\n {\n var text = @\"\n#line 1 \"\"ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\"\"\n\npublic class C {\n public void Main ()\n {\n }\n}\n\";\n //EDMAURER no need to enforce a limit here.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);//,\n //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FileNameTooLong, Line = 1, Column = 25 } });\n }\n\n [Fact]\n public void CS1579ERR_ForEachMissingMember()\n {\n var text = @\"\nusing System;\npublic class MyCollection\n{\n int[] items;\n public MyCollection()\n {\n items = new int[5] { 12, 44, 33, 2, 50 };\n }\n\n MyEnumerator GetEnumerator()\n {\n return new MyEnumerator(this);\n }\n\n public class MyEnumerator\n {\n int nIndex;\n MyCollection collection;\n public MyEnumerator(MyCollection coll)\n {\n collection = coll;\n nIndex = -1;\n }\n\n public bool MoveNext()\n {\n nIndex++;\n return (nIndex < collection.items.GetLength(0));\n }\n\n public int Current\n {\n get\n {\n return (collection.items[nIndex]);\n }\n }\n }\n\n public static void Main()\n {\n MyCollection col = new MyCollection();\n Console.WriteLine(\"\"Values in the collection are:\"\");\n foreach (int i in col) // CS1579\n {\n Console.WriteLine(i);\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (45,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method.\n // foreach (int i in col) // CS1579\n Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, \"col\").WithArguments(\"MyCollection\", \"collection\", \"MyCollection.GetEnumerator()\"),\n // (45,27): error CS1579: foreach statement cannot operate on variables of type 'MyCollection' because 'MyCollection' does not contain a public definition for 'GetEnumerator'\n // foreach (int i in col) // CS1579\n Diagnostic(ErrorCode.ERR_ForEachMissingMember, \"col\").WithArguments(\"MyCollection\", \"GetEnumerator\"));\n }\n\n [Fact]\n public void CS1579ERR_ForEachMissingMember02()\n {\n var text = @\"\npublic class Test\n{\n public static void Main(string[] args)\n {\n foreach (int x in F(1)) { }\n }\n static void F(int x) { }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ForEachMissingMember, \"F(1)\").WithArguments(\"void\", \"GetEnumerator\"));\n }\n\n [Fact]\n public void CS1593ERR_BadDelArgCount()\n {\n var text = @\"\nusing System;\ndelegate string func(int i); // declare delegate\n\nclass a\n{\n public static void Main()\n {\n func dt = new func(z);\n x(dt);\n }\n\n public static string z(int j)\n {\n Console.WriteLine(j);\n return j.ToString();\n }\n\n public static void x(func hello)\n {\n hello(8, 9); // CS1593\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgCount, Line = 21, Column = 9 } });\n }\n\n [Fact]\n public void CS1593ERR_BadDelArgCount_02()\n {\n var text = @\"\ndelegate void MyDelegate1(int x, float y);\nclass Program\n{\n public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); }\n static void Main(string[] args)\n {\n Program mc = new Program();\n MyDelegate1 md1 = null;\n md1 += mc.DelegatedMethod;\n md1(1);\n md1 -= mc.DelegatedMethod;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'MyDelegate1'\n // md1(1);\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"md1\").WithArguments(\"y\", \"MyDelegate1\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS1593ERR_BadDelArgCount_03()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n static void Main()\n {\n new Action(Console.WriteLine)(1, 1);\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadDelArgCount, \"new Action(Console.WriteLine)\").WithArguments(\"System.Action\", \"2\"));\n }\n\n [Fact()]\n public void CS1594ERR_BadDelArgTypes()\n {\n var text = @\"\nusing System;\ndelegate string func(int i); // declare delegate\n\nclass a\n{\n public static void Main()\n {\n func dt = new func(z);\n x(dt);\n }\n\n public static string z(int j)\n {\n Console.WriteLine(j);\n return j.ToString();\n }\n\n public static void x(func hello)\n {\n hello(\"\"8\"\"); // CS1594\n }\n}\n\";\n //EDMAURER Giving errors for the individual argument problems is better than generic \"delegate 'blah' has some invalid arguments\"\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 21, Column = 15 } });\n //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgTypes, Line = 21, Column = 9 } });\n }\n\n // TODO: change this to CS0051 in Roslyn?\n [Fact]\n public void CS1604ERR_AssgReadonlyLocal()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n this = null;\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS1604: Cannot assign to 'this' because it is read-only\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS1605ERR_RefReadonlyLocal()\n {\n var text = @\"\nclass C\n{\n void Test()\n {\n Ref(ref this); //CS1605\n Out(out this); //CS1605\n }\n\n static void Ref(ref C c)\n {\n }\n\n static void Out(out C c)\n {\n c = null;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only\n Diagnostic(ErrorCode.ERR_RefReadonlyLocal, \"this\").WithArguments(\"this\"),\n // (7,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only\n Diagnostic(ErrorCode.ERR_RefReadonlyLocal, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS1612ERR_ReturnNotLValue01()\n {\n var text = @\"\npublic struct MyStruct\n{\n public int Width;\n}\n\npublic class ListView\n{\n MyStruct ms;\n public MyStruct Size\n {\n get { return ms; }\n set { ms = value; }\n }\n}\n\npublic class MyClass\n{\n public MyClass()\n {\n ListView lvi;\n lvi = new ListView();\n lvi.Size.Width = 5; // CS1612\n }\n\n public static void Main()\n {\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnNotLValue, Line = 23, Column = 9 } });\n }\n\n /// \n /// Breaking change from Dev10. CS1612 is now reported for all value\n /// types, not just struct types. Specifically, CS1612 is now reported\n /// for type parameters constrained to \"struct\". (See also CS0131.)\n /// \n [WorkItem(528821, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528821\")]\n [Fact]\n public void CS1612ERR_ReturnNotLValue02()\n {\n var source =\n@\"interface I\n{\n object P { get; set; }\n}\nstruct S : I\n{\n public object P { get; set; }\n}\nclass C\n where T : struct, I\n where U : class, I\n where V : I\n{\n S F1 { get; set; }\n T F2 { get; set; }\n U F3 { get; set; }\n V F4 { get; set; }\n void M()\n {\n F1.P = null;\n F2.P = null;\n F3.P = null;\n F4.P = null;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (20,9): error CS1612: Cannot modify the return value of 'C.F1' because it is not a variable\n Diagnostic(ErrorCode.ERR_ReturnNotLValue, \"F1\").WithArguments(\"C.F1\").WithLocation(20, 9),\n // (20,9): error CS1612: Cannot modify the return value of 'C.F2' because it is not a variable\n Diagnostic(ErrorCode.ERR_ReturnNotLValue, \"F2\").WithArguments(\"C.F2\").WithLocation(21, 9));\n }\n\n [Fact]\n public void CS1615ERR_BadArgExtraRef()\n {\n var text = @\"\nclass C\n{\n public void f(int i) {}\n public static void Main()\n {\n int i = 1;\n f(ref i); // CS1615\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 7 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgExtraRef, Line = 8, Column = 13 } });\n }\n\n [Fact()]\n public void CS1618ERR_DelegateOnConditional()\n {\n var text = @\"\nusing System.Diagnostics;\n\ndelegate void del();\n\nclass MakeAnError\n{\n public static void Main()\n {\n del d = new del(ConditionalMethod); // CS1618\n }\n [Conditional(\"\"DEBUG\"\")]\n public static void ConditionalMethod()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,25): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute\n // del d = new del(ConditionalMethod); // CS1618\n Diagnostic(ErrorCode.ERR_DelegateOnConditional, \"ConditionalMethod\").WithArguments(\"MakeAnError.ConditionalMethod()\").WithLocation(10, 25));\n }\n\n [Fact()]\n public void CS1618ERR_DelegateOnConditional_02()\n {\n var text = @\"\nusing System;\nusing System.Diagnostics;\n\ndelegate void del();\n\nclass MakeAnError\n{\n class Goo: Attribute\n {\n public Goo(object o) {}\n }\n\n [Conditional(\"\"DEBUG\"\")]\n [Goo(new del(ConditionalMethod))] // CS1618\n public static void ConditionalMethod()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,18): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute\n // [Goo(new del(ConditionalMethod))] // CS1618\n Diagnostic(ErrorCode.ERR_DelegateOnConditional, \"ConditionalMethod\").WithArguments(\"MakeAnError.ConditionalMethod()\").WithLocation(15, 18));\n }\n\n [Fact]\n public void CS1620ERR_BadArgRef()\n {\n var text = @\"\nclass C\n{\n void f(ref int i) { }\n public static void Main()\n {\n int x = 1;\n f(out x); // CS1620 - f takes a ref parameter, not an out parameter\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 9 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgRef, Line = 8, Column = 15 } });\n }\n\n [Fact]\n public void CS1621ERR_YieldInAnonMeth()\n {\n var text = @\"\nusing System.Collections;\n\ndelegate object MyDelegate();\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n MyDelegate d = delegate\n {\n yield return this; // CS1621\n return this;\n };\n d();\n }\n\n public static void Main()\n {\n }\n}\n\";\n var comp = CreateCompilation(text);\n var expected = new DiagnosticDescription[] {\n // (12,13): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression\n // yield return this; // CS1621\n Diagnostic(ErrorCode.ERR_YieldInAnonMeth, \"yield\"),\n // (8,24): error CS0161: 'C.GetEnumerator()': not all code paths return a value\n // public IEnumerator GetEnumerator()\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"GetEnumerator\").WithArguments(\"C.GetEnumerator()\")\n };\n comp.VerifyDiagnostics(expected);\n comp.VerifyEmitDiagnostics(expected);\n }\n\n [Fact]\n public void CS1622ERR_ReturnInIterator()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n return (IEnumerator) this; // CS1622\n yield return this; // OK\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (8,7): error CS1622: Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.\n // return (IEnumerator) this; // CS1622\n Diagnostic(ErrorCode.ERR_ReturnInIterator, \"return\"),\n // (9,7): warning CS0162: Unreachable code detected\n // yield return this; // OK\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"yield\")\n );\n }\n\n [Fact]\n public void CS1623ERR_BadIteratorArgType()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n yield return 0;\n }\n\n public IEnumerator GetEnumerator(ref int i) // CS1623\n {\n yield return i;\n }\n\n public IEnumerator GetEnumerator(out float f) // CS1623\n {\n f = 0.0F;\n yield return f;\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (11,46): error CS1623: Iterators cannot have ref, in or out parameters\n // public IEnumerator GetEnumerator(ref int i) // CS1623\n Diagnostic(ErrorCode.ERR_BadIteratorArgType, \"i\"),\n // (16,48): error CS1623: Iterators cannot have ref, in or out parameters\n // public IEnumerator GetEnumerator(out float f) // CS1623\n Diagnostic(ErrorCode.ERR_BadIteratorArgType, \"f\")\n );\n }\n\n [Fact]\n public void CS1624ERR_BadIteratorReturn()\n {\n var text = @\"\nclass C\n{\n public int Iterator\n {\n get // CS1624\n {\n yield return 1;\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIteratorReturn, Line = 6, Column = 9 } });\n }\n\n [Fact]\n public void CS1625ERR_BadYieldInFinally()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n try\n {\n }\n finally\n {\n yield return this; // CS1625\n }\n }\n}\n\npublic class CMain\n{\n public static void Main() { }\n}\n\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (13,9): error CS1625: Cannot yield in the body of a finally clause\n // yield return this; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\")\n );\n }\n\n [Fact]\n public void CS1626ERR_BadYieldInTryOfCatch()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n try\n {\n yield return this; // CS1626\n }\n catch\n {\n \n }\n }\n}\n\npublic class CMain\n{\n public static void Main() { }\n}\n\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (10,10): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return this; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\")\n );\n }\n\n [Fact]\n public void CS1628ERR_AnonDelegateCantUse()\n {\n var text = @\"\ndelegate int MyDelegate();\n\nclass C\n{\n public static void F(ref int i)\n {\n MyDelegate d = delegate { return i; }; // CS1628\n }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonDelegateCantUse, Line = 8, Column = 42 } });\n }\n\n [Fact]\n public void CS1629ERR_IllegalInnerUnsafe()\n {\n var text = @\"\nusing System.Collections.Generic;\nclass C \n{\n IEnumerator IteratorMeth() {\n int i;\n unsafe // CS1629\n {\n int *p = &i;\n yield return *p;\n }\n }\n\n unsafe IEnumerator IteratorMeth2() { // CS1629\n yield break;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,7): error CS1629: Unsafe code may not appear in iterators\n // unsafe // CS1629\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"unsafe\"),\n // (9,10): error CS1629: Unsafe code may not appear in iterators\n // int *p = &i;\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"int *\"),\n // (9,19): error CS1629: Unsafe code may not appear in iterators\n // int *p = &i;\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"&i\"),\n // (10,24): error CS1629: Unsafe code may not appear in iterators\n // yield return *p;\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"p\"),\n // (14,29): error CS1629: Unsafe code may not appear in iterators\n // unsafe IEnumerator IteratorMeth2() { // CS1629\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"IteratorMeth2\")\n );\n }\n\n [Fact]\n public void CS1631ERR_BadYieldInCatch()\n {\n var text = @\"\nusing System;\nusing System.Collections;\n\npublic class C : IEnumerable\n{\n public IEnumerator GetEnumerator() \n {\n try\n {\n }\n catch(Exception e)\n {\n yield return this; // CS1631\n }\n } \n\n public static void Main() \n {\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (14,9): error CS1631: Cannot yield a value in the body of a catch clause\n // yield return this; // CS1631\n Diagnostic(ErrorCode.ERR_BadYieldInCatch, \"yield\"),\n // (12,23): warning CS0168: The variable 'e' is declared but never used\n // catch(Exception e)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\")\n );\n }\n\n [Fact]\n public void CS1632ERR_BadDelegateLeave()\n {\n var text = @\"\ndelegate void MyDelegate();\nclass MyClass\n{\n public void Test()\n { \n for (int i = 0 ; i < 5 ; i++)\n {\n MyDelegate d = delegate {\n break; // CS1632\n }; \n }\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n// (10,13): error CS1632: Control cannot leave the body of an anonymous method or lambda expression\n// break; // CS1632\nDiagnostic(ErrorCode.ERR_BadDelegateLeave, \"break\")\n );\n }\n\n [Fact]\n public void CS1636ERR_VarargsIterator()\n {\n var text = @\"using System.Collections;\n\npublic class Test\n{\n IEnumerable Goo(__arglist)\n {\n yield return 1;\n }\n\n static int Main(string[] args)\n {\n return 1;\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n// (5,17): error CS1636: __arglist is not allowed in the parameter list of iterators\n// IEnumerable Goo(__arglist)\nDiagnostic(ErrorCode.ERR_VarargsIterator, \"Goo\"));\n }\n\n [Fact]\n public void CS1637ERR_UnsafeIteratorArgType()\n {\n var text = @\"\nusing System.Collections;\n\npublic unsafe class C\n{\n public IEnumerator Iterator1(int* p) // CS1637\n {\n yield return null;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,39): error CS1637: Iterators cannot have unsafe parameters or yield types\n Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, \"p\"));\n }\n\n [Fact()]\n public void CS1639ERR_BadCoClassSig()\n {\n // BREAKING CHANGE: Dev10 allows this test to compile, even though the output assembly is not verifiable and generates a runtime exception:\n // BREAKING CHANGE: We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error.\n\n var text = @\"\nusing System.Runtime.InteropServices;\n\n[ComImport, Guid(\"\"00020810-0000-0000-C000-000000000046\"\")]\n[CoClass(typeof(GenericClass<>))]\npublic interface InterfaceType {}\n\npublic class GenericClass: InterfaceType {}\n\npublic class Program\n{\n public static void Main() { var i = new InterfaceType(); }\n}\n \";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadCoClassSig, Line = 12, Column = 41 } }\n );\n }\n\n [Fact()]\n public void CS1640ERR_MultipleIEnumOfT()\n {\n var text = @\"\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic class C : IEnumerable, IEnumerable, IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n yield break;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n yield break;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return (IEnumerator)((IEnumerable)this).GetEnumerator();\n }\n}\n\npublic class Test\n{\n public static int Main()\n {\n foreach (int i in new C()) { } // CS1640\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MultipleIEnumOfT, Line = 27, Column = 27 } });\n }\n\n [WorkItem(7389, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS1640ERR_MultipleIEnumOfT02()\n {\n var text = @\"\nusing System.Collections.Generic;\npublic class Test\n{\n public static void Main(string[] args)\n {\n }\n}\npublic class C where T : IEnumerable, IEnumerable\n{\n public static void TestForeach(T t)\n {\n foreach (int i in t) { }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"t\").WithArguments(\"T\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\"),\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"t\").WithArguments(\"T\", \"System.Collections.Generic.IEnumerable\"));\n }\n\n [Fact]\n public void CS1643ERR_AnonymousReturnExpected()\n {\n var text = @\"\ndelegate int MyDelegate();\n\nclass C\n{\n static void Main()\n {\n MyDelegate d = delegate\n { // CS1643\n int i = 0;\n if (i == 0)\n return 1;\n };\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,24): error CS1643: Not all code paths return a value in anonymous method of type 'MyDelegate'\n // MyDelegate d = delegate\n Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, \"delegate\").WithArguments(\"anonymous method\", \"MyDelegate\").WithLocation(8, 24)\n );\n }\n\n [Fact]\n public void CS1643ERR_AnonymousReturnExpected_Foreach()\n {\n var text = @\"\nusing System;\npublic class Test\n{\n public static void Main(string[] args)\n {\n string[] arr = null;\n Func f = () => { foreach (var x in arr) return x; };\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (8,61): error CS0029: Cannot implicitly convert type 'string' to 'int'\n // Func f = () => { foreach (var x in arr) return x; };\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"x\").WithArguments(\"string\", \"int\").WithLocation(8, 61),\n // (8,61): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type\n // Func f = () => { foreach (var x in arr) return x; };\n Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, \"x\").WithArguments(\"lambda expression\").WithLocation(8, 61),\n // (8,26): error CS1643: Not all code paths return a value in lambda expression of type 'Func'\n // Func f = () => { foreach (var x in arr) return x; };\n Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, \"=>\").WithArguments(\"lambda expression\", \"System.Func\").WithLocation(8, 26)\n );\n }\n\n [Fact]\n public void CS1648ERR_AssgReadonly2()\n {\n var text = @\"\npublic struct Inner\n {\n public int i;\n }\n\nclass Outer\n{ \n public readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void Main()\n {\n Outer outer = new Outer();\n outer.inner.i = 1; // CS1648\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonly2, Line = 17, Column = 7 } });\n }\n\n [Fact]\n public void CS1649ERR_RefReadonly2()\n {\n var text = @\"\npublic struct Inner\n{\n public int i;\n}\n\nclass Outer\n{\n public readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void f(ref int iref)\n {\n }\n\n static void Main()\n {\n Outer outer = new Outer();\n f(ref outer.inner.i); // CS1649\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (21,15): error CS1649: Members of readonly field 'Outer.inner' cannot be used as a ref or out value (except in a constructor)\n // f(ref outer.inner.i); // CS1649\n Diagnostic(ErrorCode.ERR_RefReadonly2, \"outer.inner.i\").WithArguments(\"Outer.inner\").WithLocation(21, 15)\n);\n }\n\n [Fact]\n public void CS1650ERR_AssgReadonlyStatic2()\n {\n string text =\n@\"public struct Inner\n{\n public int i;\n}\n\nclass Outer\n{\n public static readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void Main()\n {\n Outer.inner.i = 1; // CS1650\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,9): error CS1650: Fields of static readonly field 'Outer.inner' cannot be assigned to (except in a static constructor or a variable initializer)\n Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, \"Outer.inner.i\").WithArguments(\"Outer.inner\"));\n }\n\n [Fact]\n public void CS1651ERR_RefReadonlyStatic2()\n {\n var text = @\"\npublic struct Inner\n{\n public int i;\n}\n\nclass Outer\n{\n public static readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void f(ref int iref)\n {\n }\n\n static void Main()\n {\n f(ref Outer.inner.i); // CS1651\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (20,15): error CS1651: Fields of static readonly field 'Outer.inner' cannot be passed ref or out (except in a static constructor)\n Diagnostic(ErrorCode.ERR_RefReadonlyStatic2, \"Outer.inner.i\").WithArguments(\"Outer.inner\"));\n }\n\n [Fact]\n public void CS1654ERR_AssgReadonlyLocal2Cause()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nnamespace CS1654\n{\n struct Book\n {\n public string Title;\n public string Author;\n public double Price;\n public Book(string t, string a, double p)\n {\n Title = t;\n Author = a;\n Price = p;\n\n }\n }\n\n class Program\n {\n List list;\n static void Main(string[] args)\n {\n Program prog = new Program();\n prog.list = new List();\n foreach (Book b in prog.list)\n {\n b.Price += 9.95; // CS1654\n }\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (29,17): error CS1654: Cannot modify members of 'b' because it is a 'foreach iteration variable'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocal2Cause, \"b.Price\").WithArguments(\"b\", \"foreach iteration variable\"));\n }\n\n [Fact]\n public void CS1655ERR_RefReadonlyLocal2Cause()\n {\n var text = @\"\nstruct S \n{\n public int i;\n}\n\nclass CMain\n{\n static void f(ref int iref)\n {\n }\n \n public static void Main()\n {\n S[] sa = new S[10];\n foreach(S s in sa)\n {\n CMain.f(ref s.i); // CS1655\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,21): error CS1655: Cannot pass fields of 's' as a ref or out argument because it is a 'foreach iteration variable'\n // CMain.f(ref s.i); // CS1655\n Diagnostic(ErrorCode.ERR_RefReadonlyLocal2Cause, \"s.i\").WithArguments(\"s\", \"foreach iteration variable\")\n );\n }\n\n [Fact]\n public void CS1656ERR_AssgReadonlyLocalCause01()\n {\n var text = @\"\nusing System;\n\nclass C : IDisposable\n{\n public void Dispose() { }\n}\n\nclass CMain\n{\n unsafe public static void Main()\n {\n using (C c = new C())\n {\n c = new C(); // CS1656\n }\n\n int[] ary = new int[] { 1, 2, 3, 4 };\n fixed (int* p = ary)\n {\n p = null; // CS1656\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (13,13): error CS1656: Cannot assign to 'c' because it is a 'using variable'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"c\").WithArguments(\"c\", \"using variable\").WithLocation(15, 13),\n // (19,13): error CS1656: Cannot assign to 'p' because it is a 'fixed variable'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"p\").WithArguments(\"p\", \"fixed variable\").WithLocation(21, 13));\n }\n\n [Fact]\n public void CS1656ERR_AssgReadonlyLocalCause02()\n {\n var text =\n@\"class C\n{\n static void M()\n {\n M = null;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,9): error CS1656: Cannot assign to 'M' because it is a 'method group'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"M\").WithArguments(\"M\", \"method group\").WithLocation(5, 9));\n }\n\n [Fact]\n public void CS1656ERR_AssgReadonlyLocalCause_NestedForeach()\n {\n var text = @\"\npublic class Test\n{\n static public void Main(string[] args)\n {\n string S = \"\"ABC\"\";\n string T = \"\"XYZ\"\";\n foreach (char x in S)\n {\n foreach (char y in T)\n {\n x = 'M';\n }\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"x\").WithArguments(\"x\", \"foreach iteration variable\"));\n }\n\n [Fact]\n public void CS1657ERR_RefReadonlyLocalCause()\n {\n var text = @\"\nclass C\n{\n static void F(ref string s)\n {\n }\n\n static void Main(string[] args)\n {\n foreach (var a in args)\n {\n F(ref a); //CS1657\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,19): error CS1657: Cannot use 'a' as a ref or out value because it is a 'foreach iteration variable'\n // F(ref a); //CS1657\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"a\").WithArguments(\"a\", \"foreach iteration variable\").WithLocation(12, 19)\n );\n }\n\n [Fact]\n public void CS1660ERR_AnonMethToNonDel()\n {\n var text = @\"\ndelegate int MyDelegate();\nclass C {\n static void Main()\n {\n int i = delegate { return 1; }; // CS1660\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethToNonDel, Line = 6, Column = 14 } });\n }\n\n [Fact]\n public void CS1661ERR_CantConvAnonMethParams()\n {\n var text = @\"\ndelegate void MyDelegate(int i);\n\nclass C\n{\n public static void Main()\n {\n MyDelegate d = delegate(string s) { }; // CS1661\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 8, Column = 24 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 8, Column = 40 }\n });\n }\n\n [Fact]\n public void CS1662ERR_CantConvAnonMethReturns()\n {\n var text = @\"\ndelegate int MyDelegate(int i);\n\nclass C\n{\n delegate double D();\n public static void Main()\n {\n MyDelegate d = delegate(int i) { return 1.0; }; // CS1662\n D dd = () => { return \"\"Who knows the real sword of Gryffindor?\"\"; };\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,49): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)\n // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1.0\").WithArguments(\"double\", \"int\").WithLocation(9, 49),\n // (9,49): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type\n // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662\n Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, \"1.0\").WithArguments(\"anonymous method\").WithLocation(9, 49),\n // (10,31): error CS0029: Cannot implicitly convert type 'string' to 'double'\n // D dd = () => { return \"Who knows the real sword of Gryffindor?\"; };\n Diagnostic(ErrorCode.ERR_NoImplicitConv, @\"\"\"Who knows the real sword of Gryffindor?\"\"\").WithArguments(\"string\", \"double\").WithLocation(10, 31),\n // (10,31): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type\n // D dd = () => { return \"Who knows the real sword of Gryffindor?\"; };\n Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @\"\"\"Who knows the real sword of Gryffindor?\"\"\").WithArguments(\"lambda expression\").WithLocation(10, 31)\n );\n }\n\n [Fact]\n public void CS1666ERR_FixedBufferNotFixedErr()\n {\n var text = @\"\nunsafe struct S\n{\n public fixed int buffer[1];\n}\n\nunsafe class Test\n{\n public static void Main()\n {\n var inst = new Test();\n System.Console.Write(inst.example1());\n System.Console.Write(inst.field.buffer[0]);\n System.Console.Write(inst.example2());\n System.Console.Write(inst.field.buffer[0]);\n }\n\n S field = new S();\n\n private int example1()\n {\n return (field.buffer[0] = 7); // OK\n }\n\n private int example2()\n {\n fixed (int* p = field.buffer)\n {\n return (p[0] = 8); // OK\n }\n }\n}\n\";\n\n CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(\n // (13,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater.\n // System.Console.Write(inst.field.buffer[0]);\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, \"inst.field.buffer\").WithArguments(\"indexing movable fixed buffers\", \"7.3\").WithLocation(13, 30),\n // (15,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater.\n // System.Console.Write(inst.field.buffer[0]);\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, \"inst.field.buffer\").WithArguments(\"indexing movable fixed buffers\", \"7.3\").WithLocation(15, 30),\n // (22,17): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater.\n // return (field.buffer[0] = 7); // OK\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, \"field.buffer\").WithArguments(\"indexing movable fixed buffers\", \"7.3\").WithLocation(22, 17)\n );\n }\n\n [Fact]\n public void CS1666ERR_FixedBufferNotUnsafeErr()\n {\n var text = @\"\nunsafe struct S\n{\n public fixed int buffer[1];\n}\n\nclass Test\n{\n public static void Main()\n {\n var inst = new Test();\n System.Console.Write(inst.example1());\n System.Console.Write(inst.field.buffer[0]);\n }\n\n S field = new S();\n\n private int example1()\n {\n return (field.buffer[0] = 7); // OK\n }\n}\n\";\n\n CreateCompilation(text, options: TestOptions.UnsafeReleaseExe).VerifyDiagnostics(\n // (13,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context\n // System.Console.Write(inst.field.buffer[0]);\n Diagnostic(ErrorCode.ERR_UnsafeNeeded, \"inst.field.buffer\").WithLocation(13, 30),\n // (20,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context\n // return (field.buffer[0] = 7); // OK\n Diagnostic(ErrorCode.ERR_UnsafeNeeded, \"field.buffer\").WithLocation(20, 17)\n );\n }\n\n [Fact]\n public void CS1666ERR_FixedBufferNotFixed()\n {\n var text = @\"\nunsafe struct S\n{\n public fixed int buffer[1];\n}\n\nunsafe class Test\n{\n public static void Main()\n {\n var inst = new Test();\n System.Console.Write(inst.example1());\n System.Console.Write(inst.field.buffer[0]);\n System.Console.Write(inst.example2());\n System.Console.Write(inst.field.buffer[0]);\n }\n\n S field = new S();\n\n private int example1()\n {\n return (field.buffer[0] = 7); // OK\n }\n\n private int example2()\n {\n fixed (int* p = field.buffer)\n {\n return (p[0] = 8); // OK\n }\n }\n}\n\";\n\n var c = CompileAndVerify(text, expectedOutput: \"7788\", verify: Verification.Fails, options: TestOptions.UnsafeReleaseExe);\n\n c.VerifyIL(\"Test.example1()\", @\"\n{\n // Code size 22 (0x16)\n .maxstack 3\n .locals init (int V_0)\n IL_0000: ldarg.0\n IL_0001: ldflda \"\"S Test.field\"\"\n IL_0006: ldflda \"\"int* S.buffer\"\"\n IL_000b: ldflda \"\"int S.e__FixedBuffer.FixedElementField\"\"\n IL_0010: ldc.i4.7\n IL_0011: dup\n IL_0012: stloc.0\n IL_0013: stind.i4\n IL_0014: ldloc.0\n IL_0015: ret\n}\n\");\n\n c.VerifyIL(\"Test.example2()\", @\"\n{\n // Code size 25 (0x19)\n .maxstack 3\n .locals init (pinned int& V_0,\n int V_1)\n IL_0000: ldarg.0\n IL_0001: ldflda \"\"S Test.field\"\"\n IL_0006: ldflda \"\"int* S.buffer\"\"\n IL_000b: ldflda \"\"int S.e__FixedBuffer.FixedElementField\"\"\n IL_0010: stloc.0\n IL_0011: ldloc.0\n IL_0012: conv.u\n IL_0013: ldc.i4.8\n IL_0014: dup\n IL_0015: stloc.1\n IL_0016: stind.i4\n IL_0017: ldloc.1\n IL_0018: ret\n}\n\");\n }\n\n [Fact]\n public void CS1669ERR_IllegalVarArgs01()\n {\n var source =\n@\"class C \n{\n delegate void D(__arglist); // CS1669\n static void Main() {}\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,21): error CS1669: __arglist is not valid in this context\n // delegate void D(__arglist); // CS1669\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\")\n );\n }\n\n [Fact]\n public void CS1669ERR_IllegalVarArgs02()\n {\n var source =\n@\"class C\n{\n object this[object index, __arglist]\n {\n get { return null; }\n }\n public static C operator +(C c1, __arglist) { return c1; }\n public static implicit operator int(__arglist) { return 0; }\n\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,31): error CS1669: __arglist is not valid in this context\n // object this[object index, __arglist]\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\"),\n\n // (7,38): error CS1669: __arglist is not valid in this context\n // public static C operator +(C c1, __arglist) { return c1; }\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\"),\n\n // (8,41): error CS1669: __arglist is not valid in this context\n // public static implicit operator int(__arglist) { return 0; }\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\")\n );\n }\n\n [WorkItem(863433, \"DevDiv/Personal\")]\n [Fact]\n public void CS1670ERR_IllegalParams()\n {\n // TODO: extra 1670 (not check for now)\n var test = @\"\ndelegate int MyDelegate(params int[] paramsList);\nclass Test\n{\n public static int Main()\n {\n MyDelegate d = delegate(params int[] paramsList) // CS1670\n {\n return paramsList[0];\n }; \n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IllegalParams, Line = 7, Column = 33 } });\n }\n\n [Fact]\n public void CS1673ERR_ThisStructNotInAnonMeth01()\n {\n var text = @\"\ndelegate int MyDelegate();\n\npublic struct S\n{\n int member;\n\n public int F(int i)\n {\n member = i;\n MyDelegate d = delegate()\n {\n i = this.member; // CS1673\n return i;\n\n };\n return d();\n }\n}\n\nclass CMain\n{\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } });\n }\n\n [Fact]\n public void CS1673ERR_ThisStructNotInAnonMeth02()\n {\n var text = @\"\ndelegate int MyDelegate();\n\npublic struct S\n{\n int member;\n\n public int F(int i)\n {\n member = i;\n MyDelegate d = delegate()\n {\n i = member; // CS1673\n return i;\n\n };\n return d();\n }\n}\n\nclass CMain\n{\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } });\n }\n\n [Fact]\n public void CS1674ERR_NoConvToIDisp()\n {\n var text = @\"\nclass C\n{\n public static void Main()\n {\n using (int a = 0) // CS1674\n using (a); //CS1674\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,22): warning CS0642: Possible mistaken empty statement\n Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, \";\"),\n // (6,16): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'.\n Diagnostic(ErrorCode.ERR_NoConvToIDisp, \"int a = 0\").WithArguments(\"int\"),\n // (7,20): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'.\n Diagnostic(ErrorCode.ERR_NoConvToIDisp, \"a\").WithArguments(\"int\"));\n }\n\n [Fact]\n public void CS1676ERR_BadParamRef()\n {\n var text = @\"\ndelegate void E(ref int i);\nclass Errors \n{\n static void Main()\n {\n E e = delegate(out int i) { }; // CS1676\n }\n}\n\";\n var compilation = CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (7,13): error CS1661: Cannot convert anonymous method to delegate type 'E' because the parameter types do not match the delegate parameter types\n // E e = delegate(out int i) { }; // CS1676\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate(out int i) { }\").WithArguments(\"anonymous method\", \"E\"),\n // (7,22): error CS1676: Parameter 1 must be declared with the 'ref' keyword\n // E e = delegate(out int i) { }; // CS1676\n Diagnostic(ErrorCode.ERR_BadParamRef, \"i\").WithArguments(\"1\", \"ref\"),\n // (7,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method\n // E e = delegate(out int i) { }; // CS1676\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"delegate(out int i) { }\").WithArguments(\"i\")\n );\n }\n\n [Fact]\n public void CS1677ERR_BadParamExtraRef()\n {\n var text = @\"\ndelegate void D(int i);\nclass Errors\n{\n static void Main()\n {\n D d = delegate(out int i) { }; // CS1677\n D d = delegate(ref int j) { }; // CS1677\n }\n}\n\";\n var compilation = CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (7,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types\n // D d = delegate(out int i) { }; // CS1677\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate(out int i) { }\").WithArguments(\"anonymous method\", \"D\"),\n // (7,24): error CS1677: Parameter 1 should not be declared with the 'out' keyword\n // D d = delegate(out int i) { }; // CS1677\n Diagnostic(ErrorCode.ERR_BadParamExtraRef, \"i\").WithArguments(\"1\", \"out\"),\n // (8,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types\n // D d = delegate(ref int j) { }; // CS1677\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate(ref int j) { }\").WithArguments(\"anonymous method\", \"D\"),\n // (8,24): error CS1677: Parameter 1 should not be declared with the 'ref' keyword\n // D d = delegate(ref int j) { }; // CS1677\n Diagnostic(ErrorCode.ERR_BadParamExtraRef, \"j\").WithArguments(\"1\", \"ref\"),\n // (8,11): error CS0128: A local variable named 'd' is already defined in this scope\n // D d = delegate(ref int j) { }; // CS1677\n Diagnostic(ErrorCode.ERR_LocalDuplicate, \"d\").WithArguments(\"d\"),\n // (7,15): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method\n // D d = delegate(out int i) { }; // CS1677\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"delegate(out int i) { }\").WithArguments(\"i\")\n );\n }\n\n [Fact]\n public void CS1678ERR_BadParamType()\n {\n var text = @\"\ndelegate void D(int i);\nclass Errors\n{\n static void Main()\n {\n D d = delegate(string s) { }; // CS1678\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 7, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 7, Column = 31 }\n });\n }\n\n [Fact]\n public void CS1681ERR_GlobalExternAlias()\n {\n var text = @\"\nextern alias global;\n\nclass myClass\n{\n static int Main()\n {\n //global::otherClass oc = new global::otherClass();\n return 0;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (2,14): error CS1681: You cannot redefine the global extern alias\n // extern alias global;\n Diagnostic(ErrorCode.ERR_GlobalExternAlias, \"global\"),\n // (2,14): error CS0430: The extern alias 'global' was not specified in a /reference option\n // extern alias global;\n Diagnostic(ErrorCode.ERR_BadExternAlias, \"global\").WithArguments(\"global\"),\n // (2,1): info CS8020: Unused extern alias.\n // extern alias global;\n Diagnostic(ErrorCode.HDN_UnusedExternAlias, \"extern alias global;\")\n );\n }\n\n [Fact]\n public void CS1686ERR_LocalCantBeFixedAndHoisted()\n {\n var text = @\"\nclass MyClass\n{\n public unsafe delegate int* MyDelegate();\n\n public unsafe int* Test()\n {\n int j = 0;\n MyDelegate d = delegate { return &j; }; // CS1686\n return &j; // CS1686\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,42): error CS1686: Local 'j' or its members cannot have their address taken and be used inside an anonymous method or lambda expression\n // MyDelegate d = delegate { return &j; }; // CS1686\n Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, \"&j\").WithArguments(\"j\"));\n }\n\n [Fact]\n public void CS1686ERR_LocalCantBeFixedAndHoisted02()\n {\n var text = @\"using System;\n\nunsafe struct S\n{\n public fixed int buffer[1];\n public int i;\n}\n\nunsafe class Test\n{\n private void example1()\n {\n S data = new S();\n data.i = data.i + 1;\n Func lambda = () => data;\n fixed (int* p = data.buffer) // fail due to receiver being a local\n {\n }\n int *q = data.buffer; // fail due to lambda capture\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (16,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression\n // fixed (int* p = data.buffer) // fail due to receiver being a local\n Diagnostic(ErrorCode.ERR_FixedNotNeeded, \"data.buffer\"),\n // (19,18): error CS1686: Local 'data' or its members cannot have their address taken and be used inside an anonymous method or lambda expression\n // int *q = data.buffer; // fail due to lambda capture\n Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, \"data.buffer\").WithArguments(\"data\")\n );\n }\n\n [WorkItem(580537, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580537\")]\n [Fact]\n public void CS1686ERR_LocalCantBeFixedAndHoisted03()\n {\n var text = @\"unsafe\npublic struct Test\n{\n private delegate int D();\n public fixed int i[1];\n public void example()\n {\n Test t = this;\n t.i[0] = 5;\n D d = delegate {\n var x = t;\n return 0;\n };\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,9): error CS1686: Local 't' or its members cannot have their address taken and be used inside an anonymous method or lambda expression\n // t.i[0] = 5;\n Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, \"t.i\").WithArguments(\"t\")\n );\n }\n\n [Fact]\n public void CS1688ERR_CantConvAnonMethNoParams()\n {\n var text = @\"\nusing System;\ndelegate void OutParam(out int i);\nclass ErrorCS1676\n{\n static void Main()\n {\n OutParam o;\n o = delegate // CS1688\n {\n Console.WriteLine(\"\");\n };\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,31): error CS1010: Newline in constant\n // Console.WriteLine(\");\n Diagnostic(ErrorCode.ERR_NewlineInConst, \"\").WithLocation(11, 31),\n // (11,34): error CS1026: ) expected\n // Console.WriteLine(\");\n Diagnostic(ErrorCode.ERR_CloseParenExpected, \"\").WithLocation(11, 34),\n // (11,34): error CS1002: ; expected\n // Console.WriteLine(\");\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(11, 34),\n // (9,13): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'OutParam' because it has one or more out parameters\n // o = delegate // CS1688\n Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, @\"delegate // CS1688\n {\n Console.WriteLine(\"\");\n }\").WithArguments(\"OutParam\").WithLocation(9, 13)\n );\n }\n\n [Fact]\n public void CS1708ERR_FixedNeedsLvalue()\n {\n var text = @\"\nunsafe public struct S\n{\n public fixed char name[10];\n}\n\npublic unsafe class C\n{\n public S UnsafeMethod()\n {\n S myS = new S();\n return myS;\n }\n\n static void Main()\n {\n C myC = new C();\n myC.UnsafeMethod().name[3] = 'a'; // CS1708\n C._s1.name[3] = 'a'; // CS1648\n myC._s2.name[3] = 'a'; // CS1648\n }\n\n static readonly S _s1;\n public readonly S _s2;\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (18,9): error CS1708: Fixed size buffers can only be accessed through locals or fields\n // myC.UnsafeMethod().name[3] = 'a'; // CS1708\n Diagnostic(ErrorCode.ERR_FixedNeedsLvalue, \"myC.UnsafeMethod().name\").WithLocation(18, 9),\n // (19,9): error CS1650: Fields of static readonly field 'C._s1' cannot be assigned to (except in a static constructor or a variable initializer)\n // C._s1.name[3] = 'a'; // CS1648\n Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, \"C._s1.name[3]\").WithArguments(\"C._s1\").WithLocation(19, 9),\n // (20,9): error CS1648: Members of readonly field 'C._s2' cannot be modified (except in a constructor, an init-only member or a variable initializer)\n // myC._s2.name[3] = 'a'; // CS1648\n Diagnostic(ErrorCode.ERR_AssgReadonly2, \"myC._s2.name[3]\").WithArguments(\"C._s2\").WithLocation(20, 9)\n );\n }\n\n [Fact, WorkItem(543995, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543995\"), WorkItem(544258, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258\")]\n public void CS1728ERR_DelegateOnNullable()\n {\n var text = @\"\nusing System;\nclass Test\n{\n static void Main()\n {\n int? x = null;\n\n Func f1 = x.ToString; // no error\n Func f2 = x.GetHashCode; // no error\n Func f3 = x.Equals; // no error\n Func f4 = x.GetType; // no error\n\n Func x1 = x.GetValueOrDefault; // 1728\n Func x2 = x.GetValueOrDefault; // 1728\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (14,24): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault()' because it is a member of 'System.Nullable'\n // Func x1 = x.GetValueOrDefault; // 1728\n Diagnostic(ErrorCode.ERR_DelegateOnNullable, \"x.GetValueOrDefault\").WithArguments(\"int?.GetValueOrDefault()\"),\n // (15,29): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault(int)' because it is a member of 'System.Nullable'\n // Func x2 = x.GetValueOrDefault; // 1728\n Diagnostic(ErrorCode.ERR_DelegateOnNullable, \"x.GetValueOrDefault\").WithArguments(\"int?.GetValueOrDefault(int)\")\n );\n }\n\n [Fact, WorkItem(999399, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399\")]\n public void CS1729ERR_BadCtorArgCount()\n {\n var text = @\"\nclass Test\n{\n static int Main()\n {\n double d = new double(4.5); // was CS0143 (Dev10)\n Test test1 = new Test(2); // CS1729\n Test test2 = new Test();\n Parent exampleParent1 = new Parent(10); // CS1729\n Parent exampleParent2 = new Parent(10, 1);\n if (test1 == test2 & exampleParent1 == exampleParent2) {}\n return 1;\n }\n}\n\npublic class Parent\n{\n public Parent(int i, int j) { }\n}\n\npublic class Child : Parent { } // CS1729\n\npublic class Child2 : Parent\n{\n public Child2(int k)\n : base(k, 0)\n {\n }\n}\";\n var compilation = CreateCompilation(text);\n\n DiagnosticDescription[] expected = {\n // (21,14): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Parent.Parent(int, int)'\n // public class Child : Parent { } // CS1729\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"Child\").WithArguments(\"i\", \"Parent.Parent(int, int)\").WithLocation(21, 14),\n // (6,24): error CS1729: 'double' does not contain a constructor that takes 1 arguments\n // double d = new double(4.5); // was CS0143 (Dev10)\n Diagnostic(ErrorCode.ERR_BadCtorArgCount, \"double\").WithArguments(\"double\", \"1\").WithLocation(6, 24),\n // (7,26): error CS1729: 'Test' does not contain a constructor that takes 1 arguments\n // Test test1 = new Test(2); // CS1729\n Diagnostic(ErrorCode.ERR_BadCtorArgCount, \"Test\").WithArguments(\"Test\", \"1\").WithLocation(7, 26),\n // (9,37): error CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'Parent.Parent(int, int)'\n // Parent exampleParent1 = new Parent(10); // CS1729\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"Parent\").WithArguments(\"j\", \"Parent.Parent(int, int)\").WithLocation(9, 37)\n };\n\n compilation.VerifyDiagnostics(expected);\n\n compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single(), filterSpanWithinTree: null, includeEarlierStages: true).Verify(expected);\n }\n\n [WorkItem(539631, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539631\")]\n [Fact]\n public void CS1729ERR_BadCtorArgCount02()\n {\n var text = @\"\nclass MyClass\n{\n int intI = 1;\n MyClass()\n {\n intI = 2;\n }\n\n //this constructor initializer\n MyClass(int intJ) : this(3, 4) // CS1729\n {\n intI = intI * intJ;\n }\n}\n\nclass MyBase\n{\n public int intI = 1;\n protected MyBase()\n {\n intI = 2;\n }\n protected MyBase(int intJ)\n {\n intI = intJ;\n }\n}\n\nclass MyDerived : MyBase\n{\n MyDerived() : base(3, 4) // CS1729\n {\n intI = intI * 2;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 11, Column = 25 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 32, Column = 19 });\n }\n\n [Fact]\n public void CS1737ERR_DefaultValueBeforeRequiredValue()\n {\n var text = @\"\nclass C\n{\n public void Goo(string s = null, int x)\n {\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueBeforeRequiredValue, Line = 4, Column = 43 } } //sic: error on close paren\n );\n }\n\n [WorkItem(539007, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539007\")]\n [Fact]\n public void DevDiv4792_OptionalBeforeParams()\n {\n var text = @\"\nclass C\n{\n public void Goo(string s = null, params int[] ints)\n {\n }\n}\n\";\n //no errors\n var comp = CreateCompilation(text);\n Assert.False(comp.GetDiagnostics().Any());\n }\n\n [WorkItem(527351, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527351\")]\n [Fact]\n public void CS1738ERR_NamedArgumentSpecificationBeforeFixedArgument()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(age: 5,\"\"\"\");\n return 0;\n }\n public static void Test(int age, string Name)\n { }\n}\";\n var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6);\n comp.VerifyDiagnostics(\n // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.\n // Test(age: 5,\"\");\n Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, @\"\"\"\"\"\").WithArguments(\"7.2\").WithLocation(6, 21)\n );\n }\n\n [Fact]\n public void CS1739ERR_BadNamedArgument()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(5,Nam:null);\n return 0;\n }\n public static void Test(int age , string Name)\n { }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } });\n }\n\n [Fact, WorkItem(866112, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866112\")]\n public void CS1739ERR_BadNamedArgument_1()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(1, 2, Name:3);\n }\n\n public static void Test(params int [] array)\n { }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } });\n }\n\n [Fact]\n public void CS1740ERR_DuplicateNamedArgument()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(age: 5, Name: \"\"5\"\", Name: \"\"\"\");\n return 0;\n }\n public static void Test(int age, string Name)\n {\n }\n}\";\n var compilation = CSharpTestBase.CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (6,33): error CS1740: Named argument 'Name' cannot be specified multiple times\n // Test(age: 5, Name: \"5\", Name: \"\");\n Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, \"Name\").WithArguments(\"Name\").WithLocation(6, 33));\n }\n\n [Fact]\n public void CS1742ERR_NamedArgumentForArray()\n {\n var text = @\"\npublic class B\n{\n static int Main()\n {\n int[] arr = { };\n int s = arr[arr: 1];\n s = s + 1;\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1742, Line = 7, Column = 17 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(5, age: 3);\n return 0;\n }\n public static void Test(int age , string Name)\n { }\n}\";\n // CS1744: Named argument 'q' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 21 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional2()\n {\n // Unfortunately we allow \"void M(params int[] x)\" to be called in the expanded\n // form as \"M(x : 123);\". However, we still do not allow \"M(123, x:456);\".\n\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(5, x: 3);\n }\n public static void Test(params int[] x) { }\n}\";\n // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional3()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(5, x : 6);\n }\n public static void Test(int x, int y = 10, params int[] z) { }\n}\";\n // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional4()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(5, 6, 7, 8, 9, 10, z : 6);\n }\n public static void Test(int x, int y = 10, params int[] z) { }\n}\";\n // CS1744: Named argument 'z' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 33 } });\n }\n\n [Fact]\n public void CS1746ERR_BadNamedArgumentForDelegateInvoke()\n {\n var text = @\"\npublic class C\n{\n delegate int MyDg(int age);\n public static int Main()\n {\n MyDg dg = new MyDg(Test);\n int S = dg(Ne: 3);\n return 0;\n }\n public static int Test(int age)\n { return 1; }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1746, Line = 8, Column = 24 } });\n }\n\n // [Fact()]\n // public void CS1752ERR_FixedNeedsLvalue()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FixedNeedsLvalue, Line = 20, Column = 9 } }\n // );\n // }\n\n // CS1912 --> ObjectAndCollectionInitializerTests.cs\n // CS1913 --> ObjectAndCollectionInitializerTests.cs\n // CS1914 --> ObjectAndCollectionInitializerTests.cs\n // CS1917 --> ObjectAndCollectionInitializerTests.cs\n // CS1918 --> ObjectAndCollectionInitializerTests.cs\n // CS1920 --> ObjectAndCollectionInitializerTests.cs\n // CS1921 --> ObjectAndCollectionInitializerTests.cs\n // CS1922 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1919ERR_UnsafeTypeInObjectCreation()\n {\n var text = @\"\nunsafe public class C\n{\n public static int Main()\n {\n var col1 = new int*(); // CS1919\n var col2 = new char*(); // CS1919\n return 1;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,20): error CS1919: Unsafe type 'int*' cannot be used in object creation\n Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, \"new int*()\").WithArguments(\"int*\"),\n // (7,20): error CS1919: Unsafe type 'char*' cannot be used in object creation\n Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, \"new char*()\").WithArguments(\"char*\"));\n }\n\n [Fact]\n public void CS1928ERR_BadExtensionArgTypes()\n {\n var text =\n@\"class C\n{\n static void M(float f)\n {\n f.F();\n }\n}\nstatic class S\n{\n internal static void F(this double d) { }\n}\";\n var compilation = CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore });\n // Previously ERR_BadExtensionArgTypes.\n compilation.VerifyDiagnostics(\n // (5,9): error CS1929: 'float' does not contain a definition for 'F' and the best extension method overload 'S.F(double)' requires a receiver of type 'double'\n // f.F();\n Diagnostic(ErrorCode.ERR_BadInstanceArgType, \"f\").WithArguments(\"float\", \"F\", \"S.F(double)\", \"double\").WithLocation(5, 9));\n }\n\n [Fact]\n public void CS1929ERR_BadInstanceArgType()\n {\n var source = @\"class A { }\nclass B : A\n{\n static void M(A a)\n {\n a.E();\n }\n}\nstatic class S\n{\n internal static void E(this B b) { }\n}\";\n var compilation = CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore });\n compilation.VerifyDiagnostics(\n // (6,9): error CS1929: 'A' does not contain a definition for 'E' and the best extension method overload 'S.E(B)' requires a receiver of type 'B'\n // a.E();\n Diagnostic(ErrorCode.ERR_BadInstanceArgType, \"a\").WithArguments(\"A\", \"E\", \"S.E(B)\", \"B\").WithLocation(6, 9)\n );\n }\n\n [Fact]\n public void CS1930ERR_QueryDuplicateRangeVariable()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Program\n{\n static void Main()\n {\n int[] nums = { 0, 1, 2, 3, 4, 5 };\n var query = from num in nums\n let num = 3 // CS1930\n select num; \n }\n}\n\").VerifyDiagnostics(\n // (10,25): error CS1930: The range variable 'num' has already been declared\n Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, \"num\").WithArguments(\"num\"));\n }\n\n [Fact]\n public void CS1931ERR_QueryRangeVariableOverrides01()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\n\nclass Test\n{\n static void Main()\n {\n int x = 1;\n var y = from x in Enumerable.Range(1, 100) // CS1931\n select x + 1;\n }\n}\n\").VerifyDiagnostics(\n // (9,22): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'\n // var y = from x in Enumerable.Range(1, 100) // CS1931\n Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, \"x\").WithArguments(\"x\"),\n // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used\n // int x = 1;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = null\n select i;\n }\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign to a range variable\n // let k = null\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = null\").WithArguments(\"\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue02()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = ()=>3\n select i;\n }\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign lambda expression to a range variable\n // let k = ()=>3\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = ()=>3\").WithArguments(\"lambda expression\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue03()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = Main\n select i;\n }\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign method group to a range variable\n // let k = Main\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = Main\").WithArguments(\"method group\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue04()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = M()\n select i;\n }\n static void M() {}\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign void to a range variable\n // let k = M()\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = M()\").WithArguments(\"void\")\n );\n }\n\n [WorkItem(528756, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756\")]\n [Fact()]\n public void CS1933ERR_QueryNotAllowed()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nusing System.Collections;\n\nclass P\n{\n const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933\n static int Main()\n {\n return 1;\n }\n}\n\").VerifyDiagnostics(\n // EDMAURER now giving the more generic message CS0133\n // (7,27): error CS1933: Expression cannot contain query expressions\n // from\n //Diagnostic(ErrorCode.ERR_QueryNotAllowed, \"from\").WithArguments());\n\n // (7,27): error CS0133: The expression being assigned to 'P.e' must be constant\n // const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"from x in new int[] { 1, 2, 3 } select x\").WithArguments(\"P.e\")\n );\n }\n\n [Fact]\n public void CS1934ERR_QueryNoProviderCastable()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nusing System.Collections;\nstatic class Test\n{\n public static void Main()\n {\n var list = new ArrayList();\n var q = from x in list // CS1934\n select x + 1;\n }\n}\n\").VerifyDiagnostics(\n // (9,27): error CS1934: Could not find an implementation of the query pattern for source type 'System.Collections.ArrayList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'x'.\n // list\n Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, \"list\").WithArguments(\"System.Collections.ArrayList\", \"Select\", \"x\"));\n }\n\n [Fact]\n public void CS1935ERR_QueryNoProviderStandard()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Collections.Generic;\nclass Test\n{\n static int Main()\n {\n int[] nums = { 0, 1, 2, 3, 4, 5 };\n IEnumerable e = from n in nums\n where n > 3\n select n;\n return 0;\n }\n}\n\").VerifyDiagnostics(\n // (8,40): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Where' not found. Are you missing required assembly references or a using directive for 'System.Linq'?\n // nums\n Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, \"nums\").WithArguments(\"int[]\", \"Where\"));\n }\n\n [Fact]\n public void CS1936ERR_QueryNoProvider()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Collections;\nusing System.Linq;\nclass Test\n{\n static int Main()\n {\n object obj = null;\n IEnumerable e = from x in obj // CS1936\n select x;\n return 0;\n }\n}\n\").VerifyDiagnostics(\n // (10,35): error CS1936: Could not find an implementation of the query pattern for source type 'object'. 'Select' not found.\n // obj\n Diagnostic(ErrorCode.ERR_QueryNoProvider, \"obj\").WithArguments(\"object\", \"Select\"));\n }\n\n [Fact]\n public void CS1936ERR_QueryNoProvider01()\n {\n var program = @\"\nclass X\n{\n internal X Cast() { return this; }\n}\nclass Program\n{\n static void Main()\n {\n var xx = new X();\n var q3 = from int x in xx select x;\n }\n}\";\n var comp = CreateCompilation(program);\n comp.VerifyDiagnostics(\n // (11,32): error CS1936: Could not find an implementation of the query pattern for source type 'X'. 'Select' not found.\n // var q3 = from int x in xx select x;\n Diagnostic(ErrorCode.ERR_QueryNoProvider, \"xx\").WithArguments(\"X\", \"Select\")\n );\n }\n\n [Fact]\n public void CS1937ERR_QueryOuterKey()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] sourceA = { 1, 2, 3, 4, 5 };\n int[] sourceB = { 3, 4, 5, 6, 7 };\n\n var query = from a in sourceA\n join b in sourceB on b equals 5 // CS1937\n select a + b;\n }\n}\n\").VerifyDiagnostics(\n // (11,42): error CS1937: The name 'b' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.\n // join b in sourceB on b equals 5 // CS1937\n Diagnostic(ErrorCode.ERR_QueryOuterKey, \"b\").WithArguments(\"b\")\n );\n }\n\n [Fact]\n public void CS1938ERR_QueryInnerKey()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] sourceA = { 1, 2, 3, 4, 5 };\n int[] sourceB = { 3, 4, 5, 6, 7 };\n\n var query = from a in sourceA\n join b in sourceB on 5 equals a // CS1938\n select a + b;\n }\n}\n\").VerifyDiagnostics(\n // (11,51): error CS1938: The name 'a' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.\n // join b in sourceB on 5 equals a // CS1938\n Diagnostic(ErrorCode.ERR_QueryInnerKey, \"a\").WithArguments(\"a\")\n );\n }\n\n [Fact]\n public void CS1939ERR_QueryOutRefRangeVariable()\n {\n var text = @\"\nusing System.Linq;\nclass Test\n{\n public static int F(ref int i) { return i; }\n public static void Main()\n {\n var list = new int[] { 0, 1, 2, 3, 4, 5 };\n var q = from x in list\n let k = x\n select Test.F(ref x); // CS1939\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,35): error CS1939: Cannot pass the range variable 'x' as an out or ref parameter\n // select Test.F(ref x); // CS1939\n Diagnostic(ErrorCode.ERR_QueryOutRefRangeVariable, \"x\").WithArguments(\"x\"));\n }\n\n [Fact]\n public void CS1940ERR_QueryMultipleProviders()\n {\n var text =\n@\"using System; \nclass Test\n{\n public delegate int Dele(int x);\n int num = 0;\n public int Select(Func d)\n {\n return d(this.num);\n }\n public int Select(Dele d) \n {\n return d(this.num) + 1;\n }\n public static void Main()\n {\n var q = from x in new Test()\n select x; // CS1940\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (18,17): error CS1940: Multiple implementations of the query pattern were found for source type 'Test'. Ambiguous call to 'Select'.\n // select\n Diagnostic(ErrorCode.ERR_QueryMultipleProviders, \"select x\").WithArguments(\"Test\", \"Select\")\n );\n }\n\n [Fact]\n public void CS1941ERR_QueryTypeInferenceFailedMulti()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Collections;\nusing System.Linq;\nclass Test\n{\n static int Main()\n {\n var nums = new int[] { 1, 2, 3, 4, 5, 6 };\n var words = new string[] { \"\"lake\"\", \"\"mountain\"\", \"\"sky\"\" };\n IEnumerable e = from n in nums\n join w in words on n equals w // CS1941\n select w;\n return 0;\n }\n}\n\").VerifyDiagnostics(\n // (11,25): error CS1941: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.\n // join\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedMulti, \"join\").WithArguments(\"join\", \"Join\"));\n }\n\n [Fact]\n public void CS1942ERR_QueryTypeInferenceFailed()\n {\n var text = @\"\nusing System;\nclass Q\n{\n public Q Select(Func func) { return this; }\n}\nclass Program\n{\n static void Main(string[] args)\n {\n var x = from i in new Q()\n select i; //CS1942\n }\n}\n\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (12,17): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.\n // select i; //CS1942\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, \"select\").WithArguments(\"select\", \"Select\")\n );\n }\n\n [Fact]\n public void CS1943ERR_QueryTypeInferenceFailedSelectMany()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n class TestClass\n { }\n static void Main()\n {\n int[] nums = { 0, 1, 2, 3, 4, 5 };\n TestClass tc = new TestClass();\n \n var x = from n in nums\n from s in tc // CS1943\n select n + s;\n }\n}\n\").VerifyDiagnostics(\n // (13,27): error CS1943: An expression of type 'Test.TestClass' is not allowed in a subsequent from clause in a query expression with source type 'int[]'. Type inference failed in the call to 'SelectMany'.\n // tc\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, \"tc\").WithArguments(\"Test.TestClass\", \"int[]\", \"SelectMany\"));\n }\n\n [Fact]\n public void CS1943ERR_QueryTypeInferenceFailedSelectMany02()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System;\nclass Test\n{\n class F1\n {\n public F1 SelectMany(Func func1, Func func2) { return this; }\n }\n static void Main()\n {\n F1 f1 = new F1();\n var x =\n from f in f1\n from g in 3\n select f + g;\n }\n}\n\").VerifyDiagnostics(\n // (14,23): error CS1943: An expression of type 'int' is not allowed in a subsequent from clause in a query expression with source type 'Test.F1'. Type inference failed in the call to 'SelectMany'.\n // from g in 3\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, \"3\").WithArguments(\"int\", \"Test.F1\", \"SelectMany\").WithLocation(14, 23)\n );\n }\n\n [Fact, WorkItem(546510, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546510\")]\n public void CS1944ERR_ExpressionTreeContainsPointerOp()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nunsafe class Test\n{\n public delegate int* D(int i);\n static void Main()\n {\n Expression tree = x => &x; // CS1944\n Expression> testExpr = x => new int*[] { &x };\n }\n}\n\";\n //Assert.Equal(\"\", text);\n CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (10,35): error CS1944: An expression tree may not contain an unsafe pointer operation\n // Expression tree = x => &x; // CS1944\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, \"&x\"),\n // (11,68): error CS1944: An expression tree may not contain an unsafe pointer operation\n // Expression> testExpr = x => new int*[] { &x };\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, \"&x\")\n );\n }\n\n [Fact]\n public void CS1945ERR_ExpressionTreeContainsAnonymousMethod()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic delegate void D();\nclass Test\n{\n static void Main()\n {\n Expression>> tree = (x => delegate(int i) { return true; }); // CS1945\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,61): error CS1945: An expression tree may not contain an anonymous method expression\n // Expression>> tree = (x => delegate(int i) { return true; }); // CS1945\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, \"delegate(int i) { return true; }\")\n );\n }\n\n [Fact]\n public void CS1946ERR_AnonymousMethodToExpressionTree()\n {\n var text = @\"\nusing System.Linq.Expressions;\n\npublic delegate void D();\n\nclass Test\n{\n static void Main()\n {\n Expression tree = delegate() { }; //CS1946\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,30): error CS1946: An anonymous method expression cannot be converted to an expression tree\n // Expression tree = delegate() { }; //CS1946\n Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, \"delegate() { }\")\n );\n }\n\n [Fact]\n public void CS1947ERR_QueryRangeVariableReadOnly()\n {\n var program = @\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] array = new int[] { 1, 2, 3, 4, 5 };\n var x = from i in array\n let k = i\n select i = 5; // CS1947\n x.ToList();\n }\n}\n\";\n CreateCompilation(program).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, \"i\").WithArguments(\"i\"));\n }\n\n [Fact]\n public void CS1948ERR_QueryRangeVariableSameAsTypeParam()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n public void TestMethod(T t)\n {\n var x = from T in Enumerable.Range(1, 100) // CS1948\n select T;\n }\n public static void Main()\n {\n }\n}\n\").VerifyDiagnostics(\n // (8,17): error CS1948: The range variable 'T' cannot have the same name as a method type parameter\n // T\n Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, \"T\").WithArguments(\"T\"));\n }\n\n [Fact]\n public void CS1949ERR_TypeVarNotFoundRangeVariable()\n {\n var text =\n@\"using System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from var i in Enumerable.Range(1, 100) // CS1949\n select i;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (7,22): error CS1949: The contextual keyword 'var' cannot be used in a range variable declaration\n // var x = from var i in Enumerable.Range(1, 100) // CS1949\n Diagnostic(ErrorCode.ERR_TypeVarNotFoundRangeVariable, \"var\")\n );\n }\n\n // CS1950 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1951ERR_ByRefParameterInExpressionTree()\n {\n var text = @\"\npublic delegate int TestDelegate(ref int i);\nclass Test\n{\n static void Main()\n {\n System.Linq.Expressions.Expression tree1 = (ref int x) => x; // CS1951\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (7,75): error CS1951: An expression tree lambda may not contain a ref, in or out parameter\n // System.Linq.Expressions.Expression tree1 = (ref int x) => x; // CS1951\n Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, \"x\").WithLocation(7, 75)\n );\n }\n\n [Fact]\n public void CS1951ERR_InParameterInExpressionTree()\n {\n var text = @\"\npublic delegate int TestDelegate(in int i);\nclass Test\n{\n static void Main()\n {\n System.Linq.Expressions.Expression tree1 = (in int x) => x; // CS1951\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (7,74): error CS1951: An expression tree lambda may not contain a ref, in or out parameter\n // System.Linq.Expressions.Expression tree1 = (in int x) => x; // CS1951\n Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, \"x\").WithLocation(7, 74)\n );\n }\n\n [Fact]\n public void CS1952ERR_VarArgsInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nclass Test\n{\n public static int M(__arglist)\n {\n return 1;\n }\n\n static int Main()\n {\n Expression> f = x => Test.M(__arglist(x)); // CS1952\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (14,52): error CS1952: An expression tree lambda may not contain a method with variable arguments\n // Expression> f = x => Test.M(__arglist(x)); // CS1952\n Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, \"__arglist(x)\")\n );\n }\n\n [WorkItem(864605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605\")]\n [Fact]\n public void CS1953ERR_MemGroupInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\nclass CS1953\n{\n public static void Main()\n {\n double num = 10;\n Expression> testExpr =\n () => num.GetType is int; // CS0837 \n }\n}\";\n // Used to be CS1953, but now a method group in an is expression is illegal anyway.\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,21): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // () => num.GetType is int; // CS1953 \n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"num.GetType is int\").WithLocation(10, 21));\n }\n\n // CS1954 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1955ERR_NonInvocableMemberCalled()\n {\n var text = @\"\nnamespace CompilerError1955\n{\n class ClassA\n {\n public int x = 100;\n public int X\n {\n get { return x; }\n set { x = value; }\n }\n }\n\n class Test\n {\n static void Main()\n {\n ClassA a = new ClassA();\n System.Console.WriteLine(a.x()); // CS1955\n System.Console.WriteLine(a.X()); // CS1955\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 19, Column = 40 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 20, Column = 40 }});\n }\n\n // CS1958 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1959ERR_InvalidConstantDeclarationType()\n {\n var text = @\"\nclass Program\n {\n static void Test() where T : class\n {\n const T x = null; // CS1959\n }\n }\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,25): error CS1959: 'x' is of type 'T'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type.\n // const T x = null; // CS1959\n Diagnostic(ErrorCode.ERR_InvalidConstantDeclarationType, \"null\").WithArguments(\"x\", \"T\")\n );\n }\n\n /// \n /// Test the different contexts in which CS1961 can be seen.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_Contexts()\n {\n var text = @\"\ninterface IContexts\n{\n #region In\n TIn Property1In { set; }\n TIn Property2In { get; } //CS1961 on \"\"TIn\"\"\n TIn Property3In { get; set; } //CS1961 on \"\"TIn\"\"\n\n int this[TIn arg, char filler, char indexer1In] { get; }\n TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on \"\"TIn\"\"\n int this[TIn arg, bool filler, char indexer3In] { set; }\n TIn this[int arg, bool[] filler, char indexer4In] { set; }\n int this[TIn arg, long filler, char indexer5In] { get; set; }\n TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on \"\"TIn\"\"\n\n int Method1In(TIn p);\n TIn Method2In(); //CS1961 on \"\"TIn\"\"\n int Method3In(out TIn p); //CS1961 on \"\"TIn\"\"\n int Method4In(ref TIn p); //CS1961 on \"\"TIn\"\"\n\n event DOut Event1In;\n #endregion In\n\n #region Out\n TOut Property1Out { set; } //CS1961 on \"\"TOut\"\"\n TOut Property2Out { get; }\n TOut Property3Out { get; set; } //CS1961 on \"\"TOut\"\"\n\n int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on \"\"TOut\"\"\n TOut this[int arg, char[] filler, bool indexer2Out] { get; }\n int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on \"\"TOut\"\"\n TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on \"\"TOut\"\"\n int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on \"\"TOut\"\"\n TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on \"\"TOut\"\"\n\n long Method1Out(TOut p); //CS1961 on \"\"TOut\"\"\n TOut Method2Out();\n long Method3Out(out TOut p); //CS1961 on \"\"TOut\"\" (sic: out params have to be input-safe)\n long Method4Out(ref TOut p); //CS1961 on \"\"TOut\"\"\n\n event DOut Event1Out; //CS1961 on \"\"TOut\"\"\n #endregion Out\n\n #region Inv\n TInv Property1Inv { set; }\n TInv Property2Inv { get; }\n TInv Property3Inv { get; set; }\n\n int this[TInv arg, char filler, long indexer1Inv] { get; }\n TInv this[int arg, char[] filler, long indexer2Inv] { get; }\n int this[TInv arg, bool filler, long indexer3Inv] { set; }\n TInv this[int arg, bool[] filler, long indexer4Inv] { set; }\n int this[TInv arg, long filler, long indexer5Inv] { get; set; }\n TInv this[int arg, long[] filler, long indexer6Inv] { get; set; }\n\n long Method1Inv(TInv p);\n TInv Method2Inv();\n long Method3Inv(out TInv p);\n long Method4Inv(ref TInv p);\n\n event DOut Event1Inv;\n #endregion Inv\n}\n\ndelegate void DOut(); //for event types - should preserve the variance of the type arg\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (6,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts.Property2In'. 'TIn' is contravariant.\n // TIn Property2In { get; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Property2In\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(6, 5),\n // (7,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.Property3In'. 'TIn' is contravariant.\n // TIn Property3In { get; set; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Property3In\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(7, 5),\n // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts.this[int, char[], char]'. 'TIn' is contravariant.\n // TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.this[int, char[], char]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(10, 5),\n // (14,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.this[int, long[], char]'. 'TIn' is contravariant.\n // TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.this[int, long[], char]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(14, 5),\n // (17,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts.Method2In()'. 'TIn' is contravariant.\n // TIn Method2In(); //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Method2In()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(17, 5),\n // (18,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.Method3In(out TIn)'. 'TIn' is contravariant.\n // int Method3In(out TIn p); //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Method3In(out TIn)\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(18, 23),\n // (19,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.Method4In(ref TIn)'. 'TIn' is contravariant.\n // int Method4In(ref TIn p); //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Method4In(ref TIn)\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(19, 23),\n // (25,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.Property1Out'. 'TOut' is covariant.\n // TOut Property1Out { set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Property1Out\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(25, 5),\n // (27,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.Property3Out'. 'TOut' is covariant.\n // TOut Property3Out { get; set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Property3Out\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(27, 5),\n // (29,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[TOut, char, bool]'. 'TOut' is covariant.\n // int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[TOut, char, bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(29, 14),\n // (31,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[TOut, bool, bool]'. 'TOut' is covariant.\n // int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[TOut, bool, bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(31, 14),\n // (32,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[int, bool[], bool]'. 'TOut' is covariant.\n // TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[int, bool[], bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(32, 5),\n // (33,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[TOut, long, bool]'. 'TOut' is covariant.\n // int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[TOut, long, bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(33, 14),\n // (34,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.this[int, long[], bool]'. 'TOut' is covariant.\n // TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[int, long[], bool]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(34, 5),\n // (36,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.Method1Out(TOut)'. 'TOut' is covariant.\n // long Method1Out(TOut p); //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Method1Out(TOut)\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(36, 21),\n // (38,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.Method3Out(out TOut)'. 'TOut' is covariant.\n // long Method3Out(out TOut p); //CS1961 on \"TOut\" (sic: out params have to be input-safe)\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Method3Out(out TOut)\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(38, 25),\n // (39,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.Method4Out(ref TOut)'. 'TOut' is covariant.\n // long Method4Out(ref TOut p); //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Method4Out(ref TOut)\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(39, 25),\n // (41,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.Event1Out'. 'TOut' is covariant.\n // event DOut Event1Out; //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event1Out\").WithArguments(\"IContexts.Event1Out\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(41, 22));\n }\n\n /// \n /// Test all of the contexts that require output safety.\n /// Note: some also require input safety.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_OutputUnsafe()\n {\n var text = @\"\ninterface IOutputUnsafe\n{\n #region Case 1: contravariant type parameter\n TInv Property1Good { get; }\n TInv this[long[] Indexer1Good] { get; }\n TInv Method1Good();\n\n TIn Property1Bad { get; }\n TIn this[char[] Indexer1Bad] { get; }\n TIn Method1Bad();\n #endregion Case 1\n\n #region Case 2: array of output-unsafe\n TInv[] Property2Good { get; }\n TInv[] this[long[,] Indexer2Good] { get; }\n TInv[] Method2Good();\n\n TIn[] Property2Bad { get; }\n TIn[] this[char[,] Indexer2Bad] { get; }\n TIn[] Method2Bad();\n #endregion Case 2\n\n #region Case 3: constructed with output-unsafe type arg in covariant slot\n IOut Property3Good { get; }\n IOut this[long[,,] Indexer3Good] { get; }\n IOut Method3Good();\n\n IOut Property3Bad { get; }\n IOut this[char[,,] Indexer3Bad] { get; }\n IOut Method3Bad();\n #endregion Case 3\n\n #region Case 4: constructed with output-unsafe type arg in invariant slot\n IInv Property4Good { get; }\n IInv this[long[,,,] Indexer4Good] { get; }\n IInv Method4Good();\n\n IInv Property4Bad { get; }\n IInv this[char[,,,] Indexer4Bad] { get; }\n IInv Method4Bad();\n #endregion Case 4\n\n #region Case 5: constructed with input-unsafe (sic) type arg in contravariant slot\n IIn Property5Good { get; }\n IIn this[long[,,,,] Indexer5Good] { get; }\n IIn Method5Good();\n\n IIn Property5Bad { get; }\n IIn this[char[,,,,] Indexer5Bad] { get; }\n IIn Method5Bad();\n #endregion Case 5\n\n #region Case 6: constructed with input-unsafe (sic) type arg in invariant slot\n IInv Property6Good { get; }\n IInv this[long[,,,,,] Indexer6Good] { get; }\n IInv Method6Good();\n\n IInv Property6Bad { get; }\n IInv this[char[,,,,,] Indexer6Bad] { get; }\n IInv Method6Bad();\n #endregion Case 6\n}\n\ninterface IIn { }\ninterface IOut { }\ninterface IInv { }\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (9,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Property1Bad'. 'TIn' is contravariant.\n // TIn Property1Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOutputUnsafe.Property1Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(9, 5),\n // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.this[char[]]'. 'TIn' is contravariant.\n // TIn this[char[] Indexer1Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOutputUnsafe.this[char[]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(10, 5),\n // (11,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Method1Bad()'. 'TIn' is contravariant.\n // TIn Method1Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOutputUnsafe.Method1Bad()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(11, 5),\n // (19,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Property2Bad'. 'TIn' is contravariant.\n // TIn[] Property2Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn[]\").WithArguments(\"IOutputUnsafe.Property2Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(19, 5),\n // (20,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.this[char[*,*]]'. 'TIn' is contravariant.\n // TIn[] this[char[,] Indexer2Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn[]\").WithArguments(\"IOutputUnsafe.this[char[*,*]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(20, 5),\n // (21,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Method2Bad()'. 'TIn' is contravariant.\n // TIn[] Method2Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn[]\").WithArguments(\"IOutputUnsafe.Method2Bad()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(21, 5),\n // (29,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Property3Bad'. 'TIn' is contravariant.\n // IOut Property3Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IOutputUnsafe.Property3Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(29, 5),\n // (30,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.this[char[*,*,*]]'. 'TIn' is contravariant.\n // IOut this[char[,,] Indexer3Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IOutputUnsafe.this[char[*,*,*]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(30, 5),\n // (31,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Method3Bad()'. 'TIn' is contravariant.\n // IOut Method3Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IOutputUnsafe.Method3Bad()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(31, 5),\n // (39,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe.Property4Bad'. 'TIn' is contravariant.\n // IInv Property4Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Property4Bad\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(39, 5),\n // (40,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe.this[char[*,*,*,*]]'. 'TIn' is contravariant.\n // IInv this[char[,,,] Indexer4Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.this[char[*,*,*,*]]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(40, 5),\n // (41,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe.Method4Bad()'. 'TIn' is contravariant.\n // IInv Method4Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Method4Bad()\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(41, 5),\n // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe.Property5Bad'. 'TOut' is covariant.\n // IIn Property5Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IOutputUnsafe.Property5Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(49, 5),\n // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe.this[char[*,*,*,*,*]]'. 'TOut' is covariant.\n // IIn this[char[,,,,] Indexer5Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IOutputUnsafe.this[char[*,*,*,*,*]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(50, 5),\n // (51,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe.Method5Bad()'. 'TOut' is covariant.\n // IIn Method5Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IOutputUnsafe.Method5Bad()\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(51, 5),\n // (59,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe.Property6Bad'. 'TOut' is covariant.\n // IInv Property6Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Property6Bad\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(59, 5),\n // (60,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe.this[char[*,*,*,*,*,*]]'. 'TOut' is covariant.\n // IInv this[char[,,,,,] Indexer6Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.this[char[*,*,*,*,*,*]]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(60, 5),\n // (61,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe.Method6Bad()'. 'TOut' is covariant.\n // IInv Method6Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Method6Bad()\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(61, 5));\n }\n\n /// \n /// Test all of the contexts that require input safety.\n /// Note: some also require output safety.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_InputUnsafe()\n {\n var text = @\"\ninterface IInputUnsafe\n{\n #region Case 1: contravariant type parameter\n TInv Property1Good { set; }\n TInv this[long[] Indexer1GoodA] { set; }\n long this[long[] Indexer1GoodB, TInv p] { set; }\n long Method1Good(TInv p);\n\n TOut Property1Bad { set; }\n TOut this[char[] Indexer1BadA] { set; }\n long this[char[] Indexer1BadB, TOut p] { set; }\n long Method1Bad(TOut p);\n #endregion Case 1\n\n #region Case 2: array of input-unsafe\n TInv[] Property2Good { set; }\n TInv[] this[long[,] Indexer2GoodA] { set; }\n long this[long[,] Indexer2GoodB, TInv[] p] { set; }\n long Method2Good(TInv[] p);\n\n TOut[] Property2Bad { set; }\n TOut[] this[char[,] Indexer2BadA] { set; }\n long this[char[,] Indexer2BadB, TOut[] p] { set; }\n long Method2Bad(TOut[] p);\n #endregion Case 2\n\n #region Case 3: constructed with input-unsafe type arg in covariant (sic: not flipped) slot\n IOut Property3Good { set; }\n IOut this[long[,,] Indexer3GoodA] { set; }\n long this[long[,,] Indexer3GoodB, IOut p] { set; }\n long Method3Good(IOut p);\n event DOut Event3Good;\n\n IOut Property3Bad { set; }\n IOut this[char[,,] Indexer3BadA] { set; }\n long this[char[,,] Indexer3BadB, IOut p] { set; }\n long Method3Bad(IOut p);\n event DOut Event3Bad;\n #endregion Case 3\n\n #region Case 4: constructed with input-unsafe type arg in invariant slot\n IInv Property4Good { set; }\n IInv this[long[,,,] Indexer4GoodA] { set; }\n long this[long[,,,] Indexer4GoodB, IInv p] { set; }\n long Method4Good(IInv p);\n event DInv Event4Good;\n\n IInv Property4Bad { set; }\n IInv this[char[,,,] Indexer4BadA] { set; }\n long this[char[,,,] Indexer4BadB, IInv p] { set; }\n long Method4Bad(IInv p);\n event DInv Event4Bad;\n #endregion Case 4\n\n #region Case 5: constructed with output-unsafe (sic) type arg in contravariant (sic: not flipped) slot\n IIn Property5Good { set; }\n IIn this[long[,,,,] Indexer5GoodA] { set; }\n long this[long[,,,,] Indexer5GoodB, IIn p] { set; }\n long Method5Good(IIn p);\n event DIn Event5Good;\n\n IIn Property5Bad { set; }\n IIn this[char[,,,,] Indexer5BadA] { set; }\n long this[char[,,,,] Indexer5BadB, IIn p] { set; }\n long Method5Bad(IIn p);\n event DIn Event5Bad;\n #endregion Case 5\n\n #region Case 6: constructed with output-unsafe (sic) type arg in invariant slot\n IInv Property6Good { set; }\n IInv this[long[,,,,,] Indexer6GoodA] { set; }\n long this[long[,,,,,] Indexer6GoodB, IInv p] { set; }\n long Method6Good(IInv p);\n event DInv Event6Good;\n\n IInv Property6Bad { set; }\n IInv this[char[,,,,,] Indexer6BadA] { set; }\n long this[char[,,,,,] Indexer6BadB, IInv p] { set; }\n long Method6Bad(IInv p);\n event DInv Event6Bad;\n #endregion Case 6\n}\n\ninterface IIn { }\ninterface IOut { }\ninterface IInv { }\n\ndelegate void DIn();\ndelegate void DOut();\ndelegate void DInv();\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (11,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[]]'. 'TOut' is covariant.\n // TOut this[char[] Indexer1BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.this[char[]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(11, 5),\n // (12,36): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[], TOut]'. 'TOut' is covariant.\n // long this[char[] Indexer1BadB, TOut p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.this[char[], TOut]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(12, 36),\n // (23,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*]]'. 'TOut' is covariant.\n // TOut[] this[char[,] Indexer2BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.this[char[*,*]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(23, 5),\n // (24,37): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*], TOut[]]'. 'TOut' is covariant.\n // long this[char[,] Indexer2BadB, TOut[] p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.this[char[*,*], TOut[]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(24, 37),\n // (36,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*,*]]'. 'TOut' is covariant.\n // IOut this[char[,,] Indexer3BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.this[char[*,*,*]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(36, 5),\n // (37,38): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*,*], IOut]'. 'TOut' is covariant.\n // long this[char[,,] Indexer3BadB, IOut p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.this[char[*,*,*], IOut]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(37, 38),\n // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*]]'. 'TOut' is covariant.\n // IInv this[char[,,,] Indexer4BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*]]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(50, 5),\n // (51,39): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*], IInv]'. 'TOut' is covariant.\n // long this[char[,,,] Indexer4BadB, IInv p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*], IInv]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(51, 39),\n // (64,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*]]'. 'TIn' is contravariant.\n // IIn this[char[,,,,] Indexer5BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(64, 5),\n // (65,40): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*], IIn]'. 'TIn' is contravariant.\n // long this[char[,,,,] Indexer5BadB, IIn p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*], IIn]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(65, 40),\n // (78,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*,*]]'. 'TIn' is contravariant.\n // IInv this[char[,,,,,] Indexer6BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*,*]]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(78, 5),\n // (79,41): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*,*], IInv]'. 'TIn' is contravariant.\n // long this[char[,,,,,] Indexer6BadB, IInv p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*,*], IInv]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(79, 41),\n // (10,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Property1Bad'. 'TOut' is covariant.\n // TOut Property1Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.Property1Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(10, 5),\n // (13,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Method1Bad(TOut)'. 'TOut' is covariant.\n // long Method1Bad(TOut p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.Method1Bad(TOut)\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(13, 21),\n // (22,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Property2Bad'. 'TOut' is covariant.\n // TOut[] Property2Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.Property2Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(22, 5),\n // (25,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Method2Bad(TOut[])'. 'TOut' is covariant.\n // long Method2Bad(TOut[] p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.Method2Bad(TOut[])\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(25, 21),\n // (35,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Property3Bad'. 'TOut' is covariant.\n // IOut Property3Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.Property3Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(35, 5),\n // (38,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Method3Bad(IOut)'. 'TOut' is covariant.\n // long Method3Bad(IOut p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.Method3Bad(IOut)\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(38, 21),\n // (39,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Event3Bad'. 'TOut' is covariant.\n // event DOut Event3Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event3Bad\").WithArguments(\"IInputUnsafe.Event3Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(39, 22),\n // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.Property4Bad'. 'TOut' is covariant.\n // IInv Property4Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Property4Bad\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(49, 5),\n // (52,21): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.Method4Bad(IInv)'. 'TOut' is covariant.\n // long Method4Bad(IInv p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Method4Bad(IInv)\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(52, 21),\n // (53,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.Event4Bad'. 'TOut' is covariant.\n // event DInv Event4Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event4Bad\").WithArguments(\"IInputUnsafe.Event4Bad\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(53, 22),\n // (63,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.Property5Bad'. 'TIn' is contravariant.\n // IIn Property5Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.Property5Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(63, 5),\n // (66,21): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.Method5Bad(IIn)'. 'TIn' is contravariant.\n // long Method5Bad(IIn p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.Method5Bad(IIn)\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(66, 21),\n // (67,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.Event5Bad'. 'TIn' is contravariant.\n // event DIn Event5Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event5Bad\").WithArguments(\"IInputUnsafe.Event5Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(67, 20),\n // (77,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.Property6Bad'. 'TIn' is contravariant.\n // IInv Property6Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Property6Bad\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(77, 5),\n // (80,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.Method6Bad(IInv)'. 'TIn' is contravariant.\n // long Method6Bad(IInv p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Method6Bad(IInv)\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(80, 21),\n // (81,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.Event6Bad'. 'TIn' is contravariant.\n // event DInv Event6Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event6Bad\").WithArguments(\"IInputUnsafe.Event6Bad\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(81, 21));\n }\n\n /// \n /// Test output-safety checks on base interfaces.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_BaseInterfaces()\n {\n var text = @\"\ninterface IBaseInterfaces : IIn, IOut, IInv { }\n\ninterface IIn { }\ninterface IOut { }\ninterface IInv { }\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (2,39): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IIn'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IIn\", \"TOut\", \"covariant\", \"contravariantly\"),\n // (2,30): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOut'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOut\", \"TIn\", \"contravariant\", \"covariantly\"));\n }\n\n /// \n /// Test all type parameter/type argument combinations.\n /// | Type Arg Covariant | Type Arg Contravariant | Type Arg Invariant\n /// -------------------------+----------------------+------------------------+--------------------\n /// Type Param Covariant | Covariant | Contravariant | Invariant\n /// Type Param Contravariant | Contravariant | Covariant | Invariant\n /// Type Param Invariant | Error | Error | Invariant\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_Generics()\n {\n var text = @\"\ninterface IOutputUnsafeTable\n{\n ICovariant OutputUnsafe1();\n ICovariant OutputUnsafe2();\n ICovariant OutputUnsafe3();\n\n IContravariant OutputUnsafe4();\n IContravariant OutputUnsafe5();\n IContravariant OutputUnsafe6();\n\n IInvariant OutputUnsafe7();\n IInvariant OutputUnsafe8();\n IInvariant OutputUnsafe9();\n}\n\ninterface IInputUnsafeTable\n{\n void InputUnsafe1(ICovariant p);\n void InputUnsafe2(ICovariant p);\n void InputUnsafe3(ICovariant p);\n\n void InputUnsafe4(IContravariant p);\n void InputUnsafe5(IContravariant p);\n void InputUnsafe6(IContravariant p);\n\n void InputUnsafe7(IInvariant p);\n void InputUnsafe8(IInvariant p);\n void InputUnsafe9(IInvariant p);\n}\n\ninterface IBothUnsafeTable\n{\n void InputUnsafe1(ref ICovariant p);\n void InputUnsafe2(ref ICovariant p);\n void InputUnsafe3(ref ICovariant p);\n\n void InputUnsafe4(ref IContravariant p);\n void InputUnsafe5(ref IContravariant p);\n void InputUnsafe6(ref IContravariant p);\n\n void InputUnsafe7(ref IInvariant p);\n void InputUnsafe8(ref IInvariant p);\n void InputUnsafe9(ref IInvariant p);\n}\n\ninterface ICovariant { }\ninterface IContravariant { }\ninterface IInvariant { }\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (5,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IOutputUnsafeTable.OutputUnsafe2()'. 'TOutputUnsafe' is contravariant.\n // ICovariant OutputUnsafe2();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe2()\", \"TOutputUnsafe\", \"contravariant\", \"covariantly\").WithLocation(5, 5),\n // (8,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IOutputUnsafeTable.OutputUnsafe4()'. 'TInputUnsafe' is covariant.\n // IContravariant OutputUnsafe4();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe4()\", \"TInputUnsafe\", \"covariant\", \"contravariantly\").WithLocation(8, 5),\n // (12,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IOutputUnsafeTable.OutputUnsafe7()'. 'TInputUnsafe' is covariant.\n // IInvariant OutputUnsafe7();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe7()\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(12, 5),\n // (13,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IOutputUnsafeTable.OutputUnsafe8()'. 'TOutputUnsafe' is contravariant.\n // IInvariant OutputUnsafe8();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe8()\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(13, 5),\n // (19,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IInputUnsafeTable.InputUnsafe1(ICovariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe1(ICovariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe1(ICovariant)\", \"TInputUnsafe\", \"covariant\", \"contravariantly\").WithLocation(19, 23),\n // (24,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IInputUnsafeTable.InputUnsafe5(IContravariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe5(IContravariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe5(IContravariant)\", \"TOutputUnsafe\", \"contravariant\", \"covariantly\").WithLocation(24, 23),\n // (27,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IInputUnsafeTable.InputUnsafe7(IInvariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe7(IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe7(IInvariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(27, 23),\n // (28,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IInputUnsafeTable.InputUnsafe8(IInvariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe8(IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe8(IInvariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(28, 23),\n\n // Dev10 doesn't say \"must be invariantly valid\" for ref params - it lists whichever check fails first. This approach seems nicer.\n\n // (34,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe1(ref ICovariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe1(ref ICovariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe1(ref ICovariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(34, 27),\n // (35,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe2(ref ICovariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe2(ref ICovariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe2(ref ICovariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(35, 27),\n // (38,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe4(ref IContravariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe4(ref IContravariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe4(ref IContravariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(38, 27),\n // (39,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe5(ref IContravariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe5(ref IContravariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe5(ref IContravariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(39, 27),\n // (42,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe7(ref IInvariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe7(ref IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe7(ref IInvariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(42, 27),\n // (43,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe8(ref IInvariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe8(ref IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe8(ref IInvariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(43, 27));\n }\n\n [Fact]\n public void CS1961ERR_UnexpectedVariance_DelegateInvoke()\n {\n var text = @\"\ndelegate TIn D1(); //CS1961\ndelegate TOut D2();\ndelegate T D3();\n\ndelegate void D4(TIn p);\ndelegate void D5(TOut p); //CS1961\ndelegate void D6(T p);\n\ndelegate void D7(ref TIn p); //CS1961\ndelegate void D8(ref TOut p); //CS1961\ndelegate void D9(ref T p);\n\ndelegate void D10(out TIn p); //CS1961\ndelegate void D11(out TOut p); //CS1961\ndelegate void D12(out T p);\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (2,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'D1.Invoke()'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"D1.Invoke()\", \"TIn\", \"contravariant\", \"covariantly\"),\n // (7,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'D5.Invoke(TOut)'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"D5.Invoke(TOut)\", \"TOut\", \"covariant\", \"contravariantly\"),\n // (10,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D7.Invoke(ref TIn)'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"D7.Invoke(ref TIn)\", \"TIn\", \"contravariant\", \"invariantly\"),\n // (11,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D8.Invoke(ref TOut)'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"D8.Invoke(ref TOut)\", \"TOut\", \"covariant\", \"invariantly\"),\n // (14,22): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D10.Invoke(out TIn)'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"D10.Invoke(out TIn)\", \"TIn\", \"contravariant\", \"invariantly\"),\n // (15,23): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D11.Invoke(out TOut)'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"D11.Invoke(out TOut)\", \"TOut\", \"covariant\", \"invariantly\"));\n }\n\n [Fact]\n public void CS1962ERR_BadDynamicTypeof()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n dynamic S = typeof(dynamic);\n return 0;\n }\n public static int Test(int age)\n { \n return 1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,25): error CS1962: The typeof operator cannot be used on the dynamic type\n Diagnostic(ErrorCode.ERR_BadDynamicTypeof, \"typeof(dynamic)\"));\n }\n\n [Fact]\n [WorkItem(54804, \"https://github.com/dotnet/roslyn/issues/54804\")]\n public void BadNestedTypeof()\n {\n var source = @\"\n#nullable enable\n\nusing System;\nusing System.Collections.Generic;\n\nvar x = typeof(List); // 1\nx = typeof(nint); // 2\nx = typeof(List); // 3\nx = typeof(List); // 4\nx = typeof((int a, int b)); // 5\nx = typeof((int a, string? b)); // 6\nx = typeof(ValueTuple); // ok\n\";\n CreateCompilation(source).VerifyDiagnostics();\n\n CreateCompilation(source, options: TestOptions.DebugExe.WithWarningLevel(5)).VerifyDiagnostics();\n }\n\n // CS1963ERR_ExpressionTreeContainsDynamicOperation --> SyntaxBinderTests\n\n [Fact]\n public void CS1964ERR_BadDynamicConversion()\n {\n var text = @\"\nclass A\n{\n public static implicit operator dynamic(A a)\n {\n return a;\n }\n\n public static implicit operator A(dynamic a)\n {\n return a;\n}\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (9,37): error CS1964: 'A.implicit operator A(dynamic)': user-defined conversions to or from the dynamic type are not allowed\n Diagnostic(ErrorCode.ERR_BadDynamicConversion, \"A\").WithArguments(\"A.implicit operator A(dynamic)\"),\n // (4,37): error CS1964: 'A.implicit operator dynamic(A)': user-defined conversions to or from the dynamic type are not allowed\n Diagnostic(ErrorCode.ERR_BadDynamicConversion, \"dynamic\").WithArguments(\"A.implicit operator dynamic(A)\"));\n }\n\n // CS1969ERR_DynamicRequiredTypesMissing -> CodeGen_DynamicTests.Missing_*\n // CS1970ERR_ExplicitDynamicAttr --> AttributeTests_Dynamic.ExplicitDynamicAttribute\n\n [Fact]\n public void CS1971ERR_NoDynamicPhantomOnBase()\n {\n const string text = @\"\npublic class B\n{\n public virtual void M(object o) {}\n}\npublic class D : B\n{\n public override void M(object o) {}\n\n void N(dynamic d)\n {\n base.M(d);\n }\n}\n\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (12,9): error CS1971: The call to method 'M' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.\n // base.M(d);\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBase, \"base.M(d)\").WithArguments(\"M\"));\n }\n\n [Fact]\n public void CS1972ERR_NoDynamicPhantomOnBaseIndexer()\n {\n const string text = @\"\npublic class B\n{\n public string this[int index]\n {\n get { return \"\"You passed \"\" + index; }\n }\n}\npublic class D : B\n{\n public void M(object o)\n {\n int[] arr = { 1, 2, 3 };\n int s = base[(dynamic)o];\n }\n}\n\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (14,17): error CS1972: The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.\n // int s = base[(dynamic)o];\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, \"base[(dynamic)o]\"));\n }\n\n [Fact]\n public void CS1973ERR_BadArgTypeDynamicExtension()\n {\n const string text = @\"\nclass Program\n{\n static void Main()\n {\n dynamic d = 1;\n B b = new B();\n b.Goo(d);\n }\n}\npublic class B { }\nstatic public class Extension\n{\n public static void Goo(this B b, int x) { }\n}\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n// (8,9): error CS1973: 'B' has no applicable method named 'Goo' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.\n// b.Goo(d);\nDiagnostic(ErrorCode.ERR_BadArgTypeDynamicExtension, \"b.Goo(d)\").WithArguments(\"B\", \"Goo\"));\n }\n\n [Fact]\n public void CS1975ERR_NoDynamicPhantomOnBaseCtor_Base()\n {\n var text = @\"\nclass A\n{\n public A(int x)\n {\n\n }\n}\nclass B : A\n{\n public B(dynamic d)\n : base(d)\n { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, \"base\"));\n }\n\n [Fact]\n public void CS1975ERR_NoDynamicPhantomOnBaseCtor_This()\n {\n var text = @\"\nclass B\n{\n public B(dynamic d)\n : this(d, 1)\n { }\n\n public B(int a, int b)\n { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, \"this\"));\n }\n\n [Fact]\n public void CS1976ERR_BadDynamicMethodArgMemgrp()\n {\n const string text = @\"\nclass Program\n{\n static void M(dynamic d)\n {\n d.Goo(M);\n }\n}\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (6,15): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?\n // d.Goo(M);\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, \"M\"));\n }\n\n [Fact]\n public void CS1977ERR_BadDynamicMethodArgLambda()\n {\n const string text = @\"\nclass Program\n{\n static void M(dynamic d)\n {\n d.Goo(()=>{});\n d.Goo(delegate () {});\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (6,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n // d.Goo(()=>{});\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"()=>{}\"),\n // (7,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n // d.Goo(delegate () {});\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"delegate () {}\"));\n }\n\n [Fact, WorkItem(578352, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578352\")]\n public void CS1977ERR_BadDynamicMethodArgLambda_CreateObject()\n {\n string source = @\"\nusing System;\n \nclass C\n{\n static void Main()\n {\n dynamic y = null;\n new C(delegate { }, y);\n }\n \n public C(Action a, Action y)\n {\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef });\n comp.VerifyDiagnostics(\n // (9,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"delegate { }\"));\n }\n\n [Fact]\n public void CS1660ERR_BadDynamicMethodArgLambda_CollectionInitializer()\n {\n string source = @\"\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nunsafe class C : IEnumerable\n{\n public static void M(__arglist) \n {\n int a; \n int* p = &a;\n dynamic d = null;\n\n var c = new C\n {\n { d, delegate() { } },\n { d, 1, p },\n { d, __arglist },\n { d, GetEnumerator },\n { d, SomeStaticMethod },\n };\n }\n\n public static void SomeStaticMethod() {}\n\n public void Add(dynamic d, int x, int* ptr)\n {\n }\n\n public void Add(dynamic d, RuntimeArgumentHandle x)\n {\n }\n\n public void Add(dynamic d, Action f)\n {\n }\n\n public void Add(dynamic d, Func> f)\n {\n }\n\n public IEnumerator GetEnumerator()\n {\n return null;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }, options: TestOptions.UnsafeReleaseDll);\n comp.VerifyDiagnostics(\n // (16,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n // { d, delegate() { } },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"delegate() { }\").WithLocation(16, 18),\n // (17,21): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n // { d, 1, p },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"p\").WithArguments(\"int*\").WithLocation(17, 21),\n // (18,18): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation.\n // { d, __arglist },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\").WithLocation(18, 18),\n // (19,13): error CS1950: The best overloaded Add method 'C.Add(dynamic, RuntimeArgumentHandle)' for the collection initializer has some invalid arguments\n // { d, GetEnumerator },\n Diagnostic(ErrorCode.ERR_BadArgTypesForCollectionAdd, \"{ d, GetEnumerator }\").WithArguments(\"C.Add(dynamic, System.RuntimeArgumentHandle)\").WithLocation(19, 13),\n // (19,18): error CS1503: Argument 2: cannot convert from 'method group' to 'RuntimeArgumentHandle'\n // { d, GetEnumerator },\n Diagnostic(ErrorCode.ERR_BadArgType, \"GetEnumerator\").WithArguments(\"2\", \"method group\", \"System.RuntimeArgumentHandle\").WithLocation(19, 18),\n // (20,18): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?\n // { d, SomeStaticMethod },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, \"SomeStaticMethod\").WithLocation(20, 18));\n }\n\n [Fact]\n public void CS1978ERR_BadDynamicMethodArg()\n {\n // The dev 10 compiler gives arguably wrong error here; it says that \"TypedReference may not be\n // used as a type argument\". Though that is true, and though what is happening here behind the scenes \n // is that TypedReference is being used as a type argument to a dynamic call site helper method,\n // that's giving an error about an implementation detail. A better error is to say that\n // TypedReference is not a legal type in a dynamic operation.\n //\n // Dev10 compiler didn't report an error for by-ref pointer argument. See Dev10 bug 819498.\n // The error should be reported for any pointer argument regardless of its refness.\n const string text = @\"\nclass Program\n{\n unsafe static void M(dynamic d, int* i, System.TypedReference tr)\n {\n d.Goo(i);\n d.Goo(tr);\n d.Goo(ref tr);\n d.Goo(out tr);\n d.Goo(out i);\n d.Goo(ref i);\n }\n}\n\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll);\n comp.VerifyDiagnostics(\n // (6,15): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"i\").WithArguments(\"int*\"),\n // (7,15): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"tr\").WithArguments(\"System.TypedReference\"),\n // (8,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"tr\").WithArguments(\"System.TypedReference\"),\n // (9,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"tr\").WithArguments(\"System.TypedReference\"),\n // (10,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"i\").WithArguments(\"int*\"),\n // (11,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"i\").WithArguments(\"int*\"));\n }\n\n // CS1979ERR_BadDynamicQuery --> DynamicTests.cs, DynamicQuery_* \n\n // Test CS1980ERR_DynamicAttributeMissing moved to AttributeTests_Dynamic.cs\n\n // CS1763 is covered for different code path by SymbolErrorTests.CS1763ERR_NotNullRefDefaultParameter()\n [WorkItem(528854, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528854\")]\n [Fact]\n public void CS1763ERR_NotNullRefDefaultParameter02()\n {\n string text = @\"\nclass Program\n{\n public void Goo(T t = default(U)) where U : T\n {\n }\n static void Main(string[] args)\n {\n \n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,29): error CS1763: 't' is of type 'T'. A default parameter value of a reference type other than string can only be initialized with null\n // public void Goo(T t = default(U)) where U : T\n Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, \"t\").WithArguments(\"t\", \"T\"));\n }\n\n #endregion\n\n #region \"Targeted Warning Tests - please arrange tests in the order of error code\"\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent()\n {\n var text = @\"\ndelegate void MyDelegate();\nclass MyClass\n{\n public event MyDelegate evt; // CS0067\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,29): warning CS0067: The event 'MyClass.evt' is never used\n // public event MyDelegate evt; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"evt\").WithArguments(\"MyClass.evt\"));\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_Accessibility()\n {\n var text = @\"\nusing System;\nclass MyClass\n{\n public event Action E1; // CS0067\n internal event Action E2; // CS0067\n protected internal event Action E3; // CS0067\n protected event Action E4; // CS0067\n private event Action E5; // CS0067\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,25): warning CS0067: The event 'MyClass.E1' is never used\n // public event Action E1; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E1\").WithArguments(\"MyClass.E1\"),\n // (6,27): warning CS0067: The event 'MyClass.E2' is never used\n // internal event Action E2; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E2\").WithArguments(\"MyClass.E2\"),\n // (7,37): warning CS0067: The event 'MyClass.E3' is never used\n // protected internal event Action E3; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E3\").WithArguments(\"MyClass.E3\"),\n // (8,28): warning CS0067: The event 'MyClass.E4' is never used\n // protected event Action E4; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E4\").WithArguments(\"MyClass.E4\"),\n // (9,26): warning CS0067: The event 'MyClass.E5' is never used\n // private event Action E5; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E5\").WithArguments(\"MyClass.E5\"));\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_StructLayout()\n {\n var text = @\"\nusing System;\nusing System.Runtime.InteropServices;\n\n[StructLayout(LayoutKind.Sequential)]\nstruct S\n{\n event Action E1;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_Kind()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n event Action E1; // CS0067\n event Action E2 { add { } remove { } }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,18): warning CS0067: The event 'C.E1' is never used\n // event Action E1; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E1\").WithArguments(\"C.E1\"));\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_Accessed()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n event Action None; // CS0067\n event Action Read;\n event Action Write;\n event Action Add; // CS0067\n\n void M(Action a)\n {\n M(Read);\n Write = a;\n Add += a;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,18): warning CS0067: The event 'C.Add' is never used\n // event Action Add; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"Add\").WithArguments(\"C.Add\"),\n // (6,18): warning CS0067: The event 'C.None' is never used\n // event Action None; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"None\").WithArguments(\"C.None\"));\n }\n\n [Fact, WorkItem(581002, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581002\")]\n public void CS0067WRN_UnreferencedEvent_Virtual()\n {\n var text = @\"class A\n{\n public virtual event System.EventHandler B;\n class C : A\n {\n public override event System.EventHandler B;\n }\n static int Main()\n {\n C c = new C();\n A a = c;\n return 0;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (3,46): warning CS0067: The event 'A.B' is never used\n // public virtual event System.EventHandler B;\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"B\").WithArguments(\"A.B\"),\n // (6,51): warning CS0067: The event 'A.C.B' is never used\n // public override event System.EventHandler B;\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"B\").WithArguments(\"A.C.B\"));\n }\n\n\n [Fact, WorkItem(539630, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539630\")]\n public void CS0162WRN_UnreachableCode01()\n {\n var text = @\"\nclass MyTest { }\nclass MyClass\n{\n const MyTest test = null;\n public static int Main()\n {\n goto lab1;\n {\n // The following statements cannot be reached:\n int i = 9; // CS0162 \n i++;\n }\n lab1:\n if (test == null)\n {\n return 0;\n }\n else\n {\n return 1; // CS0162\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"int\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"));\n }\n\n [Fact, WorkItem(530037, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530037\")]\n public void CS0162WRN_UnreachableCode02()\n {\n var text = @\"\nusing System;\n\npublic class Test \n{\n public static void Main(string[] args)\n {\n // (1)\n do\n {\n for (; ; ) { }\n } while (args.Length > 0); // Native CS0162\n // (2)\n for (; ; ) // Roslyn CS0162\n {\n goto L2;\n Console.WriteLine(\"\"Unreachable code\"\");\n L2: // Roslyn CS0162\n break;\n }\n} }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,5): warning CS0162: Unreachable code detected\n // for (; ; ) // Roslyn CS0162\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"for\"),\n // (18,5): warning CS0162: Unreachable code detected\n // L2: // Roslyn CS0162\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"L2\")\n );\n }\n\n [Fact, WorkItem(539873, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539873\"), WorkItem(539981, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539981\")]\n public void CS0162WRN_UnreachableCode04()\n {\n var text = @\"\npublic class Cls\n{\n public static int Main()\n {\n goto Label2;\n return 0;\n Label1:\n return 1;\n Label2:\n goto Label1;\n return 2;\n }\n\n delegate void Sub_0(); \n static void M()\n {\n Sub_0 s1_3 = () => { if (2 == 1) return; else return; };\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"));\n }\n\n [Fact, WorkItem(540901, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540901\")]\n public void CS0162WRN_UnreachableCode06_Loops()\n {\n var text = @\"\nclass Program\n{\n void F()\n {\n }\n void T()\n {\n for (int i = 0; i < 0; F(), i++) // F() is unreachable\n {\n return;\n }\n }\n\n static void Main()\n {\n string[] S = new string[] { \"\"ABC\"\", \"\"XYZ\"\" };\n foreach (string x in S)\n {\n foreach (char y in x)\n {\n goto stop;\n System.Console.WriteLine(y); // unreachable\n }\n\n foreach (char y in x)\n {\n throw new System.Exception();\n System.Console.WriteLine(y); // unreachable\n }\n stop:\n return;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"F\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"System\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"System\"));\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode06_Foreach03()\n {\n var text = @\"\npublic class Test\n{\n static public void Main(string[] args)\n {\n string[] S = new string[] { \"\"ABC\"\", \"\"XYZ\"\" };\n foreach (string x in S)\n {\n foreach (char y in x)\n {\n return;\n System.Console.WriteLine(y);\n }\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, \"System\"));\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode07_GotoInLambda()\n {\n var text = @\"\nusing System;\nclass Program\n{\n static void Main()\n {\n Action a = () => { goto label1; Console.WriteLine(\"\"unreachable\"\"); label1: Console.WriteLine(\"\"reachable\"\"); };\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, @\"Console\"));\n }\n\n [Fact]\n public void CS0164WRN_UnreferencedLabel()\n {\n var text = @\"\npublic class a\n{\n public int i = 0;\n\n public static void Main()\n {\n int i = 0; // CS0164\n l1: i++;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"l1\").WithLocation(9, 7));\n }\n\n [Fact]\n public void CS0168WRN_UnreferencedVar01()\n {\n var text = @\"\npublic class clx\n{\n public int i;\n}\n\npublic class clz\n{\n public static void Main()\n {\n int j ; // CS0168, uncomment the following line\n // j++;\n clx a; // CS0168, try the following line instead\n // clx a = new clx();\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"j\").WithArguments(\"j\").WithLocation(11, 13),\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"a\").WithArguments(\"a\").WithLocation(13, 13));\n }\n\n [Fact]\n public void CS0168WRN_UnreferencedVar02()\n {\n var text =\n@\"using System;\nclass C\n{\n static void M()\n {\n try { }\n catch (InvalidOperationException e) { }\n catch (InvalidCastException e) { throw; }\n catch (Exception e) { throw e; }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(7, 42),\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(8, 37));\n }\n\n [Fact]\n public void CS0169WRN_UnreferencedField()\n {\n var text = @\"\npublic class ClassX\n{\n int i; // CS0169, i is not used anywhere\n\n public static void Main()\n {\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (4,8): warning CS0169: The field 'ClassX.i' is never used\n // int i; // CS0169, i is not used anywhere\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"i\").WithArguments(\"ClassX.i\")\n );\n }\n\n [Fact]\n public void CS0169WRN_UnreferencedField02()\n {\n var text =\n@\"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(\"\"OtherAssembly\"\")]\n\ninternal class InternalClass\n{\n internal int ActuallyInternal;\n internal int ActuallyInternalAssigned = 0;\n private int ActuallyPrivate;\n private int ActuallyPrivateAssigned = 0;\n public int EffectivelyInternal;\n public int EffectivelyInternalAssigned = 0;\n\n private class PrivateClass\n {\n public int EffectivelyPrivate;\n public int EffectivelyPrivateAssigned = 0;\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (7,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used\n // private int ActuallyPrivate;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"ActuallyPrivate\").WithArguments(\"InternalClass.ActuallyPrivate\"),\n // (8,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used\n // private int ActuallyPrivateAssigned = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"ActuallyPrivateAssigned\").WithArguments(\"InternalClass.ActuallyPrivateAssigned\"),\n // (14,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0\n // public int EffectivelyPrivate;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"EffectivelyPrivate\").WithArguments(\"InternalClass.PrivateClass.EffectivelyPrivate\", \"0\")\n );\n }\n\n [Fact]\n public void CS0169WRN_UnreferencedField03()\n {\n var text =\n@\"internal class InternalClass\n{\n internal int ActuallyInternal;\n internal int ActuallyInternalAssigned = 0;\n private int ActuallyPrivate;\n private int ActuallyPrivateAssigned = 0;\n public int EffectivelyInternal;\n public int EffectivelyInternalAssigned = 0;\n\n private class PrivateClass\n {\n public int EffectivelyPrivate;\n public int EffectivelyPrivateAssigned = 0;\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (3,18): warning CS0649: Field 'InternalClass.ActuallyInternal' is never assigned to, and will always have its default value 0\n // internal int ActuallyInternal;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"ActuallyInternal\").WithArguments(\"InternalClass.ActuallyInternal\", \"0\"),\n // (5,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used\n // private int ActuallyPrivate;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"ActuallyPrivate\").WithArguments(\"InternalClass.ActuallyPrivate\"),\n // (6,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used\n // private int ActuallyPrivateAssigned = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"ActuallyPrivateAssigned\").WithArguments(\"InternalClass.ActuallyPrivateAssigned\"),\n // (7,16): warning CS0649: Field 'InternalClass.EffectivelyInternal' is never assigned to, and will always have its default value 0\n // public int EffectivelyInternal;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"EffectivelyInternal\").WithArguments(\"InternalClass.EffectivelyInternal\", \"0\"),\n // (12,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0\n // public int EffectivelyPrivate;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"EffectivelyPrivate\").WithArguments(\"InternalClass.PrivateClass.EffectivelyPrivate\", \"0\")\n );\n }\n\n [Fact]\n public void CS0183WRN_IsAlwaysTrue()\n {\n var text = @\"using System;\npublic class IsTest10\n{\n public static int Main(String[] args)\n {\n Object obj3 = null;\n String str2 = \"\"Is 'is' too strict, per error CS0183?\"\";\n obj3 = str2;\n\n if (str2 is Object) // no error CS0183\n Console.WriteLine(\"\"str2 is Object\"\");\n\n Int32 int2 = 1;\n if (int2 is Object) // error CS0183\n Console.WriteLine(\"\"int2 is Object\"\");\n\n return 0;\n }\n}\n\";\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.WRN_IsAlwaysTrue, Line = 14, Column = 13, IsWarning = true });\n\n // TODO: extra checking\n }\n\n // Note: CS0184 tests moved to CodeGenOperator.cs to include IL verification.\n\n [WorkItem(530361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361\")]\n [Fact]\n public void CS0197WRN_ByRefNonAgileField()\n {\n var text = @\"\nclass X : System.MarshalByRefObject\n{\n public int i;\n}\n\nclass M\n{\n public int i;\n static void AddSeventeen(ref int i)\n {\n i += 17;\n }\n\n static void Main()\n {\n X x = new X();\n x.i = 12;\n AddSeventeen(ref x.i); // CS0197\n\n // OK\n M m = new M();\n m.i = 12;\n AddSeventeen(ref m.i);\n }\n}\n \";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,24): warning CS0197: Passing 'X.i' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // AddSeventeen(ref x.i); // CS0197\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"x.i\").WithArguments(\"X.i\"));\n }\n\n [WorkItem(530361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361\")]\n [Fact]\n public void CS0197WRN_ByRefNonAgileField_RefKind()\n {\n var text = @\"\nclass NotByRef\n{\n public int Instance;\n public static int Static;\n}\n\nclass ByRef : System.MarshalByRefObject\n{\n public int Instance;\n public static int Static;\n}\n\nclass Test\n{\n void M(ByRef b, NotByRef n)\n {\n None(n.Instance);\n Out(out n.Instance);\n Ref(ref n.Instance);\n\n None(NotByRef.Static);\n Out(out NotByRef.Static);\n Ref(ref NotByRef.Static);\n\n None(b.Instance);\n Out(out b.Instance);\n Ref(ref b.Instance);\n\n None(ByRef.Static);\n Out(out ByRef.Static);\n Ref(ref ByRef.Static);\n }\n\n void None(int x) { throw null; }\n void Out(out int x) { throw null; }\n void Ref(ref int x) { throw null; }\n}\n \";\n CreateCompilation(text).VerifyDiagnostics(\n // (27,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Out(out b.Instance);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"b.Instance\").WithArguments(\"ByRef.Instance\"),\n // (28,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Ref(ref b.Instance);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"b.Instance\").WithArguments(\"ByRef.Instance\"));\n }\n\n [WorkItem(530361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361\")]\n [Fact]\n public void CS0197WRN_ByRefNonAgileField_Receiver()\n {\n var text = @\"\nusing System;\n\nclass ByRef : MarshalByRefObject\n{\n public int F;\n\n protected void Ref(ref int x) { }\n\n void Test()\n {\n Ref(ref F);\n\n Ref(ref this.F);\n Ref(ref ((ByRef)this).F);\n }\n}\n\nclass Derived : ByRef\n{\n void Test()\n {\n Ref(ref F);\n\n Ref(ref this.F);\n Ref(ref ((ByRef)this).F);\n\n Ref(ref base.F);\n //Ref(ref ((ByRef)base).F);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Ref(ref ((ByRef)this).F);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"((ByRef)this).F\").WithArguments(\"ByRef.F\"),\n // (26,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Ref(ref ((ByRef)this).F);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"((ByRef)this).F\").WithArguments(\"ByRef.F\"));\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg01()\n {\n var text = @\"public class MyClass\n{\n public static void Main()\n {\n int a = 0; // CS0219\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,13): warning CS0219: The variable 'a' is assigned but its value is never used\n // int a = 0; // CS0219\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"a\").WithArguments(\"a\")\n );\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg02()\n {\n var text = @\"\npublic class clx\n{\n static void Main(string[] args)\n {\n int x = 1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\").WithLocation(6, 13));\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg03()\n {\n var text = @\"\npublic class clx\n{\n static void Main(string[] args)\n {\n int? x;\n x = null;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\").WithLocation(6, 14));\n }\n\n [Fact, WorkItem(542473, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542473\"), WorkItem(542474, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542474\")]\n public void CS0219WRN_UnreferencedVarAssg_StructString()\n {\n var text = @\"\nclass program\n{\n static void Main(string[] args)\n {\n s1 y = new s1();\n string s = \"\"\"\";\n }\n}\nstruct s1 { }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,12): warning CS0219: The variable 'y' is assigned but its value is never used\n // s1 y = new s1();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"y\").WithArguments(\"y\").WithLocation(6, 12),\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"s\").WithArguments(\"s\").WithLocation(7, 16)\n );\n }\n\n [Fact, WorkItem(542494, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542494\")]\n public void CS0219WRN_UnreferencedVarAssg_Default()\n {\n var text = @\"\nclass S\n{\n public int x = 5;\n}\n\nclass C\n{\n public static void Main()\n {\n var x = default(S);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,13): warning CS0219: The variable 'x' is assigned but its value is never used\n // var x = default(S);\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\").WithLocation(11, 13)\n );\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg_For()\n {\n var text = @\"\nclass C\n{\n public static void Main()\n {\n for (int i = 1; ; )\n {\n break;\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,18): warning CS0219: The variable 'i' is assigned but its value is never used\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"i\").WithArguments(\"i\").WithLocation(6, 18)\n );\n }\n\n [Fact, WorkItem(546619, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546619\")]\n public void NoCS0219WRN_UnreferencedVarAssg_ObjectInitializer()\n {\n var text = @\"\nstruct S\n{\n public int X { set {} }\n}\nclass C\n{\n public static void Main()\n {\n S s = new S { X = 2 }; // no error - not a constant\n int? i = new int? { }; // ditto - not the default value (though bitwise equal to it)\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(542472, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542472\")]\n public void CS0251WRN_NegativeArrayIndex()\n {\n var text = @\"\nclass C\n{\n static void Main()\n {\n int[] a = new int[1];\n int[,] b = new int[1, 1];\n a[-1] = 1; // CS0251\n a[-1, -1] = 1; // Dev10 reports CS0022 and CS0251 (twice), Roslyn reports CS0022\n b[-1] = 1; // CS0022\n b[-1, -1] = 1; // fine\n }\n}\n \";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,11): warning CS0251: Indexing an array with a negative index (array indices always start at zero)\n Diagnostic(ErrorCode.WRN_NegativeArrayIndex, \"-1\"),\n // (9,9): error CS0022: Wrong number of indices inside []; expected '1'\n Diagnostic(ErrorCode.ERR_BadIndexCount, \"a[-1, -1]\").WithArguments(\"1\"),\n // (10,9): error CS0022: Wrong number of indices inside []; expected '2'\n Diagnostic(ErrorCode.ERR_BadIndexCount, \"b[-1]\").WithArguments(\"2\"));\n }\n\n [WorkItem(530362, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362\"), WorkItem(670322, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322\")]\n [Fact]\n public void CS0252WRN_BadRefCompareLeft()\n {\n var text =\n@\"class MyClass\n{\n public static void Main()\n {\n string s = \"\"11\"\";\n object o = s + s;\n\n bool b = o == s; // CS0252\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,16): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'\n // bool b = o == s; // CS0252\n Diagnostic(ErrorCode.WRN_BadRefCompareLeft, \"o == s\").WithArguments(\"string\")\n );\n }\n\n [WorkItem(781070, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070\")]\n [Fact]\n public void CS0252WRN_BadRefCompareLeft_02()\n {\n var text =\n@\"using System;\n\npublic class Symbol\n{\n public static bool operator ==(Symbol a, Symbol b)\n {\n return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b);\n }\n public static bool operator !=(Symbol a, Symbol b)\n {\n return !(a == b);\n }\n public override bool Equals(object obj)\n {\n return (obj is Symbol || obj == null) ? this == (Symbol)obj : false;\n }\n public override int GetHashCode()\n {\n return 0;\n }\n}\n\npublic class MethodSymbol : Symbol\n{\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n MethodSymbol a1 = null;\n MethodSymbol a2 = new MethodSymbol();\n\n // In these cases the programmer explicitly inserted a cast to use object equality instead\n // of the user-defined equality operator. Since the programmer did this explicitly, in\n // Roslyn we suppress the diagnostic that was given by the native compiler suggesting casting\n // the object-typed operand back to type Symbol to get value equality.\n Console.WriteLine((object)a1 == a2);\n Console.WriteLine((object)a1 != a2);\n Console.WriteLine((object)a2 == a1);\n Console.WriteLine((object)a2 != a1);\n\n Console.WriteLine(a1 == (object)a2);\n Console.WriteLine(a1 != (object)a2);\n Console.WriteLine(a2 == (object)a1);\n Console.WriteLine(a2 != (object)a1);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [WorkItem(781070, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070\")]\n [Fact]\n public void CS0252WRN_BadRefCompareLeft_03()\n {\n var text =\n@\"using System;\n\npublic class Symbol\n{\n public static bool operator ==(Symbol a, Symbol b)\n {\n return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b);\n }\n public static bool operator !=(Symbol a, Symbol b)\n {\n return !(a == b);\n }\n public override bool Equals(object obj)\n {\n return (obj is Symbol || obj == null) ? this == (Symbol)obj : false;\n }\n public override int GetHashCode()\n {\n return 0;\n }\n}\n\npublic class MethodSymbol : Symbol\n{\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Object a1 = null;\n MethodSymbol a2 = new MethodSymbol();\n\n Console.WriteLine(a1 == a2);\n Console.WriteLine(a1 != a2);\n Console.WriteLine(a2 == a1);\n Console.WriteLine(a2 != a1);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (34,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol'\n // Console.WriteLine(a1 == a2);\n Diagnostic(ErrorCode.WRN_BadRefCompareLeft, \"a1 == a2\").WithArguments(\"Symbol\"),\n // (35,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol'\n // Console.WriteLine(a1 != a2);\n Diagnostic(ErrorCode.WRN_BadRefCompareLeft, \"a1 != a2\").WithArguments(\"Symbol\"),\n // (36,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol'\n // Console.WriteLine(a2 == a1);\n Diagnostic(ErrorCode.WRN_BadRefCompareRight, \"a2 == a1\").WithArguments(\"Symbol\"),\n // (37,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol'\n // Console.WriteLine(a2 != a1);\n Diagnostic(ErrorCode.WRN_BadRefCompareRight, \"a2 != a1\").WithArguments(\"Symbol\")\n );\n }\n\n [WorkItem(530362, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362\"), WorkItem(670322, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322\")]\n [Fact]\n public void CS0253WRN_BadRefCompareRight()\n {\n var text =\n@\"\nclass MyClass\n{\n public static void Main()\n {\n string s = \"\"11\"\";\n object o = s + s;\n\n bool c = s == o; // CS0253\n // try the following line instead\n // bool c = s == (string)o;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,16): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string'\n // bool c = s == o; // CS0253\n Diagnostic(ErrorCode.WRN_BadRefCompareRight, \"s == o\").WithArguments(\"string\")\n );\n }\n\n [WorkItem(730177, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730177\")]\n [Fact]\n public void CS0253WRN_BadRefCompare_None()\n {\n var text =\n@\"using System;\nclass MyClass\n{\n public static void Main()\n {\n MulticastDelegate x1 = null;\n bool b1 = x1 == null;\n bool b2 = x1 != null;\n bool b3 = null == x1;\n bool b4 = null != x1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [WorkItem(542399, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542399\")]\n [Fact]\n public void CS0278WRN_PatternIsAmbiguous01()\n {\n var text = @\"\nusing System.Collections.Generic;\npublic class myTest \n{\n public static void TestForeach(W w) \n where W: IEnumerable, IEnumerable\n {\n foreach (int i in w) {} // CS0278\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,25): warning CS0278: 'W' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable.GetEnumerator()'.\n // foreach (int i in w) {} // CS0278\n Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"w\").WithArguments(\"W\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\"),\n // (8,25): error CS1640: foreach statement cannot operate on variables of type 'W' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable'; try casting to a specific interface instantiation\n // foreach (int i in w) {} // CS0278\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"w\").WithArguments(\"W\", \"System.Collections.Generic.IEnumerable\"));\n }\n\n [Fact]\n public void CS0278WRN_PatternIsAmbiguous02()\n {\n var text =\n@\"using System.Collections;\nusing System.Collections.Generic;\nclass A : IEnumerable\n{\n public IEnumerator GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass B : IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass C : IEnumerable, IEnumerable\n{\n public IEnumerator GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass D : IEnumerable, IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass E\n{\n static void M(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10)\n where T1 : A, IEnumerable // duplicate interfaces\n where T2 : B, IEnumerable // duplicate interfaces\n where T3 : A, IEnumerable, IEnumerable // multiple interfaces\n where T4 : B, IEnumerable, IEnumerable // multiple interfaces\n where T5 : C, IEnumerable // multiple interfaces\n where T6 : D, IEnumerable // multiple interfaces\n where T7 : A, IEnumerable, IEnumerable // duplicate and multiple interfaces\n where T8 : B, IEnumerable, IEnumerable // duplicate and multiple interfaces\n where T9 : C, IEnumerable // duplicate and multiple interfaces\n where T10 : D, IEnumerable // duplicate and multiple interfaces\n {\n foreach (A o in t1) { }\n foreach (B o in t2) { }\n foreach (A o in t3) { }\n foreach (var o in t4) { }\n foreach (C o in t5) { }\n foreach (int o in t6) { }\n foreach (A o in t7) { }\n foreach (var o in t8) { }\n foreach (C o in t9) { }\n foreach (D o in t10) { }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (42,27): warning CS0278: 'T4' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable.GetEnumerator()'.\n Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"t4\").WithArguments(\"T4\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\").WithLocation(42, 27),\n // (42,27): error CS1640: foreach statement cannot operate on variables of type 'T4' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable'; try casting to a specific interface instantiation\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"t4\").WithArguments(\"T4\", \"System.Collections.Generic.IEnumerable\").WithLocation(42, 27),\n // (46,27): warning CS0278: 'T8' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable.GetEnumerator()'.\n Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"t8\").WithArguments(\"T8\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\").WithLocation(46, 27),\n // (46,27): error CS1640: foreach statement cannot operate on variables of type 'T8' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable'; try casting to a specific interface instantiation\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"t8\").WithArguments(\"T8\", \"System.Collections.Generic.IEnumerable\").WithLocation(46, 27));\n }\n\n [Fact]\n public void CS0279WRN_PatternStaticOrInaccessible()\n {\n var text = @\"\nusing System.Collections;\n\npublic class myTest : IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n\n internal IEnumerator GetEnumerator()\n {\n return null;\n }\n\n public static void Main()\n {\n foreach (int i in new myTest()) {} // CS0279\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,27): warning CS0279: 'myTest' does not implement the 'collection' pattern. 'myTest.GetEnumerator()' is not a public instance or extension method.\n Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, \"new myTest()\").WithArguments(\"myTest\", \"collection\", \"myTest.GetEnumerator()\"));\n }\n\n [Fact]\n public void CS0280WRN_PatternBadSignature()\n {\n var text = @\"\nusing System.Collections;\n\npublic class ValidBase: IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n\n internal IEnumerator GetEnumerator()\n {\n return null;\n }\n}\n\nclass Derived : ValidBase\n{\n // field, not method\n new public int GetEnumerator;\n}\n\npublic class Test\n{\n public static void Main()\n {\n foreach (int i in new Derived()) {} // CS0280\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (27,25): warning CS0280: 'Derived' does not implement the 'collection' pattern. 'Derived.GetEnumerator' has the wrong signature.\n // foreach (int i in new Derived()) {} // CS0280\n Diagnostic(ErrorCode.WRN_PatternBadSignature, \"new Derived()\").WithArguments(\"Derived\", \"collection\", \"Derived.GetEnumerator\"),\n // (20,19): warning CS0649: Field 'Derived.GetEnumerator' is never assigned to, and will always have its default value 0\n // new public int GetEnumerator;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"GetEnumerator\").WithArguments(\"Derived.GetEnumerator\", \"0\")\n );\n }\n\n [Fact]\n public void CS0414WRN_UnreferencedFieldAssg()\n {\n var text = @\"\nclass C\n{\n private int i = 1; // CS0414\n\n public static void Main()\n { }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (4,16): warning CS0414: The field 'C.i' is assigned but its value is never used\n // private int i = 1; // CS0414\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"i\").WithArguments(\"C.i\")\n );\n }\n\n [Fact]\n public void CS0414WRN_UnreferencedFieldAssg02()\n {\n var text =\n@\"class S\n{\n T1 t1_field = default(T1);\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (3,8): warning CS0414: The field 'S.t1_field' is assigned but its value is never used\n // T1 t1_field = default(T1);\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"t1_field\").WithArguments(\"S.t1_field\").WithLocation(3, 8)\n );\n }\n\n [Fact]\n public void CS0419WRN_AmbiguousXMLReference()\n {\n var text = @\"\ninterface I\n{\n void F();\n void F(int i);\n}\npublic class MyClass\n{\n /// \n public static void MyMethod(int i)\n {\n }\n public static void Main ()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,14): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass'\n // public class MyClass\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"MyClass\").WithArguments(\"MyClass\"),\n // (9,19): warning CS0419: Ambiguous reference in cref attribute: 'I.F'. Assuming 'I.F()', but could have also matched other overloads including 'I.F(int)'.\n // /// \n Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, \"I.F\").WithArguments(\"I.F\", \"I.F()\", \"I.F(int)\"),\n // (13,23): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass.Main()'\n // public static void Main ()\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"Main\").WithArguments(\"MyClass.Main()\"));\n }\n\n [Fact]\n public void CS0420WRN_VolatileByRef()\n {\n var text = @\"\nclass TestClass\n{\n private volatile int i;\n\n public void TestVolatileRef(ref int ii)\n {\n }\n\n public void TestVolatileOut(out int ii)\n {\n ii = 0;\n }\n\n public static void Main()\n {\n TestClass x = new TestClass();\n x.TestVolatileRef(ref x.i); // CS0420 \n x.TestVolatileOut(out x.i); // CS0420 \n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x.i\").WithArguments(\"TestClass.i\"),\n // (19,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x.i\").WithArguments(\"TestClass.i\"));\n }\n\n [Fact]\n public void CS0420WRN_VolatileByRef_Suppressed()\n {\n var text = @\"\nusing System.Threading;\n\nclass TestClass\n{\n private static volatile int x = 0;\n\n public static void TestVolatileByRef()\n {\n Interlocked.Increment(ref x); // no CS0420 \n Interlocked.Decrement(ref x); // no CS0420\n Interlocked.Add(ref x, 0); // no CS0420\n Interlocked.CompareExchange(ref x, 0, 0); // no CS0420\n Interlocked.Exchange(ref x, 0); // no CS0420\n\n // using fully qualified name\n System.Threading.Interlocked.Increment(ref x); // no CS0420 \n System.Threading.Interlocked.Decrement(ref x); // no CS0420\n System.Threading.Interlocked.Add(ref x, 0); // no CS0420\n System.Threading.Interlocked.CompareExchange(ref x, 0, 0); // no CS0420\n System.Threading.Interlocked.Exchange(ref x, 0); // no CS0420\n\n // passing volatile variables in a nested way\n Interlocked.Increment(ref Method1(ref x).y); // CS0420 for x \n Interlocked.Decrement(ref Method1(ref x).y); // CS0420 for x\n Interlocked.Add(ref Method1(ref x).y, 0); // CS0420 for x\n Interlocked.CompareExchange(ref Method1(ref x).y, 0, 0); // CS0420 for x\n Interlocked.Exchange(ref Method1(ref x).y, 0); // CS0420 for x\n\n // located as a function argument \n goo(Interlocked.Increment(ref x)); // no CS0420\n\n }\n\n public static int goo(int x)\n {\n return x; \n } \n\n public static MyClass Method1(ref int x)\n {\n return new MyClass();\n }\n\n public class MyClass\n {\n public volatile int y = 0;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (24,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (25,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (26,39): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (27,51): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (28,44): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"));\n }\n\n [WorkItem(728380, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728380\")]\n [Fact]\n public void Repro728380()\n {\n var source = @\"\nclass Test\n{\n static volatile int x;\n unsafe static void goo(int* pX) { }\n\n static int Main()\n {\n unsafe { Test.goo(&x); }\n return 1;\n }\n}\n\";\n CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,27): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer\n // unsafe { Test.goo(&x); }\n Diagnostic(ErrorCode.ERR_FixedNeeded, \"&x\"),\n // (9,28): warning CS0420: 'Test.x': a reference to a volatile field will not be treated as volatile\n // unsafe { Test.goo(&x); }\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"Test.x\"));\n }\n\n [Fact, WorkItem(528275, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275\")]\n public void CS0429WRN_UnreachableExpr()\n {\n var text = @\"\npublic class cs0429 \n{\n public static void Main() \n {\n if (false && myTest()) // CS0429\n // Try the following line instead:\n // if (true && myTest())\n {\n }\n else\n {\n int i = 0;\n i++;\n }\n }\n\n static bool myTest() { return true; }\n}\n\";\n // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions.\n // We don't report the warning.\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(528275, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275\"), WorkItem(530071, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530071\")]\n public void CS0429WRN_UnreachableExpr_02()\n {\n var text = @\"\nclass Program\n{\n static bool b = true;\n const bool con = true;\n static void Main(string[] args)\n {\n int x = 1;\n int y = 1;\n int s = true ? x++ : y++; // y++ unreachable\n s = x == y ? x++ : y++; // OK\n s = con ? x++ : y++; // y++ unreachable\n bool con1 = true;\n s = con1 ? x++ : y++; // OK\n s = b ? x++ : y++;\n s = 1 < 2 ? x++ : y++; \t// y++ unreachable\n }\n}\n\";\n // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions.\n // We don't report the warning.\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(543943, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543943\")]\n public void CS0458WRN_AlwaysNull()\n {\n var text = @\"\npublic class Test \n{\n public static void Main()\n {\n int? x = 0;\n\n x = null + x;\n x = x + default(int?);\n x += new int?();\n\n x = null - x;\n x = x - default(int?);\n x -= new int?();\n\n x = null * x;\n x = x * default(int?);\n x *= new int?();\n\n x = null / x;\n x = x / default(int?);\n x /= new int?();\n\n x = null % x;\n x = x % default(int?);\n x %= new int?();\n\n x = null << x;\n x = x << default(int?);\n x <<= new int?();\n\n x = null >> x;\n x = x >> default(int?);\n x >>= new int?();\n \n x = null & x;\n x = x & default(int?);\n x &= new int?();\n\n x = null | x;\n x = x | default(int?);\n x |= new int?();\n\n x = null ^ x;\n x = x ^ default(int?);\n x ^= new int?();\n\n //The below block of code should not raise a warning\n bool? y = null;\n y = y & null;\n y = y |false;\n y = true | null;\n\n double? d = +default(double?);\n int? i = -default(int?);\n long? l = ~default(long?);\n bool? b = !default(bool?);\n\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null + x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x + default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x += new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null - x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x - default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x -= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null * x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x * default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x *= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null / x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x / default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x /= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null % x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x % default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x %= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null << x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x << default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x <<= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null >> x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x >> default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x >>= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null & x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x & default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x &= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null | x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x | default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x |= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null ^ x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x ^ default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x ^= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"+default(double?)\").WithArguments(\"double?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"-default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"~default(long?)\").WithArguments(\"long?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"!default(bool?)\").WithArguments(\"bool?\")\n );\n }\n\n [Fact]\n public void CS0464WRN_CmpAlwaysFalse()\n {\n var text = @\"\nclass MyClass\n{\n public struct S\n {\n public static bool operator <(S x, S y) { return true; } \n public static bool operator >(S x, S y) { return true; }\n public static bool operator <=(S x, S y) { return true; } \n public static bool operator >=(S x, S y) { return true; }\n\n }\n\n public static void W(bool b)\n {\n System.Console.Write(b ? 't' : 'f');\n }\n\n public static void Main()\n {\n S s = default(S);\n S? t = s;\n int i = 0;\n int? n = i;\n\n W(i < null); // CS0464\n W(i <= null); // CS0464\n W(i > null); // CS0464\n W(i >= null); // CS0464\n\n W(n < null); // CS0464\n W(n <= null); // CS0464\n W(n > null); // CS0464\n W(n >= null); // CS0464\n\n W(s < null); // CS0464\n W(s <= null); // CS0464\n W(s > null); // CS0464\n W(s >= null); // CS0464\n\n W(t < null); // CS0464\n W(t <= null); // CS0464\n W(t > null); // CS0464\n W(t >= null); // CS0464\n\n W(i < default(short?)); // CS0464\n W(i <= default(short?)); // CS0464\n W(i > default(short?)); // CS0464\n W(i >= default(short?)); // CS0464\n\n W(n < default(short?)); // CS0464\n W(n <= default(short?)); // CS0464\n W(n > default(short?)); // CS0464\n W(n >= default(short?)); // CS0464\n\n W(s < default(S?)); // CS0464\n W(s <= default(S?)); // CS0464\n W(s > default(S?)); // CS0464\n W(s >= default(S?)); // CS0464\n\n W(t < default(S?)); // CS0464\n W(t <= default(S?)); // CS0464\n W(t > default(S?)); // CS0464\n W(t >= default(S?)); // CS0464\n\n W(i < new sbyte?()); // CS0464\n W(i <= new sbyte?()); // CS0464\n W(i > new sbyte?()); // CS0464\n W(i >= new sbyte?()); // CS0464\n\n W(n < new sbyte?()); // CS0464\n W(n <= new sbyte?()); // CS0464\n W(n > new sbyte?()); // CS0464\n W(n >= new sbyte?()); // CS0464\n\n W(s < new S?()); // CS0464\n W(s <= new S?()); // CS0464\n W(s > new S?()); // CS0464\n W(s >= new S?()); // CS0464\n\n W(t < new S?()); // CS0464\n W(t <= new S?()); // CS0464\n W(t > new S?()); // CS0464\n W(t >= new S?()); // CS0464\n\n System.Console.WriteLine();\n\n W(null < i); // CS0464\n W(null <= i); // CS0464\n W(null > i); // CS0464\n W(null >= i); // CS0464\n\n W(null < n); // CS0464\n W(null <= n); // CS0464\n W(null > n); // CS0464\n W(null >= n); // CS0464\n\n W(null < s); // CS0464\n W(null <= s); // CS0464\n W(null > s); // CS0464\n W(null >= s); // CS0464\n\n W(null < t); // CS0464\n W(null <= t); // CS0464\n W(null > t); // CS0464\n W(null >= t); // CS0464\n\n W(default(short?) < i); // CS0464\n W(default(short?) <= i); // CS0464\n W(default(short?) > i); // CS0464\n W(default(short?) >= i); // CS0464\n\n W(default(short?) < n); // CS0464\n W(default(short?) <= n); // CS0464\n W(default(short?) > n); // CS0464\n W(default(short?) >= n); // CS0464\n\n W(default(S?) < s); // CS0464\n W(default(S?) <= s); // CS0464\n W(default(S?) > s); // CS0464\n W(default(S?) >= s); // CS0464\n\n W(default(S?) < t); // CS0464\n W(default(S?) <= t); // CS0464\n W(default(S?) > t); // CS0464\n W(default(S?) >= t); // CS0464\n\n W(new sbyte?() < i); // CS0464\n W(new sbyte?() <= i); // CS0464\n W(new sbyte?() > i); // CS0464\n W(new sbyte?() >= i); // CS0464\n\n W(new sbyte?() < n); // CS0464\n W(new sbyte?() <= n); // CS0464\n W(new sbyte?() > n); // CS0464\n W(new sbyte?() > n); // CS0464\n\n W(new S?() < s); // CS0464\n W(new S?() <= s); // CS0464\n W(new S?() > s); // CS0464\n W(new S?() >= s); // CS0464\n\n W(new S?() < t); // CS0464\n W(new S?() <= t); // CS0464\n W(new S?() > t); // CS0464\n W(new S?() > t); // CS0464\n\n System.Console.WriteLine();\n\n W(null > null); // CS0464\n W(null >= null); // CS0464\n W(null < null); // CS0464\n W(null <= null); // CS0464\n }\n}\n\";\n var verifier = CompileAndVerify(source: text, expectedOutput: @\"ffffffffffffffffffffffffffffffffffffffffffffffff\nffffffffffffffffffffffffffffffffffffffffffffffff\nffff\");\n\n CreateCompilation(text).VerifyDiagnostics(\n // (25,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i < null\").WithArguments(\"int?\"),\n // (26,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i <= null\").WithArguments(\"int?\"),\n // (27,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i > null\").WithArguments(\"int?\"),\n // (28,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i >= null\").WithArguments(\"int?\"),\n // (30,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n < null\").WithArguments(\"int?\"),\n // (31,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n <= null\").WithArguments(\"int?\"),\n // (32,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n > null\").WithArguments(\"int?\"),\n // (33,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n >= null\").WithArguments(\"int?\"),\n // (35,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s < null\").WithArguments(\"MyClass.S?\"),\n // (36,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s <= null\").WithArguments(\"MyClass.S?\"),\n // (37,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s > null\").WithArguments(\"MyClass.S?\"),\n // (38,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s >= null\").WithArguments(\"MyClass.S?\"),\n // (40,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t < null\").WithArguments(\"MyClass.S?\"),\n // (41,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t <= null\").WithArguments(\"MyClass.S?\"),\n // (42,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t > null\").WithArguments(\"MyClass.S?\"),\n // (43,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t >= null\").WithArguments(\"MyClass.S?\"),\n // (45,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i < default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i < default(short?)\").WithArguments(\"short?\"),\n // (46,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i <= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i <= default(short?)\").WithArguments(\"short?\"),\n // (47,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i > default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i > default(short?)\").WithArguments(\"short?\"),\n // (48,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i >= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i >= default(short?)\").WithArguments(\"short?\"),\n // (50,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n < default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n < default(short?)\").WithArguments(\"short?\"),\n // (51,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n <= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n <= default(short?)\").WithArguments(\"short?\"),\n // (52,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n > default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n > default(short?)\").WithArguments(\"short?\"),\n // (53,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n >= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n >= default(short?)\").WithArguments(\"short?\"),\n // (55,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s < default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s < default(S?)\").WithArguments(\"MyClass.S?\"),\n // (56,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s <= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s <= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (57,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s > default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s > default(S?)\").WithArguments(\"MyClass.S?\"),\n // (58,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s >= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s >= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (60,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t < default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t < default(S?)\").WithArguments(\"MyClass.S?\"),\n // (61,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t <= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t <= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (62,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t > default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t > default(S?)\").WithArguments(\"MyClass.S?\"),\n // (63,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t >= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t >= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (65,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i < new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i < new sbyte?()\").WithArguments(\"sbyte?\"),\n // (66,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i <= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i <= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (67,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i > new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i > new sbyte?()\").WithArguments(\"sbyte?\"),\n // (68,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i >= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i >= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (70,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n < new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n < new sbyte?()\").WithArguments(\"sbyte?\"),\n // (71,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n <= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n <= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (72,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n > new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n > new sbyte?()\").WithArguments(\"sbyte?\"),\n // (73,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n >= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n >= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (75,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s < new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s < new S?()\").WithArguments(\"MyClass.S?\"),\n // (76,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s <= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s <= new S?()\").WithArguments(\"MyClass.S?\"),\n // (77,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s > new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s > new S?()\").WithArguments(\"MyClass.S?\"),\n // (78,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s >= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s >= new S?()\").WithArguments(\"MyClass.S?\"),\n // (80,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t < new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t < new S?()\").WithArguments(\"MyClass.S?\"),\n // (81,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t <= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t <= new S?()\").WithArguments(\"MyClass.S?\"),\n // (82,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t > new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t > new S?()\").WithArguments(\"MyClass.S?\"),\n // (83,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t >= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t >= new S?()\").WithArguments(\"MyClass.S?\"),\n // (87,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null < i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < i\").WithArguments(\"int?\"),\n // (88,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null <= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= i\").WithArguments(\"int?\"),\n // (89,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null > i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > i\").WithArguments(\"int?\"),\n // (90,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null >= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= i\").WithArguments(\"int?\"),\n // (92,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null < n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < n\").WithArguments(\"int?\"),\n // (93,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null <= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= n\").WithArguments(\"int?\"),\n // (94,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > n\").WithArguments(\"int?\"),\n // (95,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null >= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= n\").WithArguments(\"int?\"),\n // (97,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null < s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < s\").WithArguments(\"MyClass.S?\"),\n // (98,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null <= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= s\").WithArguments(\"MyClass.S?\"),\n // (99,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null > s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > s\").WithArguments(\"MyClass.S?\"),\n // (100,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null >= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= s\").WithArguments(\"MyClass.S?\"),\n // (102,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null < t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < t\").WithArguments(\"MyClass.S?\"),\n // (103,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null <= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= t\").WithArguments(\"MyClass.S?\"),\n // (104,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > t\").WithArguments(\"MyClass.S?\"),\n // (105,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null >= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= t\").WithArguments(\"MyClass.S?\"),\n // (107,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) < i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) < i\").WithArguments(\"short?\"),\n // (108,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) <= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) <= i\").WithArguments(\"short?\"),\n // (109,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) > i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) > i\").WithArguments(\"short?\"),\n // (110,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) >= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) >= i\").WithArguments(\"short?\"),\n // (112,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) < n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) < n\").WithArguments(\"short?\"),\n // (113,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) <= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) <= n\").WithArguments(\"short?\"),\n // (114,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) > n\").WithArguments(\"short?\"),\n // (115,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) >= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) >= n\").WithArguments(\"short?\"),\n // (117,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) < s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) < s\").WithArguments(\"MyClass.S?\"),\n // (118,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) <= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) <= s\").WithArguments(\"MyClass.S?\"),\n // (119,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) > s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) > s\").WithArguments(\"MyClass.S?\"),\n // (120,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) >= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) >= s\").WithArguments(\"MyClass.S?\"),\n // (122,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) < t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) < t\").WithArguments(\"MyClass.S?\"),\n // (123,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) <= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) <= t\").WithArguments(\"MyClass.S?\"),\n // (124,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) > t\").WithArguments(\"MyClass.S?\"),\n // (125,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) >= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) >= t\").WithArguments(\"MyClass.S?\"),\n // (127,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() < i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() < i\").WithArguments(\"sbyte?\"),\n // (128,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() <= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() <= i\").WithArguments(\"sbyte?\"),\n // (129,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() > i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() > i\").WithArguments(\"sbyte?\"),\n // (130,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() >= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() >= i\").WithArguments(\"sbyte?\"),\n // (132,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() < n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() < n\").WithArguments(\"sbyte?\"),\n // (133,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() <= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() <= n\").WithArguments(\"sbyte?\"),\n // (134,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() > n\").WithArguments(\"sbyte?\"),\n // (135,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() > n\").WithArguments(\"sbyte?\"),\n // (137,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() < s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() < s\").WithArguments(\"MyClass.S?\"),\n // (138,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() <= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() <= s\").WithArguments(\"MyClass.S?\"),\n // (139,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() > s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() > s\").WithArguments(\"MyClass.S?\"),\n // (140,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() >= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() >= s\").WithArguments(\"MyClass.S?\"),\n // (142,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() < t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() < t\").WithArguments(\"MyClass.S?\"),\n // (143,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() <= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() <= t\").WithArguments(\"MyClass.S?\"),\n // (144,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() > t\").WithArguments(\"MyClass.S?\"),\n // (145,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() > t\").WithArguments(\"MyClass.S?\"),\n // (149,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > null\").WithArguments(\"int?\"),\n // (150,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= null\").WithArguments(\"int?\"),\n // (151,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < null\").WithArguments(\"int?\"),\n // (152,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= null\").WithArguments(\"int?\")\n );\n }\n\n [Fact]\n public void CS0469WRN_GotoCaseShouldConvert()\n {\n var text = @\"\nclass Test\n{\n static void Main()\n {\n char c = (char)180;\n switch (c)\n {\n case (char)127:\n break;\n\n case (char)180: \n goto case 127; // CS0469\n // try the following line instead\n // goto case (char) 127;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,13): warning CS0469: The 'goto case' value is not implicitly convertible to type 'char'\n // goto case 127; // CS0469\n Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, \"goto case 127;\").WithArguments(\"char\").WithLocation(13, 13)\n );\n }\n\n [Fact, WorkItem(663, \"https://github.com/dotnet/roslyn/issues/663\")]\n public void CS0472WRN_NubExprIsConstBool()\n {\n // Due to a long-standing bug, the native compiler does not produce warnings for \"guid == null\",\n // but does for \"int == null\". Roslyn corrects this lapse and produces warnings for both built-in\n // and user-defined lifted equality operators, but the new warnings for user-defined types are\n // only given with /warn:n where n >= 5.\n\n var text = @\"\nusing System;\nclass MyClass\n{\n public static void W(bool b)\n {\n System.Console.Write(b ? 't' : 'f');\n }\n\n enum E : int { };\n\n public static void Main()\n {\n Guid g = default(Guid);\n Guid? h = g;\n int i = 0;\n int? n = i;\n\n W(i == null); // CS0472\n W(i != null); // CS0472\n W(n == null); // no error\n W(n != null); // no error\n W(g == null); // CS0472\n W(g != null); // CS0472\n W(h == null); // no error\n W(h != null); // no error\n\n W(i == default(short?)); // CS0472\n W(i != default(short?)); // CS0472\n W(n == default(short?)); // no error\n W(n != default(short?)); // no error\n W(g == default(Guid?)); // CS0472\n W(g != default(Guid?)); // CS0472\n W(h == default(Guid?)); // no error\n W(h != default(Guid?)); // no error\n\n W(i == new sbyte?()); // CS0472\n W(i != new sbyte?()); // CS0472\n W(n == new sbyte?()); // no error\n W(n != new sbyte?()); // no error\n W(g == new Guid?()); // CS0472\n W(g != new Guid?()); // CS0472\n W(h == new Guid?()); // no error\n W(h != new Guid?()); // no error\n\n System.Console.WriteLine();\n\n\n W(null == i); // CS0472\n W(null != i); // CS0472\n W(null == n); // no error\n W(null != n); // no error\n W(null == g); // CS0472\n W(null != g); // CS0472\n W(null == h); // no error\n W(null != h); // no error\n\n W(default(long?) == i); // CS0472\n W(default(long?) != i); // CS0472\n W(default(long?) == n); // no error\n W(default(long?) != n); // no error\n W(default(Guid?) == g); // CS0472\n W(default(Guid?) != g); // CS0472\n W(default(Guid?) == h); // no error\n W(default(Guid?) != h); // no error\n\n W(new double?() == i); // CS0472\n W(new double?() != i); // CS0472\n W(new double?() == n); // no error\n W(new double?() != n); // no error\n W(new Guid?() == g); // CS0472\n W(new Guid?() != g); // CS0472\n W(new Guid?() == h); // no error\n W(new Guid?() != h); // no error\n\n System.Console.WriteLine();\n\n W(null == null); // No error, because both sides are nullable, but of course\n W(null != null); // we could give a warning here as well.\n\n System.Console.WriteLine();\n\n //check comparisons with converted constants\n W((E?)1 == null);\n W(null != (E?)1);\n\n W((int?)1 == null);\n W(null != (int?)1);\n\n //check comparisons when null is converted \n\n W(0 == (int?)null);\n W((int?)null != 0);\n \n W(0 == (E?)null);\n W((E?)null != 0);\n }\n}\n\";\n\n string expected = @\"ftftftftftftftftftftftft\nftftftftftftftftftftftft\ntf\nftftftft\";\n var fullExpected = new DiagnosticDescription[] {\n // (19,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(i == null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(19, 11),\n // (20,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(i != null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != null\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(20, 11),\n // (23,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g == null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g == null\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(23, 11),\n // (24,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g != null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g != null\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(24, 11),\n // (28,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?'\n // W(i == default(short?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == default(short?)\").WithArguments(\"false\", \"int\", \"short?\").WithLocation(28, 11),\n // (29,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'short?'\n // W(i != default(short?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != default(short?)\").WithArguments(\"true\", \"int\", \"short?\").WithLocation(29, 11),\n // (32,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g == default(Guid?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g == default(Guid?)\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(32, 11),\n // (33,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g != default(Guid?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g != default(Guid?)\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(33, 11),\n // (37,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'sbyte?'\n // W(i == new sbyte?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == new sbyte?()\").WithArguments(\"false\", \"int\", \"sbyte?\").WithLocation(37, 11),\n // (38,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'sbyte?'\n // W(i != new sbyte?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != new sbyte?()\").WithArguments(\"true\", \"int\", \"sbyte?\").WithLocation(38, 11),\n // (41,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g == new Guid?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g == new Guid?()\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(41, 11),\n // (42,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g != new Guid?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g != new Guid?()\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(42, 11),\n // (49,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(null == i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null == i\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(49, 11),\n // (50,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(null != i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != i\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(50, 11),\n // (53,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(null == g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"null == g\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(53, 11),\n // (54,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(null != g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"null != g\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(54, 11),\n // (58,11): warning CS0472: The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?'\n // W(default(long?) == i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"default(long?) == i\").WithArguments(\"false\", \"long\", \"long?\").WithLocation(58, 11),\n // (59,11): warning CS0472: The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?'\n // W(default(long?) != i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"default(long?) != i\").WithArguments(\"true\", \"long\", \"long?\").WithLocation(59, 11),\n // (62,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(default(Guid?) == g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"default(Guid?) == g\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(62, 11),\n // (63,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(default(Guid?) != g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"default(Guid?) != g\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(63, 11),\n // (67,11): warning CS0472: The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?'\n // W(new double?() == i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"new double?() == i\").WithArguments(\"false\", \"double\", \"double?\").WithLocation(67, 11),\n // (68,11): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?'\n // W(new double?() != i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"new double?() != i\").WithArguments(\"true\", \"double\", \"double?\").WithLocation(68, 11),\n // (71,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(new Guid?() == g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"new Guid?() == g\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(71, 11),\n // (72,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(new Guid?() != g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"new Guid?() != g\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(72, 11),\n // (84,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W((E?)1 == null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(E?)1 == null\").WithArguments(\"false\", \"MyClass.E\", \"MyClass.E?\").WithLocation(84, 11),\n // (85,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W(null != (E?)1);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != (E?)1\").WithArguments(\"true\", \"MyClass.E\", \"MyClass.E?\").WithLocation(85, 11),\n // (87,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W((int?)1 == null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(int?)1 == null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(87, 11),\n // (88,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(null != (int?)1);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != (int?)1\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(88, 11),\n // (92,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(0 == (int?)null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"0 == (int?)null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(92, 11),\n // (93,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W((int?)null != 0);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(int?)null != 0\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(93, 11),\n // (95,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W(0 == (E?)null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"0 == (E?)null\").WithArguments(\"false\", \"MyClass.E\", \"MyClass.E?\").WithLocation(95, 11),\n // (96,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W((E?)null != 0);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(E?)null != 0\").WithArguments(\"true\", \"MyClass.E\", \"MyClass.E?\").WithLocation(96, 11)\n };\n var compatibleExpected = fullExpected.Where(d => !d.Code.Equals((int)ErrorCode.WRN_NubExprIsConstBool2)).ToArray();\n this.CompileAndVerify(source: text, expectedOutput: expected, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(compatibleExpected);\n this.CompileAndVerify(source: text, expectedOutput: expected).VerifyDiagnostics(fullExpected);\n }\n\n [Fact]\n public void CS0472WRN_NubExprIsConstBool_ConstructorInitializer()\n {\n var text =\n@\"class A\n{\n internal A(bool b)\n {\n }\n}\nclass B : A\n{\n B(int i) : base(i == null)\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,21): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // B(int i) : base(i == null)\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(9, 21));\n }\n\n [Fact]\n public void CS0612WRN_DeprecatedSymbol()\n {\n var text = @\"\nusing System;\nclass MyClass\n{\n [Obsolete]\n public static void ObsoleteMethod()\n {\n }\n\n [Obsolete]\n public static int ObsoleteField;\n}\nclass MainClass\n{\n static public void Main()\n {\n MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated\n MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (17,7): warning CS0612: 'MyClass.ObsoleteMethod()' is obsolete\n // MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated\n Diagnostic(ErrorCode.WRN_DeprecatedSymbol, \"MyClass.ObsoleteMethod()\").WithArguments(\"MyClass.ObsoleteMethod()\"),\n // (18,7): warning CS0612: 'MyClass.ObsoleteField' is obsolete\n // MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated\n Diagnostic(ErrorCode.WRN_DeprecatedSymbol, \"MyClass.ObsoleteField\").WithArguments(\"MyClass.ObsoleteField\"));\n }\n\n [Fact, WorkItem(546062, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062\")]\n public void CS0618WRN_DeprecatedSymbol()\n {\n var text = @\"\npublic class ConsoleStub\n{\n public static void Main(string[] args)\n {\n System.Collections.CaseInsensitiveHashCodeProvider x;\n System.Console.WriteLine(x);\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (6,9): warning CS0618: 'System.Collections.CaseInsensitiveHashCodeProvider' is obsolete: 'Please use StringComparer instead.'\n // System.Collections.CaseInsensitiveHashCodeProvider x;\n Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, \"System.Collections.CaseInsensitiveHashCodeProvider\").WithArguments(\"System.Collections.CaseInsensitiveHashCodeProvider\", \"Please use StringComparer instead.\"),\n // (7,34): error CS0165: Use of unassigned local variable 'x'\n // System.Console.WriteLine(x);\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\"));\n }\n\n [WorkItem(545347, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347\")]\n [Fact]\n public void CS0649WRN_UnassignedInternalField()\n {\n var text = @\"\nusing System.Collections;\n\nclass MyClass\n{\n Hashtable table; // CS0649\n \n public void Func(object o, string p)\n {\n table[p] = o;\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,15): warning CS0649: Field 'MyClass.table' is never assigned to, and will always have its default value null\n // Hashtable table; // CS0649\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"table\").WithArguments(\"MyClass.table\", \"null\")\n );\n }\n\n [Fact, WorkItem(543454, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543454\")]\n public void CS0649WRN_UnassignedInternalField_1()\n {\n var text = @\"\npublic class GenClass { }\npublic class Outer\n{\n internal protected class C1 { }\n public class C2 { }\n internal class Test\n {\n public GenClass Fld;\n }\n public static int Main() { return 0; }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"Fld\").WithArguments(\"Outer.Test.Fld\", \"null\"));\n }\n\n [WorkItem(546449, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546449\")]\n [WorkItem(546949, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546949\")]\n [Fact]\n public void CS0652WRN_VacuousIntegralComp()\n {\n var text = @\"\npublic class Class1\n{\n private static byte i = 0;\n public static void Main()\n {\n const short j = 256;\n if (i == j) // CS0652, 256 is out of range for byte\n i = 0;\n\n // However, we do not give this warning if both sides of the comparison are constants. In those\n // cases, we are probably in machine-generated code anyways.\n\n const byte k = 0;\n if (k == j) {}\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,11): warning CS0652: Comparison to integral constant is useless; the constant is outside the range of type 'byte'\n // if (i == j) // CS0652, 256 is out of range for byte\n Diagnostic(ErrorCode.WRN_VacuousIntegralComp, \"i == j\").WithArguments(\"byte\"));\n }\n\n [WorkItem(546790, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546790\")]\n [Fact]\n public void CS0652WRN_VacuousIntegralComp_ExplicitCast()\n {\n var text = @\"\nusing System;\n\npublic class Program\n{\n public static void Main()\n {\n Int16 wSuiteMask = 0; \n const int VER_SUITE_WH_SERVER = 0x00008000;\n if (VER_SUITE_WH_SERVER == (Int32)wSuiteMask)\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0665WRN_IncorrectBooleanAssg()\n {\n var text = @\"\nclass Test\n{\n public static void Main()\n {\n bool i = false;\n\n if (i = true) // CS0665\n // try the following line instead\n // if (i == true)\n {\n }\n\n System.Console.WriteLine(i);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,11): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"i = true\"));\n }\n\n [Fact, WorkItem(540777, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777\")]\n public void CS0665WRN_IncorrectBooleanAssg_ConditionalOperator()\n {\n var text = @\"\nclass Program\n{\n static int Main(string[] args)\n {\n bool a = true;\n System.Console.WriteLine(a);\n return ((a = false) ? 50 : 100); // Warning\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"a = false\"));\n }\n\n [Fact]\n public void CS0665WRN_IncorrectBooleanAssg_Contexts()\n {\n var text = @\"\nclass C\n{\n static void Main(string[] args)\n {\n bool b = args.Length > 1;\n\n if (b = false) { }\n while (b = false) { }\n do { } while (b = false);\n for (; b = false; ) { }\n System.Console.WriteLine((b = false) ? 1 : 2);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,13): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // if (b = false) { }\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (9,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // while (b = false) { }\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (10,23): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // do { } while (b = false);\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (11,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // for (; b = false; ) { }\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (12,35): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // System.Console.WriteLine((b = false) ? 1 : 2);\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"));\n }\n\n [Fact]\n public void CS0665WRN_IncorrectBooleanAssg_Nesting()\n {\n var text = @\"\nclass C\n{\n static void Main(string[] args)\n {\n bool b = args.Length > 1;\n\n if ((b = false)) { } // parens - warn\n if (((b = false))) { } // more parens - warn\n if (M(b = false)) { } // call - do not warn\n if ((bool)(b = false)) { } // cast - do not warn\n if ((b = false) || (b = true)) { } // binary operator - do not warn\n\n B bb = new B();\n if (bb = false) { } // implicit conversion - do not warn\n }\n\n static bool M(bool b) { return b; }\n}\n\nclass B\n{\n public static implicit operator B(bool b)\n {\n return new B();\n }\n\n public static bool operator true(B b)\n {\n return true;\n }\n\n public static bool operator false(B b)\n {\n return false;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,14): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // if ((b = false)) { } // parens - warn\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (9,15): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // if (((b = false))) { } // more parens - warn\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"));\n }\n\n [Fact, WorkItem(909, \"https://github.com/dotnet/roslyn/issues/909\")]\n public void CS0675WRN_BitwiseOrSignExtend()\n {\n var text = @\"\npublic class sign\n{\n public static void Main()\n {\n int i32_hi = 1;\n int i32_lo = 1;\n ulong u64 = 1;\n sbyte i08 = 1;\n short i16 = -1;\n\n object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675\n object v2 = (ulong)i32_hi | u64; // CS0675\n object v3 = (ulong)i32_hi | (ulong)i32_lo; // No warning; the sign extension bits are the same on both sides.\n object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675\n object v5 = (int)i08 | (int)i32_lo; // No warning; sign extension is considered to be 'expected' when casting.\n object v6 = (((ulong)i32_hi) << 32) | (uint) i32_lo; // No warning; we've cast to a smaller unsigned type first. \n // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one:\n object v7 = 0x0000BEEFU | (uint)i16; \n object v8 = 0xFFFFBEEFU | (uint)i16; \n object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 \n\n// We should do the exact same logic for nullables.\n\n int? ni32_hi = 1;\n int? ni32_lo = 1;\n ulong? nu64 = 1;\n sbyte? ni08 = 1;\n short? ni16 = -1;\n\n object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675\n object v12 = (ulong?)ni32_hi | nu64; // CS0675\n object v13 = (ulong?)ni32_hi | (ulong?)ni32_lo; // No warning; the sign extension bits are the same on both sides.\n object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675\n object v15 = (int?)ni08 | (int?)ni32_lo; // No warning; sign extension is considered to be 'expected' when casting.\n object v16 = (((ulong?)ni32_hi) << 32) | (uint?) ni32_lo; // No warning; we've cast to a smaller unsigned type first. \n // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one:\n object v17 = 0x0000BEEFU | (uint?)ni16; \n object v18 = 0xFFFFBEEFU | (uint?)ni16; \n object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 \n }\n}\n\nclass Test\n{\n static void Main()\n {\n long bits = 0;\n for (int i = 0; i < 32; i++)\n {\n if (i % 2 == 0)\n {\n bits |= (1 << i);\n bits = bits | (1 << i);\n }\n }\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (12,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(((long)i32_hi) << 32) | i32_lo\"),\n // (13,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v2 = (ulong)i32_hi | u64; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong)i32_hi | u64\"),\n // (15,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong)(uint)(ushort)i08 | (ulong)i32_lo\"),\n // (21,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 \n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"0xDEADBEEFU | (uint)i16\"),\n // (31,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(((long?)ni32_hi) << 32) | ni32_lo\"),\n // (32,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v12 = (ulong?)ni32_hi | nu64; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong?)ni32_hi | nu64\"),\n // (34,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo\"),\n // (40,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 \n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"0xDEADBEEFU | (uint?)ni16\"),\n // (53,17): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // bits |= (1 << i);\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"bits |= (1 << i)\").WithLocation(53, 17),\n // (54,24): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // bits = bits | (1 << i);\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"bits | (1 << i)\").WithLocation(54, 24)\n );\n }\n\n [Fact]\n public void CS0728WRN_AssignmentToLockOrDispose01()\n {\n CreateCompilation(@\"\nusing System;\npublic class ValidBase : IDisposable\n{\n public void Dispose() { }\n}\n\npublic class Logger\n{\n public static void dummy()\n {\n ValidBase vb = null;\n using (vb) \n {\n vb = null; // CS0728\n }\n vb = null;\n }\n public static void Main() { }\n}\")\n .VerifyDiagnostics(\n // (15,13): warning CS0728: Possibly incorrect assignment to local 'vb' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.\n Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, \"vb\").WithArguments(\"vb\"));\n }\n\n [Fact]\n public void CS0728WRN_AssignmentToLockOrDispose02()\n {\n CreateCompilation(\n@\"class D : System.IDisposable\n{\n public void Dispose() { }\n}\nclass C\n{\n static void M()\n {\n D d = new D();\n using (d)\n {\n N(ref d);\n }\n lock (d)\n {\n N(ref d);\n }\n }\n static void N(ref D d)\n {\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, \"d\").WithArguments(\"d\").WithLocation(12, 19),\n Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, \"d\").WithArguments(\"d\").WithLocation(16, 19));\n }\n\n [WorkItem(543615, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615\"), WorkItem(546550, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546550\")]\n [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]\n public void CS0811ERR_DebugFullNameTooLong()\n {\n var text = @\"\nusing System;\nusing System.Collections.Generic;\n\nnamespace TestNamespace\n{\n using VeryLong = List>>>>>>>>>>>>>>>>>>>>>>>>>>>; // CS0811\n\n class Test\n {\n static int Main()\n {\n VeryLong goo = null;\n Console.WriteLine(goo);\n return 1;\n }\n }\n}\n\";\n\n var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.DebugExe);\n\n var exebits = new System.IO.MemoryStream();\n var pdbbits = new System.IO.MemoryStream();\n var result = compilation.Emit(exebits, pdbbits, options: TestOptions.NativePdbEmit);\n\n result.Diagnostics.Verify(\n // (12,20): warning CS0811: The fully qualified name for 'AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is too long for debug information. Compile without '/debug' option.\n // static int Main()\n Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, \"Main\").WithArguments(\"AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\").WithLocation(12, 20));\n }\n\n [Fact]\n public void CS1058WRN_UnreachableGeneralCatch()\n {\n var text =\n@\"class C\n{\n static void M()\n {\n try { }\n catch (System.Exception) { }\n catch (System.IO.IOException) { }\n catch { }\n try { }\n catch (System.IO.IOException) { }\n catch (System.Exception) { }\n catch { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"System.IO.IOException\").WithArguments(\"System.Exception\").WithLocation(7, 16),\n Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, \"catch\").WithLocation(8, 9),\n Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, \"catch\").WithLocation(12, 9));\n }\n\n // [Fact(Skip = \"11486\")]\n // public void CS1060WRN_UninitializedField()\n // {\n // var text = @\"\n //namespace CS1060\n //{\n // public class U\n // {\n // public int i;\n // }\n //\n // public struct S\n // {\n // public U u;\n // }\n // public class Test\n // {\n // static void Main()\n // {\n // S s;\n // s.u.i = 5; // CS1060\n // }\n // }\n //}\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_UninitializedField, Line = 18, Column = 13, IsWarning = true } });\n // }\n\n // [Fact()]\n // public void CS1064ERR_DebugFullNameTooLong()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = 1064, Line = 7, Column = 5, IsWarning = true } }\n // );\n // }\n\n [Fact]\n public void CS1570WRN_XMLParseError()\n {\n var text = @\"\nnamespace ns\n{\n // the following line generates CS1570\n /// returns true if < 5 \n // try this instead\n // /// returns true if &lt;5 \n\n public class MyClass\n {\n public static void Main ()\n {\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (5,35): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.'\n // /// returns true if < 5 \n Diagnostic(ErrorCode.WRN_XMLParseError, \"\"),\n // (5,35): warning CS1570: XML comment has badly formed XML -- '5'\n // /// returns true if < 5 \n Diagnostic(ErrorCode.WRN_XMLParseError, \" \").WithArguments(\"5\"),\n // (11,26): warning CS1591: Missing XML comment for publicly visible type or member 'ns.MyClass.Main()'\n // public static void Main ()\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"Main\").WithArguments(\"ns.MyClass.Main()\"));\n }\n\n [Fact]\n public void CS1571WRN_DuplicateParamTag()\n {\n var text = @\"\n/// help text\npublic class MyClass\n{\n /// Used to indicate status.\n /// An initial.\n /// Used to indicate status. // CS1571\n public static void MyMethod(int Int1, char Char1)\n {\n }\n\n /// help text\n public static void Main ()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,15): warning CS1571: XML comment has a duplicate param tag for 'Int1'\n // /// Used to indicate status. // CS1571\n Diagnostic(ErrorCode.WRN_DuplicateParamTag, \"name='Int1'\").WithArguments(\"Int1\"));\n }\n\n [Fact]\n public void CS1572WRN_UnmatchedParamTag()\n {\n var text = @\"\n/// help text\npublic class MyClass\n{\n /// Used to indicate status.\n /// Used to indicate status.\n /// ??? // CS1572\n public static void MyMethod(int Int1, char Char1)\n {\n }\n\n /// help text\n public static void Main ()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,21): warning CS1572: XML comment has a param tag for 'Char2', but there is no parameter by that name\n // /// ??? // CS1572\n Diagnostic(ErrorCode.WRN_UnmatchedParamTag, \"Char2\").WithArguments(\"Char2\"));\n }\n\n [Fact]\n public void CS1573WRN_MissingParamTag()\n {\n var text = @\"\n/// \npublic class MyClass\n{\n /// Used to indicate status.\n /// enter a comment for Char1?\n public static void MyMethod(int Int1, char Char1)\n {\n }\n /// \n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,48): warning CS1573: Parameter 'Char1' has no matching param tag in the XML comment for 'MyClass.MyMethod(int, char)' (but other parameters do)\n // public static void MyMethod(int Int1, char Char1)\n Diagnostic(ErrorCode.WRN_MissingParamTag, \"Char1\").WithArguments(\"Char1\", \"MyClass.MyMethod(int, char)\"));\n }\n\n [Fact]\n public void CS1574WRN_BadXMLRef()\n {\n var text = @\"\n/// \npublic class C\n{\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,16): warning CS1574: XML comment has cref attribute 'D' that could not be resolved\n // /// \n Diagnostic(ErrorCode.WRN_BadXMLRef, \"D\").WithArguments(\"D\"));\n }\n\n [Fact]\n public void CS1580WRN_BadXMLRefParamType()\n {\n var text = @\"\n/// // CS1580\npublic class MyClass\n{\n /// help text\n public static void Main()\n {\n }\n /// help text\n public void Test(int i)\n {\n }\n /// help text\n public void Test(char i)\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,20): warning CS1580: Invalid type for parameter 'i' in XML comment cref attribute: 'Test(i)'\n // /// // CS1580\n Diagnostic(ErrorCode.WRN_BadXMLRefParamType, \"i\").WithArguments(\"i\", \"Test(i)\"),\n // (2,20): warning CS1574: XML comment has cref attribute 'Test(i)' that could not be resolved\n // /// // CS1580\n Diagnostic(ErrorCode.WRN_BadXMLRef, \"Test(i)\").WithArguments(\"Test(i)\"));\n }\n\n [Fact]\n public void CS1581WRN_BadXMLRefReturnType()\n {\n var text = @\"\n/// help text\npublic class MyClass\n{\n /// help text\n public static void Main()\n {\n }\n /// help text\n public static explicit operator int(MyClass f)\n {\n return 0;\n }\n}\n/// // CS1581\npublic class MyClass2\n{\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (15,20): warning CS1581: Invalid return type in XML comment cref attribute\n // /// // CS1581\n Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, \"intt\").WithArguments(\"intt\", \"MyClass.explicit operator intt(MyClass)\"),\n // (15,20): warning CS1574: XML comment has cref attribute 'MyClass.explicit operator intt(MyClass)' that could not be resolved\n // /// // CS1581\n Diagnostic(ErrorCode.WRN_BadXMLRef, \"MyClass.explicit operator intt(MyClass)\").WithArguments(\"explicit operator intt(MyClass)\"));\n }\n\n [Fact]\n public void CS1584WRN_BadXMLRefSyntax()\n {\n var text = @\"\n/// \npublic class MyClass1\n{\n /// \n public static MyClass1 operator /(MyClass1 a1, MyClass1 a2)\n {\n return null;\n }\n /// \n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (10,24): warning CS1584: XML comment has syntactically incorrect cref attribute 'MyClass1.operator@'\n // /// \n Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, \"MyClass1.operator\").WithArguments(\"MyClass1.operator@\"),\n // (10,41): warning CS1658: Overloadable operator expected. See also error CS1037.\n // /// \n Diagnostic(ErrorCode.WRN_ErrorOverride, \"@\").WithArguments(\"Overloadable operator expected\", \"1037\"),\n // (10,41): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @\n // /// \n Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, \"\"));\n }\n\n [Fact]\n public void CS1587WRN_UnprocessedXMLComment()\n {\n var text = @\"\n/// test // CS1587, tag not allowed on namespace\nnamespace MySpace\n{\n class MyClass\n {\n public static void Main()\n {\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, \"/\"));\n }\n\n [Fact]\n public void CS1589WRN_NoResolver()\n {\n var text = @\"\n/// // CS1589\nclass Test\n{\n public static void Main()\n {\n }\n}\n\";\n var c = CreateCompilation(\n new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) },\n options: TestOptions.ReleaseDll.WithXmlReferenceResolver(null));\n\n c.VerifyDiagnostics(\n // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name=\"test\"]/' of file 'CS1589.doc' -- References to XML documents are not supported.\n // /// // CS1589\n Diagnostic(ErrorCode.WRN_FailedInclude, @\"\").\n WithArguments(\"CS1589.doc\", @\"MyDocs/MyMembers[@name=\"\"test\"\"]/\", \"References to XML documents are not supported.\"));\n }\n\n [Fact]\n public void CS1589WRN_FailedInclude()\n {\n var text = @\"\n/// // CS1589\nclass Test\n{\n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name=\"test\"]/' of file 'CS1589.doc' -- Unable to find the specified file.\n // /// // CS1589\n Diagnostic(ErrorCode.WRN_FailedInclude, @\"\").\n WithArguments(\"CS1589.doc\", @\"MyDocs/MyMembers[@name=\"\"test\"\"]/\", \"File not found.\"));\n }\n\n [Fact]\n public void CS1590WRN_InvalidInclude()\n {\n var text = @\"\n/// // CS1590\nclass Test\n{\n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute\n // /// // CS1590\n Diagnostic(ErrorCode.WRN_InvalidInclude, @\"\").WithArguments(\"Missing file attribute\"));\n }\n\n [Fact]\n public void CS1591WRN_MissingXMLComment()\n {\n var text = @\"\n/// text\npublic class Test\n{\n // /// text\n public static void Main() // CS1591\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'Test.Main()'\n // public static void Main() // CS1591\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"Main\").WithArguments(\"Test.Main()\"));\n }\n\n [ConditionalFact(typeof(WindowsDesktopOnly), Reason = \"https://github.com/dotnet/roslyn/issues/18610\")]\n public void CS1592WRN_XMLParseIncludeError()\n {\n var xmlFile = Temp.CreateFile(extension: \".xml\").WriteAllText(\"&\");\n var sourceTemplate = @\"\n/// \npublic class Test {{ }}\n\";\n var comp = CreateCompilationWithMscorlib40AndDocumentationComments(string.Format(sourceTemplate, xmlFile.Path));\n\n using (new EnsureEnglishUICulture())\n {\n comp.VerifyDiagnostics(\n // dcf98d2ac30a.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.'\n Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments(\"Data at the root level is invalid.\"));\n }\n }\n\n [Fact]\n public void CS1658WRN_ErrorOverride()\n {\n var text = @\"\n/// \npublic class Test \n{\n ///\n public static int Main() \n {\n return 0;\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''\n // /// \n Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @\"\"\"\").WithArguments(\"\"),\n // (2,20): warning CS1658: Identifier expected. See also error CS1001.\n // /// \n Diagnostic(ErrorCode.WRN_ErrorOverride, @\"\"\"\").WithArguments(\"Identifier expected\", \"1001\"));\n }\n\n // TODO (tomat): Also fix AttributeTests.DllImport_AttributeRedefinition\n [Fact(Skip = \"530377\"), WorkItem(530377, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530377\"), WorkItem(685159, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685159\")]\n public void CS1685WRN_MultiplePredefTypes()\n {\n var text = @\"\npublic static class C\n{\n public static void Extension(this int X) {}\n}\";\n // include both mscorlib 4.0 and System.Core 3.5, both of which contain ExtensionAttribute\n // These libraries are not yet in our suite\n CreateEmptyCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MultiplePredefTypes, \"\"));\n }\n\n [Fact, WorkItem(530379, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379\")]\n public void CS1690WRN_CallOnNonAgileField()\n {\n var text = @\"\nusing System;\n\nclass WarningCS1690 : MarshalByRefObject\n{\n int i = 5;\n\n public static void Main()\n {\n WarningCS1690 e = new WarningCS1690();\n e.i.ToString(); // CS1690\n int i = e.i;\n i.ToString();\n e.i = i;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_CallOnNonAgileField, Line = 11, Column = 9, IsWarning = true } });\n }\n\n [Fact, WorkItem(530379, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379\")]\n public void CS1690WRN_CallOnNonAgileField_Variations()\n {\n var text = @\"\nusing System;\n\nstruct S\n{\n public event Action Event;\n public int Field;\n public int Property { get; set; }\n public int this[int x] { get { return 0; } set { } }\n public void M() { }\n\n class WarningCS1690 : MarshalByRefObject\n {\n S s;\n\n public static void Main()\n {\n WarningCS1690 w = new WarningCS1690();\n w.s.Event = null;\n w.s.Event += null;\n w.s.Property++;\n w.s[0]++;\n w.s.M();\n Action a = w.s.M;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.Event = null;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (20,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.Event += null;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (21,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.Property++;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (22,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s[0]++;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (23,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.M();\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (24,24): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // Action a = w.s.M;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n\n // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0\n // public int Field;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"Field\").WithArguments(\"S.Field\", \"0\"),\n // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used\n // public event Action Event;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"Event\").WithArguments(\"S.Event\"));\n }\n\n [Fact, WorkItem(530379, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379\")]\n public void CS1690WRN_CallOnNonAgileField_Class()\n {\n var text = @\"\nusing System;\n\nclass S\n{\n public event Action Event;\n public int Field;\n public int Property { get; set; }\n public int this[int x] { get { return 0; } set { } }\n public void M() { }\n\n class WarningCS1690 : MarshalByRefObject\n {\n S s;\n\n public static void Main()\n {\n WarningCS1690 w = new WarningCS1690();\n w.s.Event = null;\n w.s.Event += null;\n w.s.Property++;\n w.s[0]++;\n w.s.M();\n Action a = w.s.M;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,11): warning CS0649: Field 'S.WarningCS1690.s' is never assigned to, and will always have its default value null\n // S s;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"s\").WithArguments(\"S.WarningCS1690.s\", \"null\"),\n // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0\n // public int Field;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"Field\").WithArguments(\"S.Field\", \"0\"),\n // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used\n // public event Action Event;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"Event\").WithArguments(\"S.Event\"));\n }\n\n // [Fact()]\n // public void CS1707WRN_DelegateNewMethBind()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_DelegateNewMethBind, Line = 7, Column = 5, IsWarning = true } }\n // );\n // }\n\n [Fact(), WorkItem(530384, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530384\")]\n public void CS1709WRN_EmptyFileName()\n {\n var text = @\"\nclass Test\n{\n static void Main()\n {\n#pragma checksum \"\"\"\" \"\"{406EA660-64CF-4C82-B6F0-42D48172A799}\"\" \"\"\"\" // CS1709\n }\n}\n\";\n //EDMAURER no longer giving this low-value warning.\n CreateCompilation(text).\n VerifyDiagnostics();\n //VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptyFileName, @\"\"\"\"));\n }\n\n [Fact]\n public void CS1710WRN_DuplicateTypeParamTag()\n {\n var text = @\"\nclass Stack\n{\n}\n/// can be an int\n/// can be an int\nclass MyStackWrapper\n{\n // Open constructed type Stack.\n Stack stack;\n public MyStackWrapper(Stack s)\n {\n stack = s;\n }\n}\nclass CMain\n{\n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (6,16): warning CS1710: XML comment has a duplicate typeparam tag for 'MyType'\n // /// can be an int\n Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @\"name=\"\"MyType\"\"\").WithArguments(\"MyType\"));\n }\n\n [Fact]\n public void CS1711WRN_UnmatchedTypeParamTag()\n {\n var text = @\"\n///can be an int\nclass CMain\n{\n public static void Main() { }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,21): warning CS1711: XML comment has a typeparam tag for 'WrongName', but there is no type parameter by that name\n // ///can be an int\n Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, \"WrongName\").WithArguments(\"WrongName\"));\n }\n\n [Fact]\n public void CS1712WRN_MissingTypeParamTag()\n {\n var text = @\"\n///A generic list delegate.\n///The first type stored by the list.\npublic delegate void List();\n\n///\npublic class Test\n{\n ///\n public static void Main()\n {\n }\n}\t\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (4,29): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'List' (but other type parameters do)\n // public delegate void List();\n Diagnostic(ErrorCode.WRN_MissingTypeParamTag, \"W\").WithArguments(\"W\", \"List\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf()\n {\n var text = @\"\npublic class Test\n{\n public static void Main()\n {\n int x = 0;\n x = x; // CS1717\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_AssignmentToSelf, Line = 7, Column = 7, IsWarning = true } });\n }\n\n [WorkItem(543470, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543470\")]\n [Fact]\n public void CS1717WRN_AssignmentToSelf02()\n {\n var text = @\"\nclass C\n{\n void M(object p)\n {\n object oValue = p;\n if (oValue is int)\n {\n //(SQL 9.0) 653716 + common sense\n oValue = (double) ((int) oValue);\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf03()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n int f;\n event Action e;\n\n void Test(int p)\n {\n int l = 0;\n\n l = l;\n p = p;\n f = f;\n e = e;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // l = l;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"l = l\"),\n // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // p = p;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"p = p\"),\n // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // f = f;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"f = f\"),\n // (16,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // e = e;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"e = e\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf04()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n int f;\n event Action e;\n \n static int sf;\n static event Action se;\n\n void Test(Program other)\n {\n f = this.f;\n e = this.e;\n\n f = other.f; //fine\n e = other.e; //fine\n\n sf = sf;\n se = se;\n\n sf = Program.sf;\n se = Program.se;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // f = this.f;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"f = this.f\"),\n // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // e = this.e;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"e = this.e\"),\n // (20,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // sf = sf;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"sf = sf\"),\n // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // se = se;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"se = se\"),\n // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // sf = Program.sf;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"sf = Program.sf\"),\n // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // se = Program.se;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"se = Program.se\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf05()\n {\n var text = @\"\nusing System.Linq;\n\nclass Program\n{\n static void Main(string[] args)\n {\n var unused = from x in args select x = x;\n }\n}\n\";\n // CONSIDER: dev11 reports WRN_AssignmentToSelf.\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (8,44): error CS1947: Range variable 'x' cannot be assigned to -- it is read only\n // var unused = from x in args select x = x;\n Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, \"x\").WithArguments(\"x\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf06()\n {\n var text = @\"\nclass C\n{\n void M(\n byte b,\n sbyte sb,\n short s,\n ushort us,\n int i,\n uint ui,\n long l,\n ulong ul,\n float f,\n double d,\n decimal m,\n bool bo,\n object o,\n C cl,\n S st)\n {\n b = (byte)b;\n sb = (sbyte)sb;\n s = (short)s;\n us = (ushort)us;\n i = (int)i;\n ui = (uint)ui;\n l = (long)l;\n ul = (ulong)ul;\n f = (float)f; // Not reported by dev11.\n d = (double)d; // Not reported by dev11.\n m = (decimal)m;\n bo = (bool)bo;\n o = (object)o;\n cl = (C)cl;\n st = (S)st;\n }\n}\n\nstruct S\n{\n}\n\";\n // CONSIDER: dev11 does not strip off float or double identity-conversions and, thus,\n // does not warn about those assignments.\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // b = (byte)b;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"b = (byte)b\"),\n // (22,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // sb = (sbyte)sb;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"sb = (sbyte)sb\"),\n // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // s = (short)s;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"s = (short)s\"),\n // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // us = (ushort)us;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"us = (ushort)us\"),\n // (25,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // i = (int)i;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"i = (int)i\"),\n // (26,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // ui = (uint)ui;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"ui = (uint)ui\"),\n // (27,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // l = (long)l;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"l = (long)l\"),\n // (28,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // ul = (ulong)ul;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"ul = (ulong)ul\"),\n // (29,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // f = (float)f; // Not reported by dev11.\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"f = (float)f\"),\n // (30,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // d = (double)d; // Not reported by dev11.\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"d = (double)d\"),\n // (31,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // m = (decimal)m;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"m = (decimal)m\"),\n // (32,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // bo = (bool)bo;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"bo = (bool)bo\"),\n // (33,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // o = (object)o;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"o = (object)o\"),\n // (34,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // cl = (C)cl;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"cl = (C)cl\"),\n // (35,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // st = (S)st;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"st = (S)st\"));\n }\n\n [Fact, WorkItem(546493, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546493\")]\n public void CS1718WRN_ComparisonToSelf()\n {\n var text = @\"\nclass Tester\n{\n static int j = 123;\n static void Main()\n {\n int i = 0;\n if (i == i) i++;\n if (j == Tester.j) j++;\n }\n}\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (8,13): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // if (i == i) i++;\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"i == i\"),\n // (9,13): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // if (j == Tester.j) j++;\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"j == Tester.j\"));\n }\n\n [Fact, WorkItem(580501, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580501\")]\n public void CS1718WRN_ComparisonToSelf2()\n {\n var text = @\"\nusing System.Linq;\nclass Tester\n{\n static void Main()\n {\n var q = from int x1 in new[] { 2, 9, 1, 8, }\n where x1 > x1 // CS1718\n select x1;\n }\n}\n\";\n\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (8,15): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // where x1 > x1 // CS1718\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"x1 > x1\"));\n }\n\n [Fact]\n public void CS1720WRN_DotOnDefault01()\n {\n var source =\n@\"class A\n{\n internal object P { get; set; }\n}\ninterface I\n{\n object P { get; set; }\n}\nstatic class C\n{\n static void M()\n where T2 : new()\n where T3 : struct\n where T4 : class\n where T5 : T1\n where T6 : A\n where T7 : I\n {\n default(int).GetHashCode();\n default(object).GetHashCode();\n default(T1).GetHashCode();\n default(T2).GetHashCode();\n default(T3).GetHashCode();\n default(T4).GetHashCode();\n default(T5).GetHashCode();\n default(T6).GetHashCode();\n default(T7).GetHashCode();\n default(T6).P = null;\n default(T7).P = null;\n default(int).E();\n default(object).E();\n default(T1).E();\n default(T2).E();\n default(T3).E();\n default(T4).E();\n default(T5).E();\n default(T6).E(); // Dev10 (incorrectly) reports CS1720\n default(T7).E();\n }\n static void E(this object o) { }\n}\";\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (20,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object' is null\n // default(object).GetHashCode();\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(object).GetHashCode\").WithArguments(\"object\").WithLocation(20, 9),\n // (24,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null\n // default(T4).GetHashCode();\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T4).GetHashCode\").WithArguments(\"T4\").WithLocation(24, 9),\n // (26,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null\n // default(T6).GetHashCode();\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T6).GetHashCode\").WithArguments(\"T6\").WithLocation(26, 9),\n // (28,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null\n // default(T6).P = null;\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T6).P\").WithArguments(\"T6\").WithLocation(28, 9));\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, options: TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable)).VerifyDiagnostics(\n );\n }\n\n [Fact]\n public void CS1720WRN_DotOnDefault02()\n {\n var source =\n@\"class A\n{\n internal object this[object index] { get { return null; } set { } }\n}\nstruct S\n{\n internal object this[object index] { get { return null; } set { } }\n}\ninterface I\n{\n object this[object index] { get; set; }\n}\nclass C\n{\n unsafe static void M()\n where T1 : A\n where T2 : I\n where T3 : struct, I\n where T4 : class, I\n {\n object o;\n o = default(int*)[0];\n o = default(A)[0];\n o = default(S)[0];\n o = default(I)[0];\n o = default(object[])[0];\n o = default(T1)[0];\n o = default(T2)[0];\n o = default(T3)[0];\n o = default(T4)[0];\n default(int*)[1] = 1;\n default(A)[1] = o;\n default(I)[1] = o;\n default(object[])[1] = o;\n default(T1)[1] = o;\n default(T2)[1] = o;\n default(T3)[1] = o;\n default(T4)[1] = o;\n }\n}\";\n CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (23,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(A)[0]\").WithArguments(\"A\").WithLocation(23, 13),\n // (25,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(I)[0]\").WithArguments(\"I\").WithLocation(25, 13),\n // (26,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(object[])[0]\").WithArguments(\"object[]\").WithLocation(26, 13),\n // (27,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T1)[0]\").WithArguments(\"T1\").WithLocation(27, 13),\n // (30,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T4)[0]\").WithArguments(\"T4\").WithLocation(30, 13),\n // (32,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(A)[1]\").WithArguments(\"A\").WithLocation(32, 9),\n // (33,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(I)[1]\").WithArguments(\"I\").WithLocation(33, 9),\n // (34,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(object[])[1]\").WithArguments(\"object[]\").WithLocation(34, 9),\n // (35,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T1)[1]\").WithArguments(\"T1\").WithLocation(35, 9),\n // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T3)[1]\").WithLocation(37, 9), // Incorrect? See CS0131ERR_AssgLvalueExpected03 unit test.\n // (38,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T4)[1]\").WithArguments(\"T4\").WithLocation(38, 9));\n CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // default(T3)[1] = o;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T3)[1]\").WithLocation(37, 9));\n }\n\n [Fact]\n public void CS1720WRN_DotOnDefault03()\n {\n var source =\n@\"static class A\n{\n static void Main()\n {\n System.Console.WriteLine(default(string).IsNull());\n }\n\n internal static bool IsNull(this string val)\n {\n return (object)val == null; \n }\n}\n\";\n CompileAndVerifyWithMscorlib40(source, expectedOutput: \"True\", references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // Do not report the following warning:\n // (5,34): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null\n // System.Console.WriteLine(default(string).IsNull());\n // Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(string).IsNull\").WithArguments(\"string\").WithLocation(5, 34)\n );\n CompileAndVerifyWithMscorlib40(source, expectedOutput: \"True\", references: new[] { Net40.SystemCore }).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS1723WRN_BadXMLRefTypeVar()\n {\n var text = @\"\n///A generic list class.\n/// // CS1723\npublic class List\n{\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (3,15): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter\n // /// // CS1723\n Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, \"T\").WithArguments(\"T\"));\n }\n\n [Fact]\n public void CS1974WRN_DynamicDispatchToConditionalMethod()\n {\n var text = @\"\nusing System.Diagnostics;\nclass Myclass\n{\n static void Main()\n {\n dynamic d = null;\n // Warning because Goo might be conditional.\n Goo(d); \n // No warning; only the two-parameter Bar is conditional.\n Bar(d);\n }\n\n [Conditional(\"\"DEBUG\"\")]\n static void Goo(string d) {}\n\n [Conditional(\"\"DEBUG\"\")]\n static void Bar(int x, int y) {}\n \n static void Bar(string x) {}\n}\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n// (9,9): warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime because one or more applicable overloads are conditional methods.\n// Goo(d); \nDiagnostic(ErrorCode.WRN_DynamicDispatchToConditionalMethod, \"Goo(d)\").WithArguments(\"Goo\"));\n }\n\n [Fact]\n public void CS1981WRN_IsDynamicIsConfusing()\n {\n var text = @\"\npublic class D : C { }\npublic class C\n{\n public static int Main()\n {\n // is dynamic\n bool bi = 123 is dynamic; \n // dynamicType is valueType\n dynamic i2 = 123;\n bi = i2 is int;\n // dynamicType is refType\n dynamic c = new D();\n bi = c is C;\n dynamic c2 = new C();\n bi = c is C;\n\n // valueType as dynamic\n int i = 123 as dynamic;\n // refType as dynamic\n dynamic c3 = new D() as dynamic;\n // dynamicType as dynamic\n dynamic s = \"\"asd\"\";\n string s2 = s as dynamic;\n // default(dynamic)\n dynamic d = default(dynamic); \n // dynamicType as valueType : generate error\n int k = i2 as int;\n // dynamicType as refType \n C c4 = c3 as C;\n\n return 0;\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (7,19): warning CS1981: Using 'is' to test compatibility with 'dynamic'\n // is essentially identical to testing compatibility with 'Object' and will\n // succeed for all non-null values\n Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, \"123 is dynamic\").WithArguments(\"is\", \"dynamic\", \"Object\"),\n // (7,19): warning CS0183: The given expression is always of the provided ('dynamic') type\n Diagnostic(ErrorCode.WRN_IsAlwaysTrue, \"123 is dynamic\").WithArguments(\"dynamic\"),\n // (27,17): error CS0077: The as operator must be used with a reference type\n // or nullable type ('int' is a non-nullable value type)\n Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, \"i2 as int\").WithArguments(\"int\"),\n // (26,17): warning CS0219: The variable 'd' is assigned but its value is never used\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"d\").WithArguments(\"d\"));\n }\n\n [Fact]\n public void CS7003ERR_UnexpectedUnboundGenericName()\n {\n var text = @\"\nclass C\n{\n void M(System.Type t)\n {\n M(typeof(C>)); //unbound inside bound\n M(typeof(C<>[])); //array of unbound\n M(typeof(C<>.D)); //unbound containing bound\n M(typeof(C.D<>)); //bound containing unbound\n M(typeof(D<,>[])); //multiple type parameters\n }\n\n class D { }\n}\n\nclass D {}\";\n\n // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new.\n CreateCompilation(text).VerifyDiagnostics(\n // (6,20): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"C<>\"),\n // (7,18): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"C<>\"),\n // (8,18): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"C<>\"),\n // (9,25): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"D<>\"),\n // (10,18): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"D<,>\"));\n }\n\n [Fact]\n public void CS7003ERR_UnexpectedUnboundGenericName_Nested()\n {\n var text = @\"\nclass Outer\n{\n public static void Print()\n {\n System.Console.WriteLine(typeof(Inner<>));\n System.Console.WriteLine(typeof(Inner));\n System.Console.WriteLine(typeof(Inner));\n\n System.Console.WriteLine(typeof(Outer<>.Inner<>));\n System.Console.WriteLine(typeof(Outer<>.Inner)); //CS7003\n System.Console.WriteLine(typeof(Outer<>.Inner)); //CS7003\n\n System.Console.WriteLine(typeof(Outer.Inner<>)); //CS7003\n System.Console.WriteLine(typeof(Outer.Inner));\n System.Console.WriteLine(typeof(Outer.Inner));\n\n System.Console.WriteLine(typeof(Outer.Inner<>)); //CS7003\n System.Console.WriteLine(typeof(Outer.Inner));\n System.Console.WriteLine(typeof(Outer.Inner));\n }\n\n class Inner { }\n}\";\n\n // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new.\n CreateCompilation(text).VerifyDiagnostics(\n // (11,41): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Outer<>\"),\n // (12,41): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Outer<>\"),\n // (14,50): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Inner<>\"),\n // (18,52): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Inner<>\"));\n }\n\n [Fact(), WorkItem(529583, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529583\")]\n public void CS7003ERR_UnexpectedUnboundGenericName_Attributes()\n {\n var text = @\"\nusing System;\n\nclass Outer\n{\n public class Inner\n {\n\n }\n}\n\n[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]\nclass Attr : Attribute\n{\n public Attr(Type t)\n {\n }\n}\n\n[Attr(typeof(Outer<>.Inner<>))]\n[Attr(typeof(Outer.Inner<>))]\n[Attr(typeof(Outer<>.Inner))]\n[Attr(typeof(Outer.Inner))]\npublic class Test\n{\n public static void Main()\n {\n }\n}\";\n\n // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new.\n CreateCompilation(text).VerifyDiagnostics(\n // (21,25): error CS7003: Unexpected use of an unbound generic name\n // [Attr(typeof(Outer.Inner<>))]\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Inner<>\"),\n // (22,14): error CS7003: Unexpected use of an unbound generic name\n // [Attr(typeof(Outer<>.Inner))]\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Outer<>\"));\n }\n\n [Fact]\n public void CS7013WRN_MetadataNameTooLong()\n {\n var text = @\"\nnamespace Namespace1.Namespace2\n{\n public interface I\n {\n void Goo();\n }\n\n public class OuterGenericClass\n {\n public class NestedClass : OuterGenericClass { }\n\n public class C : I\n {\n void I.Goo()\n {\n }\n }\n }\n}\n\";\n // This error will necessarily have a very long error string.\n CreateCompilation(text).VerifyEmitDiagnostics(\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, \"Goo\").WithArguments(\"Namespace1.Namespace2.I.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo\"));\n }\n\n #endregion\n\n #region shotgun tests\n\n [Fact]\n public void DelegateCreationBad()\n {\n var text = @\"\nnamespace CSSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n }\n\n delegate void D1();\n delegate void D2();\n\n delegate int D3(int x);\n\n static D1 d1;\n static D2 d2;\n static D3 d3;\n\n internal virtual void V() { }\n void M() { }\n static void S() { }\n\n static int M2(int x) { return x; }\n\n static void F(Program p)\n {\n // Error cases\n d1 = new D1(2 + 2);\n d1 = new D1(d3);\n d1 = new D1(2, 3);\n d1 = new D1(x: 3);\n d1 = new D1(M2);\n }\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (28,25): error CS0149: Method name expected\n // d1 = new D1(2 + 2);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"2 + 2\").WithLocation(28, 25),\n // (29,18): error CS0123: No overload for 'Program.D3.Invoke(int)' matches delegate 'Program.D1'\n // d1 = new D1(d3);\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"new D1(d3)\").WithArguments(\"CSSample.Program.D3.Invoke(int)\", \"CSSample.Program.D1\").WithLocation(29, 18),\n // (30,25): error CS0149: Method name expected\n // d1 = new D1(2, 3);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"2, 3\").WithLocation(30, 25),\n // (31,28): error CS0149: Method name expected\n // d1 = new D1(x: 3);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"3\").WithLocation(31, 28),\n // (32,18): error CS0123: No overload for 'M2' matches delegate 'Program.D1'\n // d1 = new D1(M2);\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"new D1(M2)\").WithArguments(\"M2\", \"CSSample.Program.D1\").WithLocation(32, 18),\n // (16,19): warning CS0169: The field 'Program.d2' is never used\n // static D2 d2;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"d2\").WithArguments(\"CSSample.Program.d2\").WithLocation(16, 19),\n // (17,19): warning CS0649: Field 'Program.d3' is never assigned to, and will always have its default value null\n // static D3 d3;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"d3\").WithArguments(\"CSSample.Program.d3\", \"null\").WithLocation(17, 19));\n }\n\n [Fact, WorkItem(7359, \"https://github.com/dotnet/roslyn/issues/7359\")]\n public void DelegateCreationWithRefOut()\n {\n var source = @\"\nusing System;\npublic class Program\n{\n static Func Goo(Func t) { return t; }\n static Func Bar = Goo(x => x);\n static Func BarP => Goo(x => x);\n static T Id(T id) => id;\n\n static void Test(Func Baz)\n {\n var k = Bar;\n var z1 = new Func(ref Bar); // compat\n var z2 = new Func(ref Baz); // compat\n var z3 = new Func(ref k); // compat\n var z4 = new Func(ref x => x);\n var z5 = new Func(ref Goo(x => x));\n var z6 = new Func(ref BarP); \n var z7 = new Func(ref new Func(x => x));\n var z8 = new Func(ref Program.BarP); \n var z9 = new Func(ref Program.Goo(x => x));\n var z10 = new Func(ref Id); // compat\n var z11 = new Func(ref new(x => x));\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,47): error CS1510: A ref or out argument must be an assignable variable\n // var z4 = new Func(ref x => x);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x\").WithLocation(16, 47),\n // (17,47): error CS1510: A ref or out argument must be an assignable variable\n // var z5 = new Func(ref Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Goo(x => x)\").WithLocation(17, 47),\n // (18,43): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z6 = new Func(ref BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"ref BarP\").WithArguments(\"Program.BarP\").WithLocation(18, 43),\n // (19,47): error CS1510: A ref or out argument must be an assignable variable\n // var z7 = new Func(ref new Func(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new Func(x => x)\").WithLocation(19, 47),\n // (20,43): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z8 = new Func(ref Program.BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"ref Program.BarP\").WithArguments(\"Program.BarP\").WithLocation(20, 43),\n // (21,47): error CS1510: A ref or out argument must be an assignable variable\n // var z9 = new Func(ref Program.Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Program.Goo(x => x)\").WithLocation(21, 47),\n // (23,48): error CS1510: A ref or out value must be an assignable variable\n // var z11 = new Func(ref new(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new(x => x)\").WithLocation(23, 48)\n );\n\n CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (13,47): error CS0149: Method name expected\n // var z1 = new Func(ref Bar); // compat\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(13, 47),\n // (14,47): error CS0149: Method name expected\n // var z2 = new Func(ref Baz); // compat\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(14, 47),\n // (15,47): error CS0149: Method name expected\n // var z3 = new Func(ref k); // compat\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(15, 47),\n // (16,47): error CS1510: A ref or out argument must be an assignable variable\n // var z4 = new Func(ref x => x);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x\").WithLocation(16, 47),\n // (17,47): error CS1510: A ref or out argument must be an assignable variable\n // var z5 = new Func(ref Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Goo(x => x)\").WithLocation(17, 47),\n // (18,47): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z6 = new Func(ref BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"BarP\").WithArguments(\"Program.BarP\").WithLocation(18, 47),\n // (19,47): error CS1510: A ref or out argument must be an assignable variable\n // var z7 = new Func(ref new Func(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new Func(x => x)\").WithLocation(19, 47),\n // (20,47): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z8 = new Func(ref Program.BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"Program.BarP\").WithArguments(\"Program.BarP\").WithLocation(20, 47),\n // (21,47): error CS1510: A ref or out argument must be an assignable variable\n // var z9 = new Func(ref Program.Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Program.Goo(x => x)\").WithLocation(21, 47),\n // (22,48): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z10 = new Func(ref Id); // compat\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(22, 48),\n // (23,48): error CS1510: A ref or out value must be an assignable variable\n // var z11 = new Func(ref new(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new(x => x)\").WithLocation(23, 48)\n );\n }\n\n [Fact, WorkItem(7359, \"https://github.com/dotnet/roslyn/issues/7359\")]\n public void DelegateCreationWithRefOut_Parens()\n {\n // these are allowed in compat mode without the parenthesis\n // with parenthesis, it behaves like strict mode\n var source = @\"\nusing System;\npublic class Program\n{\n static Func Goo(Func t) { return t; }\n static Func Bar = Goo(x => x);\n\n static T Id(T id) => id;\n\n static void Test(Func Baz)\n {\n var k = Bar;\n var z1 = new Func(ref (Bar)); \n var z2 = new Func(ref (Baz)); \n var z3 = new Func(ref (k)); \n var z10 = new Func(ref (Id)); \n // these all are still valid for compat mode, no errors should be reported for compat mode\n var z4 = new Func(ref Bar); \n var z5 = new Func(ref Baz); \n var z6 = new Func(ref k); \n var z7 = new Func(ref Id); \n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,48): error CS0149: Method name expected\n // var z1 = new Func(ref (Bar)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(13, 48),\n // (14,48): error CS0149: Method name expected\n // var z2 = new Func(ref (Baz)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(14, 48),\n // (15,48): error CS0149: Method name expected\n // var z3 = new Func(ref (k)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(15, 48),\n // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z10 = new Func(ref (Id)); \n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(16, 49));\n\n CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (13,48): error CS0149: Method name expected\n // var z1 = new Func(ref (Bar)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(13, 48),\n // (14,48): error CS0149: Method name expected\n // var z2 = new Func(ref (Baz)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(14, 48),\n // (15,48): error CS0149: Method name expected\n // var z3 = new Func(ref (k)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(15, 48),\n // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z10 = new Func(ref (Id)); \n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(16, 49),\n // (18,47): error CS0149: Method name expected\n // var z4 = new Func(ref Bar); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(18, 47),\n // (19,47): error CS0149: Method name expected\n // var z5 = new Func(ref Baz); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(19, 47),\n // (20,47): error CS0149: Method name expected\n // var z6 = new Func(ref k); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(20, 47),\n // (21,47): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z7 = new Func(ref Id); \n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(21, 47));\n }\n\n [Fact, WorkItem(7359, \"https://github.com/dotnet/roslyn/issues/7359\")]\n public void DelegateCreationWithRefOut_MultipleArgs()\n {\n var source = @\"\nusing System;\npublic class Program\n{\n static Func BarP => null;\n static void Test(Func Baz)\n {\n var a = new Func(ref Baz, Baz.Invoke);\n var b = new Func(Baz, ref Baz.Invoke);\n var c = new Func(ref Baz, ref Baz.Invoke);\n var d = new Func(ref BarP, BarP.Invoke);\n var e = new Func(BarP, ref BarP.Invoke);\n var f = new Func(ref BarP, ref BarP.Invoke);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,46): error CS0149: Method name expected\n // var a = new Func(ref Baz, Baz.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz, Baz.Invoke\").WithLocation(8, 46),\n // (9,42): error CS0149: Method name expected\n // var b = new Func(Baz, ref Baz.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz, ref Baz.Invoke\").WithLocation(9, 42),\n // (10,46): error CS0149: Method name expected\n // var c = new Func(ref Baz, ref Baz.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz, ref Baz.Invoke\").WithLocation(10, 46),\n // (11,42): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var d = new Func(ref BarP, BarP.Invoke);\n Diagnostic(ErrorCode.ERR_RefProperty, \"ref BarP\").WithArguments(\"Program.BarP\").WithLocation(11, 42),\n // (11,46): error CS0149: Method name expected\n // var d = new Func(ref BarP, BarP.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"BarP, BarP.Invoke\").WithLocation(11, 46),\n // (12,42): error CS0149: Method name expected\n // var e = new Func(BarP, ref BarP.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"BarP, ref BarP.Invoke\").WithLocation(12, 42),\n // (13,42): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var f = new Func(ref BarP, ref BarP.Invoke);\n Diagnostic(ErrorCode.ERR_RefProperty, \"ref BarP\").WithArguments(\"Program.BarP\").WithLocation(13, 42),\n // (13,46): error CS0149: Method name expected\n // var f = new Func(ref BarP, ref BarP.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"BarP, ref BarP.Invoke\").WithLocation(13, 46)\n );\n }\n\n [WorkItem(538430, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538430\")]\n [Fact]\n public void NestedGenericAccessibility()\n {\n var text = @\"\npublic class C\n{\n}\npublic class E\n{\n class D : C\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n });\n }\n\n [WorkItem(542419, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419\")]\n [Fact]\n public void EmptyAngleBrackets()\n {\n var text = @\"\nclass Program\n{\n int f;\n int P { get; set; }\n int M() { return 0; }\n interface I { }\n class C { }\n struct S { }\n delegate void D();\n\n void Test(object p)\n {\n int l = 0;\n\n Test(l<>);\n Test(p<>);\n\n Test(f<>);\n Test(P<>);\n Test(M<>());\n\n Test(this.f<>);\n Test(this.P<>);\n Test(this.M<>());\n\n System.Func m;\n \n m = M<>;\n m = this.M<>;\n\n I<> i1 = null;\n C<> c1 = new C();\n C c2 = new C<>();\n S<> s1 = new S();\n S s2 = new S<>();\n D<> d1 = null;\n\n Program.I<> i2 = null;\n Program.C<> c3 = new Program.C();\n Program.C c4 = new Program.C<>();\n Program.S<> s3 = new Program.S();\n Program.S s4 = new Program.S<>();\n Program.D<> d2 = null;\n\n Test(default(I<>));\n Test(default(C<>));\n Test(default(S<>));\n\n Test(default(Program.I<>));\n Test(default(Program.C<>));\n Test(default(Program.S<>));\n\n string s;\n\n s = typeof(I<>).Name;\n s = typeof(C<>).Name;\n s = typeof(S<>).Name;\n \n s = typeof(Program.I<>).Name;\n s = typeof(Program.C<>).Name;\n s = typeof(Program.S<>).Name;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,14): error CS0307: The variable 'l' cannot be used with type arguments\n // Test(l<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"l<>\").WithArguments(\"l\", \"variable\").WithLocation(16, 14),\n // (17,14): error CS0307: The variable 'object' cannot be used with type arguments\n // Test(p<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"p<>\").WithArguments(\"object\", \"variable\").WithLocation(17, 14),\n // (19,14): error CS0307: The field 'Program.f' cannot be used with type arguments\n // Test(f<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"f<>\").WithArguments(\"Program.f\", \"field\").WithLocation(19, 14),\n // (20,14): error CS0307: The property 'Program.P' cannot be used with type arguments\n // Test(P<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"P<>\").WithArguments(\"Program.P\", \"property\").WithLocation(20, 14),\n // (21,14): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // Test(M<>());\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(21, 14),\n // (23,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.f<>);\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.f<>\").WithLocation(23, 14),\n // (23,19): error CS0307: The field 'Program.f' cannot be used with type arguments\n // Test(this.f<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"f<>\").WithArguments(\"Program.f\", \"field\").WithLocation(23, 19),\n // (24,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.P<>);\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.P<>\").WithLocation(24, 14),\n // (24,19): error CS0307: The property 'Program.P' cannot be used with type arguments\n // Test(this.P<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"P<>\").WithArguments(\"Program.P\", \"property\").WithLocation(24, 19),\n // (25,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.M<>());\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.M<>\").WithLocation(25, 14),\n // (25,19): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // Test(this.M<>());\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(25, 19),\n // (29,13): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // m = M<>;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(29, 13),\n // (30,13): error CS8389: Omitting the type argument is not allowed in the current context\n // m = this.M<>;\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.M<>\").WithLocation(30, 13),\n // (30,18): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // m = this.M<>;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(30, 18),\n // (32,9): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // I<> i1 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(32, 9),\n // (33,9): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // C<> c1 = new C();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(33, 9),\n // (34,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // C c2 = new C<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(34, 20),\n // (35,9): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // S<> s1 = new S();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(35, 9),\n // (36,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // S s2 = new S<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(36, 20),\n // (37,9): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments\n // D<> d1 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"D<>\").WithArguments(\"Program.D\", \"type\").WithLocation(37, 9),\n // (39,17): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // Program.I<> i2 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(39, 17),\n // (40,17): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Program.C<> c3 = new Program.C();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(40, 17),\n // (41,36): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Program.C c4 = new Program.C<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(41, 36),\n // (42,17): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Program.S<> s3 = new Program.S();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(42, 17),\n // (43,36): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Program.S s4 = new Program.S<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(43, 36),\n // (44,17): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments\n // Program.D<> d2 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"D<>\").WithArguments(\"Program.D\", \"type\").WithLocation(44, 17),\n // (46,22): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // Test(default(I<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(46, 22),\n // (47,22): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Test(default(C<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(47, 22),\n // (48,22): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Test(default(S<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(48, 22),\n // (50,30): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // Test(default(Program.I<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(50, 30),\n // (51,30): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Test(default(Program.C<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(51, 30),\n // (52,30): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Test(default(Program.S<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(52, 30),\n // (56,20): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // s = typeof(I<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(56, 20),\n // (57,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // s = typeof(C<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(57, 20),\n // (58,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // s = typeof(S<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(58, 20),\n // (60,28): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // s = typeof(Program.I<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(60, 28),\n // (61,28): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // s = typeof(Program.C<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(61, 28),\n // (62,28): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // s = typeof(Program.S<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(62, 28),\n // (4,9): warning CS0649: Field 'Program.f' is never assigned to, and will always have its default value 0\n // int f;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"f\").WithArguments(\"Program.f\", \"0\").WithLocation(4, 9)\n );\n }\n\n [WorkItem(542419, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419\")]\n [Fact]\n public void EmptyAngleBrackets_Events()\n {\n var text = @\"\nclass Program\n{\n event System.Action E;\n event System.Action F { add { } remove { } }\n\n void Test(T p)\n {\n Test(E<>);\n Test(this.E<>);\n\n E<> += null; //parse error\n F<> += null; //parse error\n\n this.E<> += null; //parse error\n this.F<> += null; //parse error\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // Parser\n\n // (12,11): error CS1525: Invalid expression term '>'\n // E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(12, 11),\n // (12,13): error CS1525: Invalid expression term '+='\n // E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(12, 13),\n // (13,11): error CS1525: Invalid expression term '>'\n // F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(13, 11),\n // (13,13): error CS1525: Invalid expression term '+='\n // F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(13, 13),\n // (15,16): error CS1525: Invalid expression term '>'\n // this.E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(15, 16),\n // (15,18): error CS1525: Invalid expression term '+='\n // this.E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(15, 18),\n // (16,16): error CS1525: Invalid expression term '>'\n // this.F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(16, 16),\n // (16,18): error CS1525: Invalid expression term '+='\n // this.F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(16, 18),\n\n // Binder\n\n // (9,14): error CS0307: The event 'Program.E' cannot be used with type arguments\n // Test(E<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"E<>\").WithArguments(\"Program.E\", \"event\").WithLocation(9, 14),\n // (10,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.E<>);\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.E<>\").WithLocation(10, 14),\n // (10,19): error CS0307: The event 'Program.E' cannot be used with type arguments\n // Test(this.E<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"E<>\").WithArguments(\"Program.E\", \"event\").WithLocation(10, 19),\n // (13,9): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -=\n // F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_BadEventUsageNoField, \"F\").WithArguments(\"Program.F\").WithLocation(13, 9),\n // (16,14): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -=\n // this.F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_BadEventUsageNoField, \"F\").WithArguments(\"Program.F\").WithLocation(16, 14));\n }\n\n [WorkItem(542419, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419\")]\n [WorkItem(542679, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542679\")]\n [Fact]\n public void EmptyAngleBrackets_TypeParameters()\n {\n var text = @\"\nclass Program\n{\n void Test(T p)\n {\n Test(default(T<>));\n string s = typeof(T<>).Name;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6, 24): error CS0307: The type parameter 'T' cannot be used with type arguments\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"T<>\").WithArguments(\"T\", \"type parameter\"),\n // (7,27): error CS0307: The type parameter 'T' cannot be used with type arguments\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"T<>\").WithArguments(\"T\", \"type parameter\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_TypeWithCorrectArity()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n C<>.M();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0305: Using the generic type 'C' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"C<>\").WithArguments(\"C\", \"type\", \"1\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_MethodWithCorrectArity()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n M<>();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"M<>\").WithArguments(\"M\", \"method group\", \"1\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_QualifiedTypeWithCorrectArity()\n {\n var text = @\"\nclass A\n{\n class C\n {\n static void M()\n {\n A.C<>.M();\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,15): error CS0305: Using the generic type 'A.C' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"C<>\").WithArguments(\"A.C\", \"type\", \"1\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_QualifiedMethodWithCorrectArity()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n C.M<>();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"C.M<>\").WithArguments(\"M\", \"method group\", \"1\"));\n }\n\n [Fact]\n public void NamesTooLong()\n {\n var longE = new String('e', 1024);\n\n var builder = new System.Text.StringBuilder();\n\n builder.Append(@\"\nclass C\n{\n\");\n builder.AppendFormat(\"int {0}1;\\n\", longE);\n builder.AppendFormat(\"event System.Action {0}2;\\n\", longE);\n builder.AppendFormat(\"public void {0}3() {{ }}\\n\", longE);\n builder.AppendFormat(\"public void goo(int {0}4) {{ }}\\n\", longE);\n builder.AppendFormat(\"public string {0}5 {{ get; set; }}\\n\", longE);\n\n builder.AppendLine(@\"\n}\n\");\n CreateCompilation(builder.ToString(), null, TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)).VerifyEmitDiagnostics(\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //event\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //backing field\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(\"add_\" + longE + 2), //accessor\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(\"remove_\" + longE + 2), //accessor\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 3).WithArguments(longE + 3),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 4).WithArguments(longE + 4),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(longE + 5),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(\"<\" + longE + 5 + \">k__BackingField\"),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, \"get\").WithArguments(\"get_\" + longE + 5),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, \"set\").WithArguments(\"set_\" + longE + 5),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 1).WithArguments(longE + 1)\n );\n }\n #endregion\n\n #region regression tests\n\n [WorkItem(541605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541605\")]\n [Fact]\n public void CS0019ERR_ImplicitlyTypedVariableAssignedNullCoalesceExpr()\n {\n CreateCompilation(@\"\nclass Test\n{\n public static void Main()\n {\n var p = null ?? null; //CS0019\n }\n}\n\").VerifyDiagnostics(\n // error CS0019: Operator '??' cannot be applied to operands of type '' and ''\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null ?? null\").WithArguments(\"??\", \"\", \"\"));\n }\n\n [WorkItem(528577, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528577\")]\n [Fact(Skip = \"528577\")]\n public void CS0122ERR_InaccessibleGenericType()\n {\n CreateCompilation(@\"\npublic class Top\n{\n class Outer\n {\n }\n}\n\npublic class MyClass\n{\n public static void Main()\n {\n var test = new Top.Outer();\n }\n}\n\").VerifyDiagnostics(\n // (13,33): error CS0122: 'Top.Outer' is inaccessible due to its protection level\n // var test = new Top.Outer();\n Diagnostic(ErrorCode.ERR_BadAccess, \"new Top.Outer()\").WithArguments(\"Top.Outer\"));\n }\n\n [WorkItem(528591, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528591\")]\n [Fact]\n public void CS0121ERR_IncorrectErrorSpan1()\n {\n CreateCompilation(@\"\nclass Test\n{\n public static void Method1(int a, long b)\n {\n }\n\n public static void Method1(long a, int b)\n {\n }\n\n public static void Main()\n {\n Method1(10, 20); //CS0121\n }\n}\n\").VerifyDiagnostics(\n // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Method1(int, long)' and 'Test.Method1(long, int)'\n // Method1(10, 20)\n Diagnostic(ErrorCode.ERR_AmbigCall, \"Method1\").WithArguments(\"Test.Method1(int, long)\", \"Test.Method1(long, int)\"));\n }\n\n [WorkItem(528592, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528592\")]\n [Fact]\n public void CS0121ERR_IncorrectErrorSpan2()\n {\n CreateCompilation(@\"\npublic class Class1\n{\n public Class1(int a, long b)\n {\n }\n\n public Class1(long a, int b)\n {\n }\n}\n\nclass Test\n{\n public static void Main()\n {\n var i1 = new Class1(10, 20); //CS0121\n }\n}\n\").VerifyDiagnostics(\n // (17,18): error CS0121: The call is ambiguous between the following methods or properties: 'Class1.Class1(int, long)' and 'Class1.Class1(long, int)'\n // new Class1(10, 20)\n Diagnostic(ErrorCode.ERR_AmbigCall, \"Class1\").WithArguments(\"Class1.Class1(int, long)\", \"Class1.Class1(long, int)\"));\n }\n\n [WorkItem(542468, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542468\")]\n [Fact]\n public void CS1513ERR_RbraceExpected_DevDiv9741()\n {\n var text = @\"\nclass Program\n{\n private delegate string D();\n static void Main(string[] args)\n {\n D d = delegate\n {\n .ToString();\n };\n }\n} \n\";\n // Used to assert.\n CreateCompilation(text).VerifyDiagnostics(\n // (8,10): error CS1513: } expected\n // {\n Diagnostic(ErrorCode.ERR_RbraceExpected, \"\").WithLocation(8, 10),\n // (9,14): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()'\n // .ToString();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"ToString\").WithArguments(\"object.ToString()\").WithLocation(9, 14),\n // (7,15): error CS1643: Not all code paths return a value in anonymous method of type 'Program.D'\n // D d = delegate\n Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, \"delegate\").WithArguments(\"anonymous method\", \"Program.D\").WithLocation(7, 15)\n );\n }\n\n [WorkItem(543473, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543473\")]\n [Fact]\n public void CS0815ERR_CannotAssignLambdaExpressionToAnImplicitlyTypedLocalVariable()\n {\n var text =\n@\"class Program\n{\n static void Main(string[] args)\n {\n var a1 = checked((a) => a);\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (5,26): error CS8917: The delegate type could not be inferred.\n // var a1 = checked((a) => a);\n Diagnostic(ErrorCode.ERR_CannotInferDelegateType, \"(a) => a\").WithLocation(5, 26));\n }\n\n [Fact, WorkItem(543665, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543665\")]\n public void CS0246ERR_SingleTypeNameNotFound_UndefinedTypeInDelegateSignature()\n {\n var text = @\"\nusing System;\nclass Test\n{\n static void Main()\n {\n var d = (Action>)delegate(List t) {};\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,41): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?)\n // var d = (Action>)delegate(List t) {};\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"List\").WithArguments(\"List<>\").WithLocation(7, 41),\n // (7,21): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?)\n // var d = (Action>)delegate(List t) {};\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"List\").WithArguments(\"List<>\").WithLocation(7, 21)\n );\n }\n\n [Fact]\n [WorkItem(633183, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183\")]\n public void CS0199ERR_RefReadonlyStatic_StaticFieldInitializer()\n {\n var source = @\"\nclass Program\n{\n Program(ref string s) { }\n static readonly Program Field1 = new Program(ref Program.Field2);\n static readonly string Field2 = \"\"\"\";\n static void Main() { }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact]\n [WorkItem(633183, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183\")]\n public void CS0199ERR_RefReadonlyStatic_NestedStaticFieldInitializer()\n {\n var source = @\"\nclass Program\n{\n Program(ref string s) { }\n static readonly Program Field1 = new Program(ref Program.Field2);\n static readonly string Field2 = \"\"\"\";\n static void Main() { }\n\n class Inner\n {\n static readonly Program Field3 = new Program(ref Program.Field2);\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (11,58): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor)\n // static readonly Program Field3 = new Program(ref Program.Field2);\n Diagnostic(ErrorCode.ERR_RefReadonlyStatic, \"Program.Field2\").WithLocation(11, 58)\n);\n }\n\n [Fact]\n public void BadYield_MultipleReasons()\n {\n var source = @\"\nusing System.Collections.Generic;\n\nclass Program\n{\n IEnumerable Test()\n {\n try\n {\n try\n {\n yield return 11; // CS1626\n }\n catch\n {\n yield return 12; // CS1626\n }\n finally\n {\n yield return 13; // CS1625\n }\n }\n catch\n {\n try\n {\n yield return 21; // CS1626\n }\n catch\n {\n yield return 22; // CS1631\n }\n finally\n {\n yield return 23; // CS1625\n }\n }\n finally\n {\n try\n {\n yield return 31; // CS1625\n }\n catch\n {\n yield return 32; // CS1625\n }\n finally\n {\n yield return 33; // CS1625\n }\n }\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (12,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return 11; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\"),\n // (16,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return 12; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\"),\n // (20,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 13; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n\n // (27,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return 21; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\"),\n // (31,17): error CS1631: Cannot yield a value in the body of a catch clause\n // yield return 22; // CS1631\n Diagnostic(ErrorCode.ERR_BadYieldInCatch, \"yield\"),\n // (35,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 23; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n\n // (42,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 31; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n // (46,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 32; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n // (50,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 33; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"));\n }\n\n [Fact]\n public void BadYield_Lambda()\n {\n var source = @\"\nusing System;\nusing System.Collections.Generic;\n\nclass Program\n{\n IEnumerable Test()\n {\n try\n {\n }\n finally\n {\n Action a = () => { yield break; };\n Action b = () =>\n {\n try\n {\n }\n finally\n {\n yield break;\n }\n };\n }\n\n yield break;\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (14,32): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression\n // Action a = () => { yield break; };\n Diagnostic(ErrorCode.ERR_YieldInAnonMeth, \"yield\"),\n\n // CONSIDER: ERR_BadYieldInFinally is redundant, but matches dev11.\n\n // (22,21): error CS1625: Cannot yield in the body of a finally clause\n // yield break;\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n // (22,21): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression\n // yield break;\n Diagnostic(ErrorCode.ERR_YieldInAnonMeth, \"yield\"));\n }\n\n #endregion\n\n [Fact]\n public void Bug528147()\n {\n var text = @\"\nusing System;\n \ninterface I { }\n \nclass A\n{\n private class B { }\n public class C : I\n {\n }\n}\n \nclass Program\n{\n delegate void D(A.C x);\n \n static void M(I c)\n {\n Console.WriteLine(\"\"I\"\");\n }\n\n static void Main()\n {\n D d = M;\n d(null);\n }\n}\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n// (25,15): error CS0122: 'Program.M(I)' is inaccessible due to its protection level\n// D d = M;\nDiagnostic(ErrorCode.ERR_BadAccess, \"M\").WithArguments(\"Program.M(I)\")\n );\n }\n\n [WorkItem(630799, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630799\")]\n [Fact]\n public void Bug630799()\n {\n var text = @\"\nusing System;\n \nclass Program\n{\n static void Goo() where T : S where S : Exception\n {\n try\n {\n }\n catch(S e)\n {\n }\n catch(T e)\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,15): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('S')\n // catch(T e)\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"T\").WithArguments(\"S\").WithLocation(14, 15),\n // (11,17): warning CS0168: The variable 'e' is declared but never used\n // catch(S e)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(11, 17),\n // (14,17): warning CS0168: The variable 'e' is declared but never used\n // catch(T e)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(14, 17)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccess001()\n {\n var text = @\"\nclass Program\n{\n public int P1\n {\n set { }\n }\n\n public void V() { }\n\n static void Main(string[] args)\n {\n var x = 123 ?.ToString();\n\n var p = new Program();\n var x1 = p.P1 ?.ToString();\n var x2 = p.V() ?.ToString();\n var x3 = p.V ?.ToString();\n var x4 = ()=> { return 1; } ?.ToString();\n }\n}\n\";\n CreateCompilationWithMscorlib45(text).VerifyDiagnostics(\n // (13,21): error CS0023: Operator '?' cannot be applied to operand of type 'int'\n // var x = 123 ?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"int\").WithLocation(13, 21),\n // (16,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor\n // var x1 = p.P1 ?.ToString();\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"p.P1\").WithArguments(\"Program.P1\").WithLocation(16, 18),\n // (17,24): error CS0023: Operator '?' cannot be applied to operand of type 'void'\n // var x2 = p.V() ?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"void\").WithLocation(17, 24),\n // (18,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context\n // var x3 = p.V ?.ToString();\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"V\").WithArguments(\"Program.V()\", \"method\").WithLocation(18, 20),\n // (19,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression'\n // var x4 = ()=> { return 1; } ?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"()=> { return 1; } ?.ToString()\").WithArguments(\"?\", \"lambda expression\").WithLocation(19, 18)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccess002_notIn5()\n {\n var text = @\"\nclass Program\n{\n public int? P1\n {\n get { return null; }\n } \n\n public void V() { }\n\n static void Main(string[] args)\n {\n var p = new Program();\n var x1 = p.P1 ?.ToString;\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics(\n // (14,18): error CS8026: Feature 'null propagation operator' is not available in C# 5. Please use language version 6 or greater.\n // var x1 = p.P1 ?.ToString;\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, \"p.P1 ?.ToString\").WithArguments(\"null propagating operator\", \"6\").WithLocation(14, 18),\n // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group'\n // var x1 = p.P1 ?.ToString;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"method group\").WithLocation(14, 23)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccess002()\n {\n var text = @\"\nclass Program\n{\n public int? P1\n {\n get { return null; }\n } \n\n public void V() { }\n\n static void Main(string[] args)\n {\n var p = new Program();\n var x1 = p.P1 ?.ToString;\n }\n}\n\";\n CreateCompilationWithMscorlib45(text).VerifyDiagnostics(\n // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group'\n // var x1 = p.P1 ?.ToString;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"method group\").WithLocation(14, 23)\n );\n }\n\n\n [Fact]\n [CompilerTrait(CompilerFeature.IOperation)]\n [WorkItem(23009, \"https://github.com/dotnet/roslyn/issues/23009\")]\n public void ConditionalElementAccess001()\n {\n var text = @\"\nclass Program\n{\n public int P1\n {\n set { }\n }\n\n public void V() \n { \n var x6 = base?.ToString();\n }\n\n static void Main(string[] args)\n {\n var x = 123 ?[1,2];\n\n var p = new Program();\n var x1 = p.P1 ?[1,2];\n var x2 = p.V() ?[1,2];\n var x3 = p.V ?[1,2];\n var x4 = ()=> { return 1; } ?[1,2];\n\n var x5 = null?.ToString();\n }\n}\n\";\n var compilation = CreateCompilationWithMscorlib45(text).VerifyDiagnostics(\n // (11,18): error CS0175: Use of keyword 'base' is not valid in this context\n // var x6 = base?.ToString();\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\").WithLocation(11, 18),\n // (16,21): error CS0023: Operator '?' cannot be applied to operand of type 'int'\n // var x = 123 ?[1,2];\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"int\").WithLocation(16, 21),\n // (19,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor\n // var x1 = p.P1 ?[1,2];\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"p.P1\").WithArguments(\"Program.P1\").WithLocation(19, 18),\n // (20,24): error CS0023: Operator '?' cannot be applied to operand of type 'void'\n // var x2 = p.V() ?[1,2];\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"void\").WithLocation(20, 24),\n // (21,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context\n // var x3 = p.V ?[1,2];\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"V\").WithArguments(\"Program.V()\", \"method\").WithLocation(21, 20),\n // (22,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression'\n // var x4 = ()=> { return 1; } ?[1,2];\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"()=> { return 1; } ?[1,2]\").WithArguments(\"?\", \"lambda expression\").WithLocation(22, 18),\n // (24,22): error CS0023: Operator '?' cannot be applied to operand of type ''\n // var x5 = null?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"\").WithLocation(24, 22)\n );\n var tree = compilation.SyntaxTrees.Single();\n var node = tree.GetRoot().DescendantNodes().OfType().First();\n\n Assert.Equal(\"base?.ToString()\", node.ToString());\n\n compilation.VerifyOperationTree(node, expectedOperationTree:\n@\"\nIConditionalAccessOperation (OperationKind.ConditionalAccess, Type: ?, IsInvalid) (Syntax: 'base?.ToString()')\n Operation: \n IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base')\n WhenNotNull: \n IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')\n Instance Receiver: \n IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base')\n Arguments(0)\n\");\n }\n\n [Fact]\n [WorkItem(976765, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765\")]\n public void ConditionalMemberAccessPtr()\n {\n var text = @\"\nusing System;\n \nclass Program\n{\n unsafe static void Main()\n {\n IntPtr? intPtr = null;\n var p = intPtr?.ToPointer();\n }\n}\n\n\";\n CreateCompilationWithMscorlib45(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,23): error CS0023: Operator '?' cannot be applied to operand of type 'void*'\n // var p = intPtr?.ToPointer();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"void*\").WithLocation(9, 23)\n );\n }\n\n [Fact]\n [WorkItem(991490, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991490\")]\n public void ConditionalMemberAccessExprLambda()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nclass Program\n{\n static void M(T x)\n {\n Expression> s = () => x?.ToString();\n Expression> c = () => x.ToString()?[0];\n Expression> c1 = () => x.ToString()?.Length;\n\n Expression> c2 = () => x?.ToString()?.Length;\n}\n\n static void Main()\n {\n M((string)null);\n }\n}\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (9,44): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> s = () => x?.ToString();\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x?.ToString()\").WithLocation(9, 44),\n // (10,43): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c = () => x.ToString()?[0];\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x.ToString()?[0]\").WithLocation(10, 43),\n // (11,43): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c1 = () => x.ToString()?.Length;\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x.ToString()?.Length\").WithLocation(11, 43),\n // (13,43): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c2 = () => x?.ToString()?.Length;\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x?.ToString()?.Length\").WithLocation(13, 43),\n // (13,45): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c2 = () => x?.ToString()?.Length;\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \".ToString()?.Length\").WithLocation(13, 45)\n );\n }\n\n [Fact]\n [WorkItem(915609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609\")]\n public void DictionaryInitializerInExprLambda()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void M(T x)\n {\n Expression>> s = () => new Dictionary () {[1] = 2};\n}\n\n static void Main()\n {\n M((string)null);\n }\n}\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics(\n // (10,87): error CS8073: An expression tree lambda may not contain a dictionary initializer.\n // Expression>> s = () => new Dictionary () {[1] = 2};\n Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, \"[1]\").WithLocation(10, 87)\n );\n }\n\n [Fact]\n [WorkItem(915609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609\")]\n public void DictionaryInitializerInExprLambda1()\n {\n var text = @\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n\nnamespace ConsoleApplication31\n{\n class Program\n {\n static void Main(string[] args)\n {\n var o = new Goo();\n var x = o.E.Compile()().Pop();\n System.Console.WriteLine(x);\n }\n }\n\n static class StackExtensions\n {\n public static void Add(this Stack s, T x) => s.Push(x);\n }\n\n class Goo\n {\n public Expression>> E = () => new Stack { 42 };\n }\n}\n\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics(\n // (25,72): error CS8075: An expression tree lambda may not contain an extension collection element initializer.\n // public Expression>> E = () => new Stack { 42 };\n Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, \"42\").WithLocation(25, 72)\n );\n }\n\n [WorkItem(310, \"https://github.com/dotnet/roslyn/issues/310\")]\n [Fact]\n public void ExtensionElementInitializerInExpressionLambda()\n {\n var text = @\"\nusing System;\nusing System.Collections;\nusing System.Linq.Expressions;\nclass C\n{\n static void Main()\n {\n Expression> e = () => new C { H = { [\"\"Key\"\"] = \"\"Value\"\" } };\n Console.WriteLine(e);\n var c = e.Compile().Invoke();\n Console.WriteLine(c.H[\"\"Key\"\"]);\n }\n readonly Hashtable H = new Hashtable();\n}\n\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics(\n // (9,53): error CS8073: An expression tree lambda may not contain a dictionary initializer.\n // Expression> e = () => new C { H = { [\"Key\"] = \"Value\" } };\n Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, @\"[\"\"Key\"\"]\").WithLocation(9, 53)\n );\n }\n\n [WorkItem(12900, \"https://github.com/dotnet/roslyn/issues/12900\")]\n [WorkItem(17138, \"https://github.com/dotnet/roslyn/issues/17138\")]\n [Fact]\n public void CSharp7FeaturesInExprTrees()\n {\n var source = @\"\nusing System;\n//using System.Collections;\nusing System.Linq.Expressions;\nclass C\n{\n static void Main()\n {\n // out variable declarations\n Expression> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1\n\n // pattern matching\n object o = 3;\n Expression> e2 = () => o is int y && y == 3; // ERROR 2\n\n // direct tuple creation could be OK, as it is just a constructor invocation,\n // not for long tuples the generated code is more complex, and we would\n // prefer custom expression trees to express the semantics.\n Expression> e3 = () => (1, o); // ERROR 3: tuple literal\n Expression> e4 = () => (1, 2); // ERROR 4: tuple literal\n\n // tuple conversions\n (byte, byte) t1 = (1, 2);\n Expression> e5 = () => t1; // OK, identity conversion\n Expression> e6 = () => t1; // ERROR 5: tuple conversion\n\n Expression> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method\n\n // discard\n Expression> e8 = () => TryGetThree(out int _);\n Expression> e9 = () => TryGetThree(out var _);\n Expression> e10 = () => _ = (bool)o;\n Expression> e11 = () => _ = (_, _) = GetTuple();\n Expression> e12 = () => _ = var (a, _) = GetTuple();\n Expression> e13 = () => _ = (var a, var _) = GetTuple();\n Expression> e14 = () => TryGetThree(out _);\n }\n\n static bool TryGetThree(out int three)\n {\n three = 3;\n return true;\n }\n\n static int three = 3;\n static ref int GetRefThree()\n {\n return ref three;\n }\n static int TakeRef(ref int x)\n {\n Console.WriteLine(\"\"wow\"\");\n return x;\n }\n static (object, object) GetTuple()\n {\n return (null, null);\n }\n}\nnamespace System\n{\n struct ValueTuple\n {\n public T1 Item1;\n public T2 Item2;\n public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; }\n }\n}\n\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Indicates that the use of on a member is meant to be treated as a tuple with element names.\n /// \n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )]\n public sealed class TupleElementNamesAttribute : Attribute\n {\n public TupleElementNamesAttribute(string[] transformNames) { }\n }\n}\n\";\n var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe);\n compilation.VerifyDiagnostics(\n // (34,50): error CS8185: A declaration is not allowed in this context.\n // Expression> e12 = () => _ = var (a, _) = GetTuple();\n Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, \"var (a, _)\").WithLocation(34, 50),\n // (35,51): error CS8185: A declaration is not allowed in this context.\n // Expression> e13 = () => _ = (var a, var _) = GetTuple();\n Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, \"var a\").WithLocation(35, 51),\n // (10,59): error CS8198: An expression tree may not contain an out argument variable declaration.\n // Expression> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, \"int x\").WithLocation(10, 59),\n // (14,43): error CS8122: An expression tree may not contain an 'is' pattern-matching operator.\n // Expression> e2 = () => o is int y && y == 3; // ERROR 2\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, \"o is int y\").WithLocation(14, 43),\n // (19,45): error CS8143: An expression tree may not contain a tuple literal.\n // Expression> e3 = () => (1, o); // ERROR 3: tuple literal\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, \"(1, o)\").WithLocation(19, 45),\n // (20,49): error CS8143: An expression tree may not contain a tuple literal.\n // Expression> e4 = () => (1, 2); // ERROR 4: tuple literal\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, \"(1, 2)\").WithLocation(20, 49),\n // (25,49): error CS8144: An expression tree may not contain a tuple conversion.\n // Expression> e6 = () => t1; // ERROR 5: tuple conversion\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, \"t1\").WithLocation(25, 49),\n // (27,54): error CS8156: An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference\n // Expression> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method\n Diagnostic(ErrorCode.ERR_RefReturningCallInExpressionTree, \"GetRefThree()\").WithLocation(27, 54),\n // (30,59): error CS8205: An expression tree may not contain a discard.\n // Expression> e8 = () => TryGetThree(out int _);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, \"int _\").WithLocation(30, 59),\n // (31,59): error CS8205: An expression tree may not contain a discard.\n // Expression> e9 = () => TryGetThree(out var _);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, \"var _\").WithLocation(31, 59),\n // (32,44): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e10 = () => _ = (bool)o;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"_ = (bool)o\").WithLocation(32, 44),\n // (33,46): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e11 = () => _ = (_, _) = GetTuple();\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"_ = (_, _) = GetTuple()\").WithLocation(33, 46),\n // (33,50): error CS8143: An expression tree may not contain a tuple literal.\n // Expression> e11 = () => _ = (_, _) = GetTuple();\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, \"(_, _)\").WithLocation(33, 50),\n // (36,60): error CS8205: An expression tree may not contain a discard.\n // Expression> e14 = () => TryGetThree(out _);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, \"_\").WithLocation(36, 60)\n );\n }\n\n [Fact]\n public void DictionaryInitializerInCS5()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n var s = new Dictionary () {[1] = 2};\n }\n}\n\";\n CreateCompilationWithMscorlib45(text,\n new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef },\n parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics(\n // (8,46): error CS8026: Feature 'dictionary initializer' is not available in C# 5. Please use language version 6 or greater.\n // var s = new Dictionary () {[1] = 2};\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, \"[1] = 2\").WithArguments(\"dictionary initializer\", \"6\").WithLocation(8, 46)\n );\n }\n\n [Fact]\n public void DictionaryInitializerDataFlow()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n int i;\n var s = new Dictionary () {[i] = 2};\n\n i = 1;\n System.Console.WriteLine(i);\n }\n\n static void Goo()\n {\n int i;\n var s = new Dictionary () {[i = 1] = 2};\n\n System.Console.WriteLine(i);\n }\n}\n\";\n CreateCompilationWithMscorlib45(text,\n new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef },\n parseOptions: TestOptions.Regular).VerifyDiagnostics(\n // (9,47): error CS0165: Use of unassigned local variable 'i'\n // var s = new Dictionary () {[i] = 2};\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"i\").WithArguments(\"i\").WithLocation(9, 47)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccessNotStatement()\n {\n var text = @\"\nclass Program\n{\n static void Main()\n {\n var x = new int[10];\n\n x?.Length;\n x?[1];\n x?.ToString()[1];\n }\n}\n\";\n CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x?.Length;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x?.Length\").WithLocation(8, 9),\n // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x?[1];\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x?[1]\").WithLocation(9, 9),\n // (10,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x?.ToString()[1];\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x?.ToString()[1]\").WithLocation(10, 9)\n );\n }\n\n [WorkItem(23422, \"https://github.com/dotnet/roslyn/issues/23422\")]\n [Fact]\n public void ConditionalMemberAccessRefLike()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n var o = new Program();\n\n o?.F(); // this is ok\n\n var x = o?.F();\n\n var y = o?.F() ?? default;\n\n var z = o?.F().field ?? default;\n }\n\n S2 F() => throw null;\n}\n\npublic ref struct S1\n{\n\n}\n\npublic ref struct S2\n{\n public S1 field;\n}\n\";\n CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (10,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2'\n // var x = o?.F();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"S2\").WithLocation(10, 18),\n // (12,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2'\n // var y = o?.F() ?? default;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"S2\").WithLocation(12, 18),\n // (14,18): error CS0023: Operator '?' cannot be applied to operand of type 'S1'\n // var z = o?.F().field ?? default;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"S1\").WithLocation(14, 18)\n );\n }\n\n [Fact]\n [WorkItem(1179322, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179322\")]\n public void LabelSameNameAsParameter()\n {\n var text = @\"\nclass Program\n{\n static object M(object obj, object value)\n {\n if (((string)obj).Length == 0) value: new Program();\n }\n}\n\";\n var compilation = CreateCompilation(text);\n compilation.GetParseDiagnostics().Verify();\n\n // Make sure the compiler can handle producing method body diagnostics for this pattern when \n // queried via an API (command line compile would exit after parse errors were reported). \n compilation.GetMethodBodyDiagnostics().Verify(\n // (6,41): error CS1023: Embedded statement cannot be a declaration or labeled statement\n // if (((string)obj).Length == 0) value: new Program();\n Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, \"value: new Program();\").WithLocation(6, 41),\n // (6,41): warning CS0164: This label has not been referenced\n // if (((string)obj).Length == 0) value: new Program();\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"value\").WithLocation(6, 41),\n // (4,19): error CS0161: 'Program.M(object, object)': not all code paths return a value\n // static object M(object obj, object value)\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"M\").WithArguments(\"Program.M(object, object)\").WithLocation(4, 19));\n }\n\n [Fact]\n public void ThrowInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static bool b = true;\n static object o = string.Empty;\n static void Main(string[] args)\n {\n Expression> e1 = () => o ?? throw null;\n Expression> e2 = () => b ? throw null : o;\n Expression> e3 = () => b ? o : throw null;\n Expression> e4 = () => throw null;\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (13,54): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e1 = () => o ?? throw null;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(13, 54),\n // (14,53): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e2 = () => b ? throw null : o;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(14, 53),\n // (15,57): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e3 = () => b ? o : throw null;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(15, 57),\n // (16,49): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e4 = () => throw null;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(16, 49)\n );\n }\n\n [Fact, WorkItem(17674, \"https://github.com/dotnet/roslyn/issues/17674\")]\n public void VoidDiscardAssignment()\n {\n var text = @\"\nclass Program\n{\n public static void Main(string[] args)\n {\n _ = M();\n }\n static void M() { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (6,9): error CS8209: A value of type 'void' may not be assigned.\n // _ = M();\n Diagnostic(ErrorCode.ERR_VoidAssignment, \"_\").WithLocation(6, 9)\n );\n }\n\n [Fact, WorkItem(22880, \"https://github.com/dotnet/roslyn/issues/22880\")]\n public void AttributeCtorInParam()\n {\n var text = @\"\n[A(1)]\nclass A : System.Attribute {\n A(in int x) { }\n}\n\n[B()]\nclass B : System.Attribute {\n B(in int x = 1) { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (2,2): error CS8358: Cannot use attribute constructor 'A.A(in int)' because it has 'in' parameters.\n // [A(1)]\n Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, \"A(1)\").WithArguments(\"A.A(in int)\").WithLocation(2, 2),\n // (7,2): error CS8358: Cannot use attribute constructor 'B.B(in int)' because it has 'in' parameters.\n // [B()]\n Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, \"B()\").WithArguments(\"B.B(in int)\").WithLocation(7, 2)\n );\n }\n\n [Fact]\n public void ERR_ExpressionTreeContainsSwitchExpression()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class C\n{\n public int Test()\n {\n Expression> e = a => a switch { 0 => 1, _ => 2 }; // CS8411\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text, parseOptions: TestOptions.RegularWithRecursivePatterns).VerifyDiagnostics(\n // (9,45): error CS8411: An expression tree may not contain a switch expression.\n // Expression> e = a => a switch { 0 => 1, _ => 2 }; // CS8411\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, \"a switch { 0 => 1, _ => 2 }\").WithLocation(9, 45)\n );\n }\n\n [Fact]\n public void PointerGenericConstraintTypes()\n {\n var source = @\"\nnamespace A\n{\n class D {}\n}\n\nclass B {}\n\nunsafe class C where T : byte*\n where U : unmanaged\n where V : U*\n where X : object*\n where Y : B*\n where Z : A.D*\n{\n void M1() where A : byte* {}\n void M2() where A : unmanaged \n where B : A* {}\n void M3() where A : object* {}\n void M4() where A : B* {}\n void M5() where A : T {}\n}\";\n var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);\n comp.VerifyDiagnostics(\n // (9,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // unsafe class C where T : byte*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"byte*\").WithLocation(9, 44),\n // (11,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where V : U*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"U*\").WithLocation(11, 44),\n // (12,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where X : object*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"object*\").WithLocation(12, 44),\n // (13,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where Y : B*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"B*\").WithLocation(13, 44),\n // (14,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where Z : A.D*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"A.D*\").WithLocation(14, 44),\n // (16,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // void M1() where A : byte* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"byte*\").WithLocation(16, 28),\n // (18,31): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where B : A* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"A*\").WithLocation(18, 31),\n // (19,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // void M3() where A : object* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"object*\").WithLocation(19, 28),\n // (20,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // void M4() where A : B* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"B*\").WithLocation(20, 28)\n );\n }\n\n [Fact]\n public void ArrayGenericConstraintTypes()\n {\n var source = @\"class A where T : object[] {}\";\n\n var comp = CreateCompilation(source);\n comp.VerifyDiagnostics(\n // (1,22): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // class A where T : object[] {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"object[]\").WithLocation(1, 22));\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.CSharp.Test.Utilities;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\nusing static Roslyn.Test.Utilities.TestMetadata;\n\nnamespace Microsoft.CodeAnalysis.CSharp.UnitTests\n{\n /// \n /// this place is dedicated to binding related error tests\n /// \n public class SemanticErrorTests : CompilingTestBase\n {\n #region \"Targeted Error Tests - please arrange tests in the order of error code\"\n\n [Fact]\n public void CS0019ERR_BadBinaryOps01()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static void Main()\n {\n bool q = false;\n if (q == 1)\n { }\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 9, Column = 17 });\n }\n\n [Fact]\n public void CS0019ERR_BadBinaryOps02()\n {\n var text =\n@\"using System;\nenum E { A, B, C }\nenum F { X = (E.A + E.B) * DayOfWeek.Monday } // no error\nclass C\n{\n static void M(object o)\n {\n M((E.A + E.B) * DayOfWeek.Monday);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 8, Column = 12 });\n }\n\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps03()\n {\n var text =\n@\"delegate void MyDelegate1(ref int x, out float y);\nclass Program\n{\n public void DelegatedMethod1(ref int x, out float y)\n {\n y = 1;\n }\n public void DelegatedMethod2(out int x, ref float y)\n {\n x = 1;\n }\n public void DelegatedMethod3(out int x, float y = 1)\n {\n x = 1;\n }\n static void Main(string[] args)\n {\n Program mc = new Program();\n MyDelegate1 md1 = null;\n md1 += mc.DelegatedMethod1;\n md1 += mc.DelegatedMethod2; // Invalid\n md1 += mc.DelegatedMethod3; // Invalid\n md1 -= mc.DelegatedMethod1;\n md1 -= mc.DelegatedMethod2; // Invalid\n md1 -= mc.DelegatedMethod3; // Invalid\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (21,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1'\n // md1 += mc.DelegatedMethod2; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod2\").WithArguments(\"DelegatedMethod2\", \"MyDelegate1\"),\n // (22,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1'\n // md1 += mc.DelegatedMethod3; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod3\").WithArguments(\"DelegatedMethod3\", \"MyDelegate1\"),\n // (24,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1'\n // md1 -= mc.DelegatedMethod2; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod2\").WithArguments(\"DelegatedMethod2\", \"MyDelegate1\"),\n // (25,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1'\n // md1 -= mc.DelegatedMethod3; // Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"DelegatedMethod3\").WithArguments(\"DelegatedMethod3\", \"MyDelegate1\")\n );\n }\n\n // Method List to removal or concatenation\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps04()\n {\n var text =\n@\"using System;\ndelegate void boo();\npublic class abc\n{\n public void bar() { System.Console.WriteLine(\"\"bar\"\"); }\n static public void far() { System.Console.WriteLine(\"\"far\"\"); }\n}\nclass C\n{\n static void Main(string[] args)\n {\n abc p = new abc();\n boo goo = null;\n boo goo1 = new boo(abc.far);\n boo[] arrfoo = { p.bar, abc.far };\n goo += arrfoo; // Invalid\n goo -= arrfoo; // Invalid\n goo += new boo[] { p.bar, abc.far };\t// Invalid\n goo -= new boo[] { p.bar, abc.far };\t// Invalid\n goo += Delegate.Combine(arrfoo);\t// Invalid\n goo += Delegate.Combine(goo, goo1); \t// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo += arrfoo; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"arrfoo\").WithArguments(\"boo[]\", \"boo\"),\n // (17,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo -= arrfoo; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"arrfoo\").WithArguments(\"boo[]\", \"boo\"),\n // (18,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo += new boo[] { p.bar, abc.far };\t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new boo[] { p.bar, abc.far }\").WithArguments(\"boo[]\", \"boo\"),\n // (19,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo'\n // goo -= new boo[] { p.bar, abc.far };\t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new boo[] { p.bar, abc.far }\").WithArguments(\"boo[]\", \"boo\"),\n // (20,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?)\n // goo += Delegate.Combine(arrfoo);\t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"Delegate.Combine(arrfoo)\").WithArguments(\"System.Delegate\", \"boo\"),\n // (21,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?)\n // goo += Delegate.Combine(goo, goo1); \t// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"Delegate.Combine(goo, goo1)\").WithArguments(\"System.Delegate\", \"boo\")\n );\n }\n\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps05()\n {\n var text =\n@\"public delegate double MyDelegate1(ref int integerPortion, out float fraction);\npublic delegate double MyDelegate2(ref int integerPortion, out float fraction);\nclass C\n{\n static void Main(string[] args)\n {\n C mc = new C();\n MyDelegate1 md1 = null;\n MyDelegate2 md2 = null;\n md1 += md2; // Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0029: Cannot implicitly convert type 'MyDelegate2' to 'MyDelegate1'\n // md1 += md2; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"md2\").WithArguments(\"MyDelegate2\", \"MyDelegate1\")\n );\n }\n\n // Anonymous method to removal or concatenation\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps06()\n {\n var text =\n@\"delegate void boo(int x);\nclass C\n{\n static void Main(string[] args)\n {\n boo goo = null;\n goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid\n goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate (string x) { System.Console.WriteLine(x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (7,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (8,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate (string x) { System.Console.WriteLine(x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (8,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\")\n );\n }\n\n // Lambda expression to removal or concatenation\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps07()\n {\n var text =\n@\"delegate void boo(int x);\nclass C\n{\n static void Main(string[] args)\n {\n boo goo = null;\n goo += (string x) => { };// Invalid\n goo -= (string x) => { };// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"(string x) => { }\").WithArguments(\"lambda expression\", \"boo\"),\n // (7,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (8,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo -= (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"(string x) => { }\").WithArguments(\"lambda expression\", \"boo\"),\n // (8,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo -= (string x) => { };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\")\n );\n }\n\n // Successive operator for addition and subtraction assignment\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps08()\n {\n var text =\n@\"using System;\ndelegate void boo(int x);\nclass C\n{\n public void bar(int x) { Console.WriteLine(\"\"\"\", x); }\n static public void far(int x) { Console.WriteLine(\"\"far:{0}\"\", x); }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += p.bar + far;// Invalid\n goo += (x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); } + far;// Invalid\n goo += delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); } + far;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,16): error CS0019: Operator '+' cannot be applied to operands of type 'method group' and 'method group'\n // goo += p.bar + far;// Invalid\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"p.bar + far\").WithArguments(\"+\", \"method group\", \"method group\").WithLocation(11, 16),\n // (12,16): error CS0019: Operator '+' cannot be applied to operands of type 'lambda expression' and 'method group'\n // goo += (x) => { System.Console.WriteLine(\"Lambda:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.ERR_BadBinaryOps, @\"(x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); } + far\").WithArguments(\"+\", \"lambda expression\", \"method group\").WithLocation(12, 16),\n // (12,70): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate.\n // goo += (x) => { System.Console.WriteLine(\"Lambda:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"+\").WithArguments(\"+\").WithLocation(12, 70),\n // (13,16): error CS0019: Operator '+' cannot be applied to operands of type 'anonymous method' and 'method group'\n // goo += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.ERR_BadBinaryOps, @\"delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); } + far\").WithArguments(\"+\", \"anonymous method\", \"method group\").WithLocation(13, 16),\n // (13,83): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate.\n // goo += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); } + far;// Invalid\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"+\").WithArguments(\"+\").WithLocation(13, 83)\n );\n }\n\n // Removal or concatenation for the delegate on Variance\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps09()\n {\n var text =\n@\"using System.Collections.Generic;\n\ndelegate IList Delegate1(List x);\ndelegate IEnumerable Delegate2(IList x);\ndelegate IEnumerable Delegate3(IList x);\n\nclass C\n{\n public static List Method1(IList x)\n {\n return null;\n }\n\n public static IList Method1(IList x)\n {\n return null;\n }\n static void Main(string[] args)\n {\n Delegate1 d1 = Method1;\n d1 += Method1;\n Delegate2 d2 = Method1;\n d2 += Method1;\n Delegate3 d3 = Method1;\n d1 += d2; // invalid\n d2 += d1; // invalid\n d2 += d3; // invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (25,15): error CS0029: Cannot implicitly convert type 'Delegate2' to 'Delegate1'\n // d1 += d2; // invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"d2\").WithArguments(\"Delegate2\", \"Delegate1\"),\n // (26,15): error CS0029: Cannot implicitly convert type 'Delegate1' to 'Delegate2'\n // d2 += d1; // invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"d1\").WithArguments(\"Delegate1\", \"Delegate2\"),\n // (27,15): error CS0029: Cannot implicitly convert type 'Delegate3' to 'Delegate2'\n // d2 += d3; // invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"d3\").WithArguments(\"Delegate3\", \"Delegate2\")\n );\n }\n\n // generic-delegate (goo(...)) += non generic-methodgroup(bar(...))\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps10()\n {\n var text =\n@\"delegate void boo(T x);\nclass C\n{\n public void bar(int x) { System.Console.WriteLine(\"\"bar:{0}\"\", x); }\n public void bar1(string x) { System.Console.WriteLine(\"\"bar1:{0}\"\", x); }\n\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += p.bar;// OK\n goo += p.bar1;// Invalid\n goo += (x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// OK\n goo += (string x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// Invalid\n goo += delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// OK\n goo += delegate (string x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// Invalid\n\n boo goo1 = null;\n goo1 += p.bar;// Invalid\n goo1 += p.bar1;// OK\n goo1 += (x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// OK\n goo1 += (int x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); };// Invalid\n goo1 += delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// Invalid\n goo1 += delegate (string x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); };// OK\n goo += goo1;// Invalid\n goo1 += goo;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,18): error CS0123: No overload for 'bar1' matches delegate 'boo'\n // goo += p.bar1;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"bar1\").WithArguments(\"bar1\", \"boo\"),\n // (14,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += (string x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"(string x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); }\").WithArguments(\"lambda expression\", \"boo\"),\n // (14,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += (string x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (16,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo += delegate (string x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"delegate (string x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (16,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int'\n // goo += delegate (string x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"string\", \"\", \"int\"),\n // (19,19): error CS0123: No overload for 'bar' matches delegate 'boo'\n // goo1 += p.bar;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"bar\").WithArguments(\"bar\", \"boo\"),\n // (22,17): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo1 += (int x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"(int x) => { System.Console.WriteLine(\"\"Lambda:{0}\"\", x); }\").WithArguments(\"lambda expression\", \"boo\"),\n // (22,22): error CS1678: Parameter 1 is declared as type 'int' but should be 'string'\n // goo1 += (int x) => { System.Console.WriteLine(\"Lambda:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"int\", \"\", \"string\"),\n // (23,17): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types\n // goo1 += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @\"delegate (int x) { System.Console.WriteLine(\"\"Anonymous:{0}\"\", x); }\").WithArguments(\"anonymous method\", \"boo\"),\n // (23,31): error CS1678: Parameter 1 is declared as type 'int' but should be 'string'\n // goo1 += delegate (int x) { System.Console.WriteLine(\"Anonymous:{0}\", x); };// Invalid\n Diagnostic(ErrorCode.ERR_BadParamType, \"x\").WithArguments(\"1\", \"\", \"int\", \"\", \"string\"),\n // (25,16): error CS0029: Cannot implicitly convert type 'boo' to 'boo'\n // goo += goo1;// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"goo1\").WithArguments(\"boo\", \"boo\"),\n // (26,17): error CS0029: Cannot implicitly convert type 'boo' to 'boo'\n // goo1 += goo;// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"goo\").WithArguments(\"boo\", \"boo\")\n );\n }\n\n // generic-delegate (goo(...)) += generic-methodgroup(bar(...))\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps11()\n {\n var text =\n@\"delegate void boo(T x);\nclass C\n{\n static void far(T x) { }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += far;// OK\n goo += far;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0123: No overload for 'far' matches delegate 'boo'\n // goo += far;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"far\").WithArguments(\"far\", \"boo\")\n );\n }\n\n // non generic-delegate (goo(...)) += generic-methodgroup(bar(...))\n [WorkItem(539906, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps12()\n {\n var text =\n@\"delegate void boo(T x);\nclass C\n{\n static void far(T x) { }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += far;// OK\n goo += far;// Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0123: No overload for 'far' matches delegate 'boo'\n // goo += far;// Invalid\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"far\").WithArguments(\"far\", \"boo\")\n );\n }\n\n // distinguish '|' from '||'\n [WorkItem(540235, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540235\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps13()\n {\n var text = @\"\nclass C\n{\n int a = 1 | 1;\n int b = 1 & 1;\n int c = 1 || 1;\n int d = 1 && 1;\n\n bool e = true | true;\n bool f = true & true;\n bool g = true || true;\n bool h = true && true;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,13): error CS0019: Operator '||' cannot be applied to operands of type 'int' and 'int'\n // int c = 1 || 1;\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"1 || 1\").WithArguments(\"||\", \"int\", \"int\"),\n // (7,13): error CS0019: Operator '&&' cannot be applied to operands of type 'int' and 'int'\n // int d = 1 && 1;\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"1 && 1\").WithArguments(\"&&\", \"int\", \"int\"),\n // (4,9): warning CS0414: The field 'C.a' is assigned but its value is never used\n // int a = 1 | 1;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"a\").WithArguments(\"C.a\"),\n // (5,9): warning CS0414: The field 'C.b' is assigned but its value is never used\n // int b = 1 & 1;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"b\").WithArguments(\"C.b\"),\n // (9,10): warning CS0414: The field 'C.e' is assigned but its value is never used\n // bool e = true | true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"e\").WithArguments(\"C.e\"),\n // (10,10): warning CS0414: The field 'C.f' is assigned but its value is never used\n // bool f = true & true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"f\").WithArguments(\"C.f\"),\n // (11,10): warning CS0414: The field 'C.g' is assigned but its value is never used\n // bool g = true || true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"g\").WithArguments(\"C.g\"),\n // (12,10): warning CS0414: The field 'C.h' is assigned but its value is never used\n // bool h = true && true;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"h\").WithArguments(\"C.h\"));\n }\n\n /// \n /// Conversion errors for Null Coalescing operator(??)\n /// \n [Fact]\n public void CS0019ERR_BadBinaryOps14()\n {\n var text = @\"\npublic class D { }\npublic class Error\n{\n public int? NonNullableValueType_a(int a)\n {\n int? b = null;\n int? z = a ?? b;\n return z;\n }\n public int? NonNullableValueType_b(char ch)\n {\n char b = ch;\n int? z = null ?? b;\n return z;\n }\n public int NonNullableValueType_const_a(char ch)\n {\n char b = ch;\n int z = 10 ?? b;\n return z;\n }\n public D NoPossibleConversionError()\n {\n D b = new D();\n Error a = null;\n D z = a ?? b;\n return z;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'int?'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"a ?? b\").WithArguments(\"??\", \"int\", \"int?\"),\n // (13,18): error CS0019: Operator '??' cannot be applied to operands of type '' and 'char'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null ?? b\").WithArguments(\"??\", \"\", \"char\"),\n // (19,17): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'char'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"10 ?? b\").WithArguments(\"??\", \"int\", \"char\"),\n // (26,15): error CS0019: Operator '??' cannot be applied to operands of type 'Error' and 'D'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"a ?? b\").WithArguments(\"??\", \"Error\", \"D\"));\n }\n\n [WorkItem(542115, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542115\")]\n [Fact]\n public void CS0019ERR_BadBinaryOps15()\n {\n var text =\n@\"class C\n{\n static void M(T1 t1, T2 t2, T3 t3, T4 t4, int i, C c)\n where T2 : class\n where T3 : struct\n where T4 : T1\n {\n bool b;\n b = (t1 == t1);\n b = (t1 == t2);\n b = (t1 == t3);\n b = (t1 == t4);\n b = (t1 == i);\n b = (t1 == c);\n b = (t1 == null);\n b = (t2 == t1);\n b = (t2 == t2);\n b = (t2 == t3);\n b = (t2 == t4);\n b = (t2 == i);\n b = (t2 == c);\n b = (t2 == null);\n b = (t3 == t1);\n b = (t3 == t2);\n b = (t3 == t3);\n b = (t3 == t4);\n b = (t3 == i);\n b = (t3 == c);\n b = (t3 == null);\n b = (t4 != t1);\n b = (t4 != t2);\n b = (t4 != t3);\n b = (t4 != t4);\n b = (t4 != i);\n b = (t4 != c);\n b = (t4 != null);\n b = (i != t1);\n b = (i != t2);\n b = (i != t3);\n b = (i != t4);\n b = (i != i);\n b = (i != c);\n b = (i != null);\n b = (c != t1);\n b = (c != t2);\n b = (c != t3);\n b = (c != t4);\n b = (c != i);\n b = (c != c);\n b = (c != null);\n b = (null != t1);\n b = (null != t2);\n b = (null != t3);\n b = (null != t4);\n b = (null != i);\n b = (null != c);\n b = (null != null);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T1'\n // b = (t1 == t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t1\").WithArguments(\"==\", \"T1\", \"T1\"),\n // (10,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T2'\n // b = (t1 == t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t2\").WithArguments(\"==\", \"T1\", \"T2\"),\n // (11,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T3'\n // b = (t1 == t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t3\").WithArguments(\"==\", \"T1\", \"T3\"),\n // (12,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T4'\n // b = (t1 == t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == t4\").WithArguments(\"==\", \"T1\", \"T4\"),\n // (13,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'int'\n // b = (t1 == i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == i\").WithArguments(\"==\", \"T1\", \"int\"),\n // (14,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'C'\n // b = (t1 == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t1 == c\").WithArguments(\"==\", \"T1\", \"C\"),\n // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T1'\n // b = (t2 == t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == t1\").WithArguments(\"==\", \"T2\", \"T1\"),\n // (18,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T3'\n // b = (t2 == t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == t3\").WithArguments(\"==\", \"T2\", \"T3\"),\n // (19,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T4'\n // b = (t2 == t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == t4\").WithArguments(\"==\", \"T2\", \"T4\"),\n // (20,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'int'\n // b = (t2 == i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t2 == i\").WithArguments(\"==\", \"T2\", \"int\"),\n // (23,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T1'\n // b = (t3 == t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t1\").WithArguments(\"==\", \"T3\", \"T1\"),\n // (24,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T2'\n // b = (t3 == t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t2\").WithArguments(\"==\", \"T3\", \"T2\"),\n // (25,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T3'\n // b = (t3 == t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t3\").WithArguments(\"==\", \"T3\", \"T3\"),\n // (26,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T4'\n // b = (t3 == t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == t4\").WithArguments(\"==\", \"T3\", \"T4\"),\n // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'int'\n // b = (t3 == i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == i\").WithArguments(\"==\", \"T3\", \"int\"),\n // (28,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'C'\n // b = (t3 == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == c\").WithArguments(\"==\", \"T3\", \"C\"),\n // (29,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and ''\n // b = (t3 == null);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t3 == null\").WithArguments(\"==\", \"T3\", \"\"),\n // (30,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T1'\n // b = (t4 != t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t1\").WithArguments(\"!=\", \"T4\", \"T1\"),\n // (31,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T2'\n // b = (t4 != t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t2\").WithArguments(\"!=\", \"T4\", \"T2\"),\n // (32,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T3'\n // b = (t4 != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t3\").WithArguments(\"!=\", \"T4\", \"T3\"),\n // (33,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T4'\n // b = (t4 != t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != t4\").WithArguments(\"!=\", \"T4\", \"T4\"),\n // (34,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'int'\n // b = (t4 != i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != i\").WithArguments(\"!=\", \"T4\", \"int\"),\n // (35,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'C'\n // b = (t4 != c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t4 != c\").WithArguments(\"!=\", \"T4\", \"C\"),\n // (37,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T1'\n // b = (i != t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t1\").WithArguments(\"!=\", \"int\", \"T1\"),\n // (38,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T2'\n // b = (i != t2);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t2\").WithArguments(\"!=\", \"int\", \"T2\"),\n // (39,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T3'\n // b = (i != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t3\").WithArguments(\"!=\", \"int\", \"T3\"),\n // (40,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T4'\n // b = (i != t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != t4\").WithArguments(\"!=\", \"int\", \"T4\"),\n // (42,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'C'\n // b = (i != c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"i != c\").WithArguments(\"!=\", \"int\", \"C\"),\n // (44,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T1'\n // b = (c != t1);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != t1\").WithArguments(\"!=\", \"C\", \"T1\"),\n // (46,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T3'\n // b = (c != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != t3\").WithArguments(\"!=\", \"C\", \"T3\"),\n // (47,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T4'\n // b = (c != t4);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != t4\").WithArguments(\"!=\", \"C\", \"T4\"),\n // (48,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'int'\n // b = (c != i);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c != i\").WithArguments(\"!=\", \"C\", \"int\"),\n // (53,14): error CS0019: Operator '!=' cannot be applied to operands of type '' and 'T3'\n // b = (null != t3);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null != t3\").WithArguments(\"!=\", \"\", \"T3\"),\n // (17,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // b = (t2 == t2);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"t2 == t2\"),\n // (41,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // b = (i != i);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"i != i\"),\n // (43,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // b = (i != null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != null\").WithArguments(\"true\", \"int\", \"int?\"),\n // (49,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // b = (c != c);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"c != c\"),\n // (55,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // b = (null != i);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != i\").WithArguments(\"true\", \"int\", \"int?\"));\n }\n\n [Fact]\n public void CS0019ERR_BadBinaryOps16()\n {\n var text =\n@\"class A { }\nclass B : A { }\ninterface I { }\nclass C\n{\n static void M(T t, U u, A a, B b, C c, I i)\n where T : A\n where U : B\n {\n bool x;\n x = (t == t);\n x = (t == u);\n x = (t == a);\n x = (t == b);\n x = (t == c);\n x = (t == i);\n x = (u == t);\n x = (u == u);\n x = (u == a);\n x = (u == b);\n x = (u == c);\n x = (u == i);\n x = (a == t);\n x = (a == u);\n x = (a == a);\n x = (a == b);\n x = (a == c);\n x = (a == i);\n x = (b == t);\n x = (b == u);\n x = (b == a);\n x = (b == b);\n x = (b == c);\n x = (b == i);\n x = (c == t);\n x = (c == u);\n x = (c == a);\n x = (c == b);\n x = (c == c);\n x = (c == i);\n x = (i == t);\n x = (i == u);\n x = (i == a);\n x = (i == b);\n x = (i == c);\n x = (i == i);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,14): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'C'\n // x = (t == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"t == c\").WithArguments(\"==\", \"T\", \"C\"),\n // (21,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and 'C'\n // x = (u == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"u == c\").WithArguments(\"==\", \"U\", \"C\"),\n // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'A' and 'C'\n // x = (a == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"a == c\").WithArguments(\"==\", \"A\", \"C\"),\n // (33,14): error CS0019: Operator '==' cannot be applied to operands of type 'B' and 'C'\n // x = (b == c);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"b == c\").WithArguments(\"==\", \"B\", \"C\"),\n // (35,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'T'\n // x = (c == t);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == t\").WithArguments(\"==\", \"C\", \"T\"),\n // (36,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'U'\n // x = (c == u);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == u\").WithArguments(\"==\", \"C\", \"U\"),\n // (37,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A'\n // x = (c == a);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == a\").WithArguments(\"==\", \"C\", \"A\"),\n // (38,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'B'\n // x = (c == b);\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"c == b\").WithArguments(\"==\", \"C\", \"B\"),\n // (11,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (t == t);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"t == t\"),\n // (18,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (u == u);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"u == u\"),\n // (25,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (a == a);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"a == a\"),\n // (32,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (b == b);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"b == b\"),\n // (39,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (c == c);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"c == c\"),\n // (46,14): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // x = (i == i);\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"i == i\"));\n }\n\n [Fact]\n public void CS0019ERR_BadBinaryOps17()\n {\n var text =\n@\"struct S { }\nabstract class A\n{\n internal virtual void M(U u) where U : T\n {\n bool b;\n b = (u == null);\n b = (null != u);\n }\n}\nclass B : A\n{\n internal override void M(U u)\n {\n bool b;\n b = (u == null);\n b = (null != u);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and ''\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"u == null\").WithArguments(\"==\", \"U\", \"\").WithLocation(16, 14),\n // (17,14): error CS0019: Operator '!=' cannot be applied to operands of type '' and 'U'\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null != u\").WithArguments(\"!=\", \"\", \"U\").WithLocation(17, 14));\n }\n\n [Fact]\n public void CS0020ERR_IntDivByZero()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static int Main()\n {\n int s = 1 / 0; // CS0020\n return s;\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 21 } });\n }\n\n [Fact]\n public void CS0020ERR_IntDivByZero_02()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static void Main()\n {\n decimal x1 = 1.20M / 0; // CS0020\n decimal x2 = 1.20M / decimal.Zero; // CS0020\n decimal x3 = decimal.MaxValue / decimal.Zero; // CS0020\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 26 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 9, Column = 26 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 10, Column = 26 } });\n }\n\n [Fact]\n public void CS0021ERR_BadIndexLHS()\n {\n var text =\n@\"enum E { }\nclass C\n{\n static void M()\n {\n object o;\n o = M[0];\n o = ((System.Action)null)[0];\n o = ((dynamic)o)[0];\n o = default(E)[0];\n o = default(T)[0];\n o = (new C())[0];\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,13): error CS0021: Cannot apply indexing with [] to an expression of type 'method group'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"M[0]\").WithArguments(\"method group\").WithLocation(7, 13),\n // (8,13): error CS0021: Cannot apply indexing with [] to an expression of type 'System.Action'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"((System.Action)null)[0]\").WithArguments(\"System.Action\").WithLocation(8, 13),\n // (10,13): error CS0021: Cannot apply indexing with [] to an expression of type 'E'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"default(E)[0]\").WithArguments(\"E\").WithLocation(10, 13),\n // (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'T'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"default(T)[0]\").WithArguments(\"T\").WithLocation(11, 13),\n // (12,13): error CS0021: Cannot apply indexing with [] to an expression of type 'C'\n Diagnostic(ErrorCode.ERR_BadIndexLHS, \"(new C())[0]\").WithArguments(\"C\").WithLocation(12, 13));\n }\n\n [Fact]\n public void CS0022ERR_BadIndexCount()\n {\n var text = @\"\nnamespace x\n{\n public class b\n {\n public static void Main()\n {\n int[,] a = new int[10,2] ;\n a[2] = 4; //bad index count in access\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIndexCount, Line = 9, Column = 25 } });\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount02()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1 2]; //bad index count in size specifier - no initializer\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS1003: Syntax error, ',' expected\n Diagnostic(ErrorCode.ERR_SyntaxError, \"2\").WithArguments(\",\", \"\"));\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount03()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1 2] { 1 }; //bad index count in size specifier - with initializer\n }\n}\n\";\n // NOTE: Dev10 just gives a parse error on '2'\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS1003: Syntax error, ',' expected\n Diagnostic(ErrorCode.ERR_SyntaxError, \"2\").WithArguments(\",\", \"\"),\n // (6,35): error CS0846: A nested array initializer is expected\n Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, \"1\"));\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount04()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1,]; //bad index count in size specifier - no initializer\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS0443: Syntax error; value expected\n Diagnostic(ErrorCode.ERR_ValueExpected, \"\"));\n }\n\n [WorkItem(542486, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486\")]\n [Fact]\n public void CS0022ERR_BadIndexCount05()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int[,] a = new int[1,] { { 1 } }; //bad index count in size specifier - with initializer\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,30): error CS0443: Syntax error; value expected\n Diagnostic(ErrorCode.ERR_ValueExpected, \"\"));\n }\n\n [WorkItem(539590, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp1()\n {\n var text = @\"\nnamespace X\n{\n class C\n {\n object M()\n {\n object q = new object();\n if (!q) // CS0023\n { }\n\n object obj = -null; // CS0023\n obj = !null; // CS0023\n obj = ~null; // CS0023\n\n obj++; // CS0023\n --obj; // CS0023\n return +null; // CS0023\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,17): error CS0023: Operator '!' cannot be applied to operand of type 'object'\n // if (!q) // CS0023\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"!q\").WithArguments(\"!\", \"object\").WithLocation(9, 17),\n // (12,26): error CS8310: Operator '-' cannot be applied to operand ''\n // object obj = -null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"-null\").WithArguments(\"-\", \"\").WithLocation(12, 26),\n // (13,19): error CS8310: Operator '!' cannot be applied to operand ''\n // obj = !null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"!null\").WithArguments(\"!\", \"\").WithLocation(13, 19),\n // (14,19): error CS8310: Operator '~' cannot be applied to operand ''\n // obj = ~null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"~null\").WithArguments(\"~\", \"\").WithLocation(14, 19),\n // (16,13): error CS0023: Operator '++' cannot be applied to operand of type 'object'\n // obj++; // CS0023\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"obj++\").WithArguments(\"++\", \"object\").WithLocation(16, 13),\n // (17,13): error CS0023: Operator '--' cannot be applied to operand of type 'object'\n // --obj; // CS0023\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"--obj\").WithArguments(\"--\", \"object\").WithLocation(17, 13),\n // (18,20): error CS8310: Operator '+' cannot be applied to operand ''\n // return +null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"+null\").WithArguments(\"+\", \"\").WithLocation(18, 20)\n );\n }\n\n [WorkItem(539590, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_Nullable()\n {\n var text = @\"\npublic class Test\n{\n public static void Main()\n {\n bool? b = !null; // CS0023\n int? n = ~null; // CS0023\n float? f = +null; // CS0023\n long? u = -null; // CS0023\n\n ++n;\n n--;\n --u;\n u++;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,19): error CS8310: Operator '!' cannot be applied to operand ''\n // bool? b = !null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"!null\").WithArguments(\"!\", \"\").WithLocation(6, 19),\n // (7,18): error CS8310: Operator '~' cannot be applied to operand ''\n // int? n = ~null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"~null\").WithArguments(\"~\", \"\").WithLocation(7, 18),\n // (8,20): error CS8310: Operator '+' cannot be applied to operand ''\n // float? f = +null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"+null\").WithArguments(\"+\", \"\").WithLocation(8, 20),\n // (9,19): error CS8310: Operator '-' cannot be applied to operand ''\n // long? u = -null; // CS0023\n Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, \"-null\").WithArguments(\"-\", \"\").WithLocation(9, 19)\n );\n }\n\n [WorkItem(539590, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp2()\n {\n var text = @\"\nnamespace X\n{\n class C\n {\n void M()\n {\n System.Action f = M;\n f = +M; // CS0023\n f = +(() => { }); // CS0023\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,17): error CS0023: Operator '+' cannot be applied to operand of type 'method group'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"+M\").WithArguments(\"+\", \"method group\"),\n // (10,17): error CS0023: Operator '+' cannot be applied to operand of type 'lambda expression'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"+(() => { })\").WithArguments(\"+\", \"lambda expression\"));\n }\n\n [WorkItem(540211, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_VoidMissingInstanceMethod()\n {\n var text = @\"class C\n{\n void M()\n {\n M().Goo();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \".\").WithArguments(\".\", \"void\"));\n }\n\n [WorkItem(540211, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_VoidToString()\n {\n var text = @\"class C\n{\n void M()\n {\n M().ToString(); //plausible, but still wrong\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void'\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \".\").WithArguments(\".\", \"void\"));\n }\n\n [WorkItem(540329, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_null()\n {\n var text = @\"\nclass X\n{\n static void Main()\n {\n int x = null.Length;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"null.Length\").WithArguments(\".\", \"\"));\n }\n\n [WorkItem(540329, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329\")]\n [Fact]\n public void CS0023ERR_BadUnaryOp_lambdaExpression()\n {\n var text = @\"\nclass X\n{\n static void Main()\n {\n System.Func f = arg => { arg = 2; return arg; }.ToString();\n \n var x = delegate { }.ToString();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"arg => { arg = 2; return arg; }.ToString\").WithArguments(\".\", \"lambda expression\"),\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"delegate { }.ToString\").WithArguments(\".\", \"anonymous method\"));\n }\n\n [Fact]\n public void CS0026ERR_ThisInStaticMeth()\n {\n var text = @\"\npublic class MyClass\n{\n public static int i = 0;\n\n public static void Main()\n {\n // CS0026\n this.i = this.i + 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 18 }\n });\n }\n\n [Fact]\n public void CS0026ERR_ThisInStaticMeth_StaticConstructor()\n {\n var text = @\"\npublic class MyClass\n{\n int f;\n void M() { }\n int P { get; set; }\n\n static MyClass()\n {\n this.f = this.P;\n this.M();\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (10,18): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (11,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"));\n }\n\n [Fact]\n public void CS0026ERR_ThisInStaticMeth_Combined()\n {\n var text = @\"\nusing System;\n\nclass CLS\n{\n static CLS() { var x = this.ToString(); }\n static object FLD = this.ToString();\n static object PROP { get { return this.ToString(); } }\n static object METHOD() { return this.ToString(); }\n}\n\nclass A : Attribute\n{\n public object P;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,25): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static object FLD = this.ToString();\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (6,28): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static CLS() { var x = this.ToString(); }\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (8,39): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static object PROP { get { return this.ToString(); } }\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (9,37): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer\n // static object METHOD() { return this.ToString(); }\n Diagnostic(ErrorCode.ERR_ThisInStaticMeth, \"this\"),\n // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null\n // public object P;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"P\").WithArguments(\"A.P\", \"null\")\n );\n }\n\n [Fact]\n public void CS0027ERR_ThisInBadContext()\n {\n var text = @\"\nnamespace ConsoleApplication3\n{\n class MyClass\n {\n int err1 = this.Fun() + 1; // CS0027 \n public void Fun()\n {\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 6, Column = 20 } });\n }\n\n [Fact]\n public void CS0027ERR_ThisInBadContext_2()\n {\n var text = @\"\nusing System;\n\n[assembly: A(P = this.ToString())]\n\nclass A : Attribute\n{\n public object P;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,18): error CS0027: Keyword 'this' is not available in the current context\n // [assembly: A(P = this.ToString())]\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\"));\n }\n\n [Fact]\n public void CS0027ERR_ThisInBadContext_Interactive()\n {\n string text = @\"\nint a;\nint b = a;\nint c = this.a; // 1\nthis.c = // 2\n this.a; // 3\nint prop { get { return 1; } set { this.a = 1;} } // 4\n\nvoid goo() {\n this.goo(); // 5\n this.a = // 6\n this.b; // 7\n object c = this; // 8\n}\n\nthis.prop = 1; // 9\n\nclass C\n{\n C() : base()\n {\n }\n\n void goo()\n {\n this.goo(); // OK\n }\n}\";\n var comp = CreateCompilationWithMscorlib45(\n new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script) });\n comp.VerifyDiagnostics(\n // (4,9): error CS0027: Keyword 'this' is not available in the current context\n // int c = this.a; // 1\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(4, 9),\n // (5,1): error CS0027: Keyword 'this' is not available in the current context\n // this.c = // 2\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(5, 1),\n // (6,5): error CS0027: Keyword 'this' is not available in the current context\n // this.a; // 3\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(6, 5),\n // (16,1): error CS0027: Keyword 'this' is not available in the current context\n // this.prop = 1; // 9\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(16, 1),\n // (7,36): error CS0027: Keyword 'this' is not available in the current context\n // int prop { get { return 1; } set { this.a = 1;} } // 4\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(7, 36),\n // (10,5): error CS0027: Keyword 'this' is not available in the current context\n // this.goo(); // 5\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(10, 5),\n // (11,5): error CS0027: Keyword 'this' is not available in the current context\n // this.a = // 6\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(11, 5),\n // (12,9): error CS0027: Keyword 'this' is not available in the current context\n // this.b; // 7\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(12, 9),\n // (13,16): error CS0027: Keyword 'this' is not available in the current context\n // object c = this; // 8\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(13, 16)\n );\n }\n\n [Fact]\n public void CS0029ERR_NoImplicitConv01()\n {\n var text = @\"\nnamespace ConsoleApplication3\n{\n class MyClass\n {\n\n int err1 = 1; \n\n public string Fun()\n {\n return err1;\n }\n\n public static void Main()\n {\n MyClass c = new MyClass();\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConv, Line = 11, Column = 20 } });\n }\n\n [Fact]\n public void CS0029ERR_NoImplicitConv02()\n {\n var source = \"enum E { A = new[] { 1, 2, 3 } }\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,14): error CS0029: Cannot implicitly convert type 'int[]' to 'int'\n // enum E { A = new[] { 1, 2, 3 } }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new[] { 1, 2, 3 }\").WithArguments(\"int[]\", \"int\").WithLocation(1, 14));\n }\n\n [Fact]\n public void CS0029ERR_NoImplicitConv03()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n const C d = F();\n }\n static D F()\n {\n return null;\n }\n}\nclass D\n{\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,21): error CS0029: Cannot implicitly convert type 'D' to 'C'\n // const C d = F();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"F()\").WithArguments(\"D\", \"C\").WithLocation(5, 21));\n }\n\n [WorkItem(541719, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541719\")]\n [Fact]\n public void CS0029ERR_NoImplicitConv04()\n {\n var text =\n@\"class C1\n{\n public static void Main()\n {\n bool m = true;\n int[] arr = new int[m]; // Invalid\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,29): error CS0029: Cannot implicitly convert type 'bool' to 'int'\n // int[] arr = new int[m]; // Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"m\").WithArguments(\"bool\", \"int\").WithLocation(6, 29));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void ThrowExpression_ImplicitVoidConversion_Return()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n return true ? throw null : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,23): error CS0029: Cannot implicitly convert type '' to 'void'\n // return true ? throw null : M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"throw null\").WithArguments(\"\", \"void\").WithLocation(6, 23));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void ThrowExpression_ImplicitVoidConversion_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n object obj = true ? throw null : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,29): error CS0029: Cannot implicitly convert type '' to 'void'\n // object obj = true ? throw null : M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"throw null\").WithArguments(\"\", \"void\").WithLocation(6, 29));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void IntLiteral_ImplicitVoidConversion_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n var obj = true ? 0 : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,19): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'void'\n // var obj = true ? 0 : M2();\n Diagnostic(ErrorCode.ERR_InvalidQM, \"true ? 0 : M2()\").WithArguments(\"int\", \"void\").WithLocation(6, 19)\n );\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_ImplicitVoidConversion_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n object obj = true ? M2() : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object'\n // object obj = true ? M2() : M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"true ? M2() : M2()\").WithArguments(\"void\", \"object\").WithLocation(6, 22));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_ImplicitVoidConversion_DiscardAssignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n _ = true ? M2() : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS8209: A value of type 'void' may not be assigned.\n // _ = true ? M2() : M2();\n Diagnostic(ErrorCode.ERR_VoidAssignment, \"_\").WithLocation(6, 9));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_Assignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n object obj = M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object'\n // object obj = M2();\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"M2()\").WithArguments(\"void\", \"object\").WithLocation(6, 22));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_DiscardAssignment()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n _ = M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS8209: A value of type 'void' may not be assigned.\n // _ = M2();\n Diagnostic(ErrorCode.ERR_VoidAssignment, \"_\").WithLocation(6, 9));\n }\n\n [Fact, WorkItem(40405, \"https://github.com/dotnet/roslyn/issues/40405\")]\n public void VoidCall_ImplicitVoidConversion_Return()\n {\n string text = @\"\nclass C\n{\n void M1()\n {\n return true ? M2() : M2();\n }\n\n void M2() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0127: Since 'C.M1()' returns void, a return keyword must not be followed by an object expression\n // return true ? M2() : M2();\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"C.M1()\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0030ERR_NoExplicitConv()\n {\n var text = @\"\nnamespace x\n{\n public class iii\n {\n public static iii operator ++(iii aa)\n {\n return (iii)0; // CS0030\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,20): error CS0030: Cannot convert type 'int' to 'x.iii'\n // return (iii)0; // CS0030\n Diagnostic(ErrorCode.ERR_NoExplicitConv, \"(iii)0\").WithArguments(\"int\", \"x.iii\"));\n }\n\n [WorkItem(528539, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539\")]\n [WorkItem(1119609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609\")]\n [WorkItem(920, \"http://github.com/dotnet/roslyn/issues/920\")]\n [Fact]\n public void CS0030ERR_NoExplicitConv02()\n {\n const string text = @\"\npublic class C\n{\n public static void Main()\n {\n decimal x = (decimal)double.PositiveInfinity;\n }\n}\";\n var diagnostics = CreateCompilation(text).GetDiagnostics();\n\n var savedCurrentCulture = Thread.CurrentThread.CurrentCulture;\n var savedCurrentUICulture = Thread.CurrentThread.CurrentUICulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;\n\n try\n {\n diagnostics.Verify(\n // (6,21): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal'\n // decimal x = (decimal)double.PositiveInfinity;\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.PositiveInfinity\").WithArguments(\"Infinity\", \"decimal\"),\n // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used\n // decimal x = (decimal)double.PositiveInfinity;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\"));\n }\n finally\n {\n Thread.CurrentThread.CurrentCulture = savedCurrentCulture;\n Thread.CurrentThread.CurrentUICulture = savedCurrentUICulture;\n }\n }\n\n [Fact]\n public void CS0030ERR_NoExplicitConv_Foreach()\n {\n var text = @\"\npublic class Test\n{\n static void Main(string[] args)\n {\n int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } };\n foreach (int outer in arr) { } // invalid\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoExplicitConv, \"foreach\").WithArguments(\"int[]\", \"int\"));\n }\n\n [Fact]\n public void CS0031ERR_ConstOutOfRange01()\n {\n var text =\n@\"public class a\n{\n int num = (int)2147483648M; //CS0031\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (3,15): error CS0031: Constant value '2147483648M' cannot be converted to a 'int'\n // int num = (int)2147483648M; //CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(int)2147483648M\").WithArguments(\"2147483648M\", \"int\"),\n // (3,9): warning CS0414: The field 'a.num' is assigned but its value is never used\n // int num = (int)2147483648M; //CS0031\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"num\").WithArguments(\"a.num\"));\n }\n\n [WorkItem(528539, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539\")]\n [Fact]\n public void CS0031ERR_ConstOutOfRange02()\n {\n var text = @\"\nenum E : ushort\n{\n A = 10,\n B = -1 // CS0031\n}\nenum F : sbyte\n{\n A = 0x7f,\n B = 0xf0, // CS0031\n C,\n D = (A + 1) - 2,\n E = (A + 1), // CS0031\n}\nclass A\n{\n byte bt = 256;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,9): error CS0031: Constant value '-1' cannot be converted to a 'ushort'\n // B = -1 // CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"-1\").WithArguments(\"-1\", \"ushort\").WithLocation(5, 9),\n // (10,9): error CS0031: Constant value '240' cannot be converted to a 'sbyte'\n // B = 0xf0, // CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"0xf0\").WithArguments(\"240\", \"sbyte\").WithLocation(10, 9),\n // (13,10): error CS0031: Constant value '128' cannot be converted to a 'sbyte'\n // E = (A + 1), // CS0031\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"A + 1\").WithArguments(\"128\", \"sbyte\").WithLocation(13, 10),\n // (17,15): error CS0031: Constant value '256' cannot be converted to a 'byte'\n // byte bt = 256;\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"256\").WithArguments(\"256\", \"byte\").WithLocation(17, 15),\n // (17,10): warning CS0414: The field 'A.bt' is assigned but its value is never used\n // byte bt = 256;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"bt\").WithArguments(\"A.bt\").WithLocation(17, 10));\n }\n\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked04()\n {\n // Confirm that we truncate the constant value before performing the range check\n var template =\n@\"public class C\n{\n void M()\n {\n System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 0.9));\n System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 1.0)); //CS0221\n System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 0.9));\n System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 1.0)); //CS0221\n }\n}\n\";\n var integralTypes = new Type[]\n {\n typeof(char),\n typeof(sbyte),\n typeof(byte),\n typeof(short),\n typeof(ushort),\n typeof(int),\n typeof(uint),\n };\n\n foreach (Type t in integralTypes)\n {\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(template.Replace(\"System.Int32\", t.ToString()),\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 });\n }\n }\n\n // Note that the errors for Int64 and UInt64 are not\n // exactly the same as for Int32, etc. above, but the\n // differences match the native compiler.\n [WorkItem(528715, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528715\")]\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked05()\n {\n // Confirm that we truncate the constant value before performing the range check\n var text1 =\n@\"public class C\n{\n void M()\n {\n System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 0.9));\n System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 1.0));\n System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 0.9)); //CS0221\n System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 1.0)); //CS0221\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text1,\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 });\n\n var text2 =\n@\"public class C\n{\n void M()\n {\n System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 0.9));\n System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 1.0)); //CS0221\n System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 0.9)); //CS0221\n System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 1.0)); //CS0221\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text2,\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 });\n\n var text3 =\n@\"class C\n{\n static void Main()\n {\n System.Console.WriteLine(long.MinValue);\n System.Console.WriteLine((long)(double)long.MinValue);\n }\n}\";\n CreateCompilation(text3).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0034ERR_AmbigBinaryOps()\n {\n #region \"Source\"\n var text = @\"\npublic class A\n{\n // allows for the conversion of A object to int\n public static implicit operator int(A s)\n {\n return 0;\n }\n\n public static implicit operator string(A i)\n {\n return null;\n }\n}\n\npublic class B\n{\n public static implicit operator int(B s)\n // one way to resolve this CS0034 is to make one conversion explicit\n // public static explicit operator int (B s)\n {\n return 0;\n }\n\n public static implicit operator string(B i)\n {\n return null;\n }\n\n public static implicit operator B(string i)\n {\n return null;\n }\n\n public static implicit operator B(int i)\n {\n return null;\n }\n}\n\npublic class C\n{\n public static void Main()\n {\n A a = new A();\n B b = new B();\n b = b + a; // CS0034\n // another way to resolve this CS0034 is to make a cast\n // b = b + (int)a;\n }\n}\n\";\n #endregion\n\n CreateCompilation(text).VerifyDiagnostics(\n // (47,13): error CS0034: Operator '+' is ambiguous on operands of type 'B' and 'A'\n // b = b + a; // CS0034\n Diagnostic(ErrorCode.ERR_AmbigBinaryOps, \"b + a\").WithArguments(\"+\", \"B\", \"A\"));\n }\n\n [Fact]\n public void CS0035ERR_AmbigUnaryOp_RoslynCS0023()\n {\n var text = @\"\nclass MyClass\n{\n private int i;\n\n public MyClass(int i)\n {\n this.i = i;\n }\n\n public static implicit operator double(MyClass x)\n {\n return (double)x.i;\n }\n\n public static implicit operator decimal(MyClass x)\n {\n return (decimal)x.i;\n }\n}\n\nclass MyClass2\n{\n static void Main()\n {\n MyClass x = new MyClass(7);\n object o = -x; // CS0035\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (27,20): error CS0035: Operator '-' is ambiguous on an operand of type 'MyClass'\n // object o = -x; // CS0035\n Diagnostic(ErrorCode.ERR_AmbigUnaryOp, \"-x\").WithArguments(\"-\", \"MyClass\"));\n }\n\n [Fact]\n public void CS0037ERR_ValueCantBeNull01()\n {\n var source =\n@\"enum E { }\nstruct S { }\nclass C\n{\n static void M()\n {\n int i;\n i = null;\n i = (int)null;\n E e;\n e = null;\n e = (E)null;\n S s;\n s = null;\n s = (S)null;\n X x;\n x = null;\n x = (X)null;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"null\").WithArguments(\"int\").WithLocation(8, 13),\n // (9,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(int)null\").WithArguments(\"int\").WithLocation(9, 13),\n // (11,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"null\").WithArguments(\"E\").WithLocation(11, 13),\n // (12,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(E)null\").WithArguments(\"E\").WithLocation(12, 13),\n // (14,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"null\").WithArguments(\"S\").WithLocation(14, 13),\n // (15,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(S)null\").WithArguments(\"S\").WithLocation(15, 13),\n // (16,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"X\").WithArguments(\"X\").WithLocation(16, 9),\n // (18,14): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"X\").WithArguments(\"X\").WithLocation(18, 14));\n }\n\n [Fact]\n public void CS0037ERR_ValueCantBeNull02()\n {\n var source =\n@\"interface I { }\nclass A { }\nclass B\n where T2 : class\n where T3 : struct\n where T4 : new()\n where T5 : I\n where T6 : A\n where T7 : T1\n{\n static void M(object o)\n {\n o = (T1)null;\n o = (T2)null;\n o = (T3)null;\n o = (T4)null;\n o = (T5)null;\n o = (T6)null;\n o = (T7)null;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,17): error CS0037: Cannot convert null to 'T1' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T1)null\").WithArguments(\"T1\").WithLocation(13, 13),\n // (15,17): error CS0037: Cannot convert null to 'T3' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T3)null\").WithArguments(\"T3\").WithLocation(15, 13),\n // (16,17): error CS0037: Cannot convert null to 'T4' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T4)null\").WithArguments(\"T4\").WithLocation(16, 13),\n // (17,17): error CS0037: Cannot convert null to 'T5' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T5)null\").WithArguments(\"T5\").WithLocation(17, 13),\n // (19,17): error CS0037: Cannot convert null to 'T7' because it is a non-nullable value type\n Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(T7)null\").WithArguments(\"T7\").WithLocation(19, 13));\n }\n\n [WorkItem(539589, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539589\")]\n [Fact]\n public void CS0037ERR_ValueCantBeNull03()\n {\n var text = @\"\nclass Program\n{\n enum MyEnum\n {\n Zero = 0,\n One = 1\n }\n\n static int Main()\n {\n return Goo((MyEnum)null);\n }\n\n static int Goo(MyEnum x)\n {\n return 1;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ValueCantBeNull, \"(MyEnum)null\").WithArguments(\"Program.MyEnum\").WithLocation(12, 20));\n }\n\n [Fact(), WorkItem(528875, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528875\")]\n public void CS0038ERR_WrongNestedThis()\n {\n var text = @\"\nclass OuterClass\n{\n public int count;\n // try the following line instead\n // public static int count;\n\n class InnerClass\n {\n void func()\n {\n // or, create an instance\n // OuterClass class_inst = new OuterClass();\n // int count2 = class_inst.count;\n int count2 = count; // CS0038\n }\n }\n\n public static void Main()\n {\n }\n}\";\n // Triage decided not to implement the more specific error (WrongNestedThis) and stick with ObjectRequired.\n var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary()\n {\n { MessageProvider.Instance.GetIdForErrorCode(649), ReportDiagnostic.Suppress }\n }));\n\n comp.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ObjectRequired, \"count\").WithArguments(\"OuterClass.count\"));\n }\n\n [Fact]\n public void CS0039ERR_NoExplicitBuiltinConv01()\n {\n var text =\n@\"class A\n{\n}\nclass B: A\n{\n}\nclass C: A\n{\n}\nclass M\n{\n static void Main()\n {\n A a = new C();\n B b = new B();\n C c;\n\n // This is valid; there is a built-in reference\n // conversion from A to C.\n c = a as C; \n\n //The following generates CS0039; there is no\n // built-in reference conversion from B to C.\n c = b as C; // CS0039\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (24,13): error CS0039: Cannot convert type 'B' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion\n Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, \"b as C\").WithArguments(\"B\", \"C\").WithLocation(24, 13));\n }\n\n [Fact, WorkItem(541142, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541142\")]\n public void CS0039ERR_NoExplicitBuiltinConv02()\n {\n var text =\n@\"delegate void D();\nclass C\n{\n static void M(C c)\n {\n (F as D)();\n (c.F as D)();\n (G as D)();\n }\n void F() { }\n static void G() { }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // (F as D)();\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"F as D\").WithLocation(6, 10),\n // (7,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // (c.F as D)();\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"c.F as D\").WithLocation(7, 10),\n // (8,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // (G as D)();\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"G as D\").WithLocation(8, 10));\n }\n\n [Fact, WorkItem(542047, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542047\")]\n public void CS0039ERR_ConvTypeReferenceToObject()\n {\n var text = @\"using System;\nclass C\n{\n static void Main()\n {\n TypedReference a = new TypedReference();\n object obj = a as object; //CS0039\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n //(7,22): error CS0039: Cannot convert type 'System.TypedReference' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion\n Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, \"a as object\").WithArguments(\"System.TypedReference\", \"object\").WithLocation(7, 22));\n }\n\n [Fact]\n public void CS0069ERR_EventPropertyInInterface()\n {\n var text = @\"\ninterface I\n{\n event System.Action E1 { add; }\n event System.Action E2 { remove; }\n event System.Action E3 { add; remove; }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(\n // (4,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E1 { add; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"add\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(4, 30),\n // (4,33): error CS0073: An add or remove accessor must have a body\n // event System.Action E1 { add; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(4, 33),\n // (5,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E2 { remove; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"remove\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(5, 30),\n // (5,36): error CS0073: An add or remove accessor must have a body\n // event System.Action E2 { remove; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(5, 36),\n // (6,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"add\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(6, 30),\n // (6,33): error CS0073: An add or remove accessor must have a body\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(6, 33),\n // (6,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, \"remove\").WithArguments(\"default interface implementation\", \"8.0\").WithLocation(6, 35),\n // (6,41): error CS0073: An add or remove accessor must have a body\n // event System.Action E3 { add; remove; }\n Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, \";\").WithLocation(6, 41),\n // (4,25): error CS0065: 'I.E1': event property must have both add and remove accessors\n // event System.Action E1 { add; }\n Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, \"E1\").WithArguments(\"I.E1\").WithLocation(4, 25),\n // (5,25): error CS0065: 'I.E2': event property must have both add and remove accessors\n // event System.Action E2 { remove; }\n Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, \"E2\").WithArguments(\"I.E2\").WithLocation(5, 25));\n }\n\n [Fact]\n public void CS0070ERR_BadEventUsage()\n {\n var text = @\"\npublic delegate void EventHandler();\n\npublic class A\n{\n public event EventHandler Click;\n\n public static void OnClick()\n {\n EventHandler eh;\n A a = new A();\n eh = a.Click;\n }\n\n public static void Main()\n {\n }\n}\n\npublic class B\n{\n public int mf ()\n {\n EventHandler eh = new EventHandler(A.OnClick);\n A a = new A();\n eh = a.Click; // CS0070\n // try the following line instead\n // a.Click += eh;\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsage, Line = 26, Column = 14 } });\n }\n\n [Fact]\n public void CS0079ERR_BadEventUsageNoField()\n {\n var text = @\"\npublic delegate void MyEventHandler();\n\npublic class Class1\n{\n private MyEventHandler _e;\n\n public event MyEventHandler Pow\n {\n add\n {\n _e += value;\n }\n remove\n {\n _e -= value;\n }\n }\n\n public void Handler()\n {\n }\n\n public void Fire()\n {\n if (_e != null)\n {\n Pow(); // CS0079\n // try the following line instead\n // _e();\n }\n }\n\n public static void Main()\n {\n Class1 p = new Class1();\n p.Pow += new MyEventHandler(p.Handler);\n p._e();\n p.Pow += new MyEventHandler(p.Handler);\n p._e();\n p._e -= new MyEventHandler(p.Handler);\n if (p._e != null)\n {\n p._e();\n }\n p.Pow -= new MyEventHandler(p.Handler);\n if (p._e != null)\n {\n p._e();\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsageNoField, Line = 28, Column = 13 } });\n }\n\n [WorkItem(538213, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538213\")]\n [Fact]\n public void CS0103ERR_NameNotInContext()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n IO.File.Exists(\"\"test\"\");\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"IO\").WithArguments(\"IO\").WithLocation(6, 9));\n }\n\n [WorkItem(542574, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542574\")]\n [Fact]\n public void CS0103ERR_NameNotInContextLambdaExtension()\n {\n var text = @\"using System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] sourceA = { 1, 2, 3, 4, 5 };\n int[] sourceB = { 3, 4, 5, 6, 7 };\n\n var query = sourceA.Join(sourceB, a => b, b => 5, (a, b) => a + b);\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"b\").WithArguments(\"b\").WithLocation(9, 48));\n }\n\n [Fact()]\n public void CS0103ERR_NameNotInContext_foreach()\n {\n var text = @\"class C\n{\n static void Main()\n {\n foreach (var y in new[] {new {y = y }}){ }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"y\").WithArguments(\"y\").WithLocation(5, 43));\n }\n\n [WorkItem(528780, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528780\")]\n [Fact]\n public void CS0103ERR_NameNotInContext_namedAndOptional()\n {\n var text = @\"using System;\nclass NamedExample\n{\n static void Main(string[] args)\n {\n }\n static int CalculateBMI(int weight, int height = weight)\n {\n return (weight * 703) / (height * height);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,54): error CS0103: The name 'weight' does not exist in the current context\n // static int CalculateBMI(int weight, int height = weight)\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"weight\").WithArguments(\"weight\").WithLocation(7, 54),\n // (1,1): hidden CS8019: Unnecessary using directive.\n // using System;\n Diagnostic(ErrorCode.HDN_UnusedUsingDirective, \"using System;\").WithLocation(1, 1)\n );\n }\n\n [Fact]\n public void CS0118ERR_BadSKknown()\n {\n CreateCompilation(\n@\"public class TestType {}\n\npublic class MyClass {\n\n public static int Main() {\n TestType myTest = new TestType();\n bool b = myTest is myTest;\n return 1;\n }\n\n}\", parseOptions: TestOptions.Regular6)\n .VerifyDiagnostics(\n // (7,22): error CS0118: 'myTest' is a 'variable' but is used like a 'type'\n Diagnostic(ErrorCode.ERR_BadSKknown, \"myTest\").WithArguments(\"myTest\", \"variable\", \"type\"));\n }\n\n [Fact]\n public void CS0118ERR_BadSKknown_02()\n {\n CreateCompilation(@\"\nusing System;\npublic class P {\n public static void Main(string[] args) {\n#pragma warning disable 219\n Action a = null;\n Action b = null;\n }\n}\")\n .VerifyDiagnostics(\n // (6,16): error CS0118: 'args' is a variable but is used like a type\n // Action a = null;\n Diagnostic(ErrorCode.ERR_BadSKknown, \"args\").WithArguments(\"args\", \"variable\", \"type\").WithLocation(6, 16),\n // (7,16): error CS0118: 'a' is a variable but is used like a type\n // Action b = null;\n Diagnostic(ErrorCode.ERR_BadSKknown, \"a\").WithArguments(\"a\", \"variable\", \"type\").WithLocation(7, 16));\n }\n\n\n [Fact]\n public void CS0118ERR_BadSKknown_CheckedUnchecked()\n {\n string source = @\"\nusing System;\n \nclass Program\n{\n static void Main()\n {\n\t\tvar z = 1;\n \n\t\t(Console).WriteLine(); // error\n (System).Console.WriteLine(); // error\n checked(Console).WriteLine(); // error \n checked(System).Console.WriteLine(); // error\n\n checked(z).ToString(); // ok\n checked(typeof(Console)).ToString(); // ok\n checked(Console.WriteLine)(); // ok\n checked(z) = 1; // ok\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,4): error CS0119: 'System.Console' is a type, which is not valid in the given context\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"Console\").WithArguments(\"System.Console\", \"type\"),\n // (11,10): error CS0118: 'System' is a namespace but is used like a variable\n Diagnostic(ErrorCode.ERR_BadSKknown, \"System\").WithArguments(\"System\", \"namespace\", \"variable\"),\n // (12,17): error CS0119: 'System.Console' is a type, which is not valid in the given context\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"Console\").WithArguments(\"System.Console\", \"type\"),\n // (13,17): error CS0118: 'System' is a namespace but is used like a variable\n Diagnostic(ErrorCode.ERR_BadSKknown, \"System\").WithArguments(\"System\", \"namespace\", \"variable\"));\n }\n\n [WorkItem(542773, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542773\")]\n [Fact]\n public void CS0119ERR_BadSKunknown01_switch()\n {\n CreateCompilation(\n@\"class A\n{\n public static void Main()\n { }\n void goo(color color1)\n {\n switch (color)\n {\n default:\n break;\n }\n }\n}\nenum color\n{\n blue,\n green\n}\n\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadSKunknown, \"color\").WithArguments(\"color\", \"type\"));\n }\n\n [Fact, WorkItem(538214, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214\"), WorkItem(528703, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528703\")]\n public void CS0119ERR_BadSKunknown01()\n {\n var source =\n@\"class Test\n{\n public static void M()\n {\n int x = 0;\n x = (global::System.Int32) + x;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,14): error CS0119: 'int' is a type, which is not valid in the given context\n // x = (global::System.Int32) + x;\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"global::System.Int32\").WithArguments(\"int\", \"type\"),\n // (6,14): error CS0119: 'int' is a type, which is not valid in the given context\n // x = (global::System.Int32) + x;\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"global::System.Int32\").WithArguments(\"int\", \"type\"));\n }\n\n [Fact]\n public void CS0119ERR_BadSKunknown02()\n {\n var source =\n@\"class A\n{\n internal static object F;\n internal static void M() { }\n}\nclass B where T : A\n{\n static void M(T t)\n {\n U.ReferenceEquals(T.F, null);\n T.M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,27): error CS0119: 'T' is a type parameter, which is not valid in the given context\n // U.ReferenceEquals(T.F, null);\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"T\").WithArguments(\"T\", \"type parameter\"),\n // (10,9): error CS0119: 'U' is a type parameter, which is not valid in the given context\n // U.ReferenceEquals(T.F, null);\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"U\").WithArguments(\"U\", \"type parameter\"),\n // (11,9): error CS0119: 'T' is a type parameter, which is not valid in the given context\n // T.M();\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"T\").WithArguments(\"T\", \"type parameter\"),\n // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null\n // internal static object F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"A.F\", \"null\")\n );\n }\n\n [WorkItem(541203, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541203\")]\n [Fact]\n public void CS0119ERR_BadSKunknown_InThrowStmt()\n {\n CreateCompilation(\n@\"class Test\n{\n public static void M()\n {\n throw System.Exception;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"System.Exception\").WithArguments(\"System.Exception\", \"type\"));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue01()\n {\n var source =\n@\"namespace x\n{\n public class C\n {\n const int x = 1;\n\n const int a = x + b;\n const int b = x + c;\n const int c = x + d;\n const int d = x + e;\n const int e = x + a;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,19): error CS0110: The evaluation of the constant value for 'x.C.a' involves a circular definition\n // const int a = x + b;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"a\").WithArguments(\"x.C.a\").WithLocation(7, 19));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue02()\n {\n var source =\n@\"enum E { A = B, B = A }\nenum F { X, Y = Y }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition\n // enum E { A = B, B = A }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"A\").WithArguments(\"E.A\").WithLocation(1, 10),\n // (2,13): error CS0110: The evaluation of the constant value for 'F.Y' involves a circular definition\n // enum F { X, Y = Y }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"Y\").WithArguments(\"F.Y\").WithLocation(2, 13));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue03()\n {\n var source =\n@\"enum E { A, B = A } // no error\nenum F { W, X = Z, Y, Z }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (2,13): error CS0110: The evaluation of the constant value for 'F.X' involves a circular definition\n // enum F { W, X = Z, Y, Z }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"X\").WithArguments(\"F.X\").WithLocation(2, 13));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue04()\n {\n var source =\n@\"enum E { A = B, B }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition\n // enum E { A = B, B }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"A\").WithArguments(\"E.A\").WithLocation(1, 10));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue05()\n {\n var source =\n@\"enum E { A = C, B = C, C }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,17): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition\n // enum E { A = C, B = C, C }\n Diagnostic(ErrorCode.ERR_CircConstValue, \"B\").WithArguments(\"E.B\").WithLocation(1, 17));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue06()\n {\n var source =\n@\"class C\n{\n private const int F = (int)E.B;\n enum E { A = F, B }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,23): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition\n // private const int F = (int)E.B;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"F\").WithArguments(\"C.F\").WithLocation(3, 23));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue07()\n {\n // Should report errors from other subexpressions\n // in addition to circular reference.\n var source =\n@\"class C\n{\n const int F = (long)(F + F + G);\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,34): error CS0103: The name 'G' does not exist in the current context\n // const int F = (long)(F + F + G);\n Diagnostic(ErrorCode.ERR_NameNotInContext, \"G\").WithArguments(\"G\").WithLocation(3, 34),\n // (3,15): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition\n // const int F = (long)(F + F + G);\n Diagnostic(ErrorCode.ERR_CircConstValue, \"F\").WithArguments(\"C.F\").WithLocation(3, 15));\n }\n\n [Fact]\n public void CS0110ERR_CircConstValue08()\n {\n // Decimal constants are special (since they're not runtime constants).\n var source =\n@\"class C\n{\n const decimal D = D;\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,19): error CS0110: The evaluation of the constant value for 'C.D' involves a circular definition\n // const decimal D = D;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"D\").WithArguments(\"C.D\").WithLocation(3, 19));\n }\n\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_1()\n {\n var test = @\"\nint x;\n\";\n CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics(\n // (2,5): warning CS0168: The variable 'x' is declared but never used\n // int x;\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"x\").WithArguments(\"x\").WithLocation(2, 5)\n );\n }\n\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_2()\n {\n var test = @\"\nnamespace x\n{\n using System;\n void Method(string str) // CS0116\n {\n Console.WriteLine(str);\n }\n}\nint AIProp { get ; set ; }\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test,\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 10 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 10, Column = 5 });\n }\n\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_3()\n {\n var test = @\"\nnamespace ns1\n{\n goto Labl; // Invalid\n const int x = 1;\n Lab1:\n const int y = 2;\n}\n\";\n // TODO (tomat): EOFUnexpected shouldn't be reported if we enable parsing global statements in namespaces\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test,\n // (4,5): error CS1022: Type or namespace definition, or end-of-file expected\n // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods\n // (4,14): error CS1022: Type or namespace definition, or end-of-file expected\n // (6,5): error CS0116: A namespace does not directly contain members such as fields or methods\n // (6,9): error CS1022: Type or namespace definition, or end-of-file expected\n // (5,15): error CS0116: A namespace does not directly contain members such as fields or methods\n // (7,15): error CS0116: A namespace does not directly contain members such as fields or methods\n new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 5 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 4, Column = 10 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 14 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 6, Column = 5 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 6, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 7, Column = 15 });\n }\n\n [WorkItem(540091, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091\")]\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_4()\n {\n var test = @\"\ndelegate int D();\nD d = null;\n\";\n CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics(\n // (3,1): error CS8803: Top-level statements must precede namespace and type declarations.\n // D d = null;\n Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, \"D d = null;\").WithLocation(3, 1),\n // (3,3): warning CS0219: The variable 'd' is assigned but its value is never used\n // D d = null;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"d\").WithArguments(\"d\").WithLocation(3, 3)\n );\n }\n\n [WorkItem(540091, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091\")]\n [Fact]\n public void CS0116ERR_NamespaceUnexpected_5()\n {\n var test = @\"\ndelegate int D();\nD d = {;}\n\";\n // In this case, CS0116 is suppressed because of the syntax errors\n\n CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics(\n // (3,1): error CS8803: Top-level statements must precede namespace and type declarations.\n // D d = {;}\n Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, \"D d = {;\").WithLocation(3, 1),\n // (3,8): error CS1513: } expected\n Diagnostic(ErrorCode.ERR_RbraceExpected, \";\"),\n // (3,9): error CS1022: Type or namespace definition, or end-of-file expected\n Diagnostic(ErrorCode.ERR_EOFExpected, \"}\"),\n // (3,7): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead.\n Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, \"{\"));\n }\n\n [WorkItem(539129, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539129\")]\n [Fact]\n public void CS0117ERR_NoSuchMember()\n {\n CreateCompilation(\n@\"enum E { }\nclass C\n{\n static void M()\n {\n C.F(E.A);\n C.P = C.Q;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"F\").WithArguments(\"C\", \"F\"),\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"A\").WithArguments(\"E\", \"A\"),\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"P\").WithArguments(\"C\", \"P\"),\n Diagnostic(ErrorCode.ERR_NoSuchMember, \"Q\").WithArguments(\"C\", \"Q\"));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired01()\n {\n CreateCompilation(\n@\"class C\n{\n object field;\n object Property { get; set; }\n void Method() { }\n static void M()\n {\n field = Property;\n C.field = C.Property;\n Method();\n C.Method();\n }\n}\n\")\n .VerifyDiagnostics(\n // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\").WithLocation(8, 9),\n // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\").WithLocation(8, 17),\n // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.field\").WithArguments(\"C.field\").WithLocation(9, 9),\n // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Property\").WithArguments(\"C.Property\").WithLocation(9, 19),\n // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\").WithLocation(10, 9),\n // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // C.Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Method\").WithArguments(\"C.Method()\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired02()\n {\n CreateCompilation(\n@\"using System;\n\nclass Program\n{\n private readonly int v = 5;\n delegate int del(int i);\n static void Main(string[] args)\n {\n del myDelegate = (int x) => x * v;\n Console.Write(string.Concat(myDelegate(7), \"\"he\"\"));\n }\n}\")\n .VerifyDiagnostics(\n // (9,41): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"v\").WithArguments(\"Program.v\"));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired03()\n {\n var source =\n@\"delegate int boo();\ninterface I\n{\n int bar();\n}\npublic struct abc : I\n{\n public int bar() { System.Console.WriteLine(\"\"bar\"\"); return 0x01; }\n}\nclass C\n{\n static void Main(string[] args)\n {\n abc p = new abc();\n boo goo = null;\n goo += new boo(I.bar);\n goo();\n }\n}\";\n CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(\n // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()'\n // goo += new boo(I.bar);\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"I.bar\").WithArguments(\"I.bar()\"),\n // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used\n // abc p = new abc();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"p\").WithArguments(\"p\")\n );\n CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics(\n // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()'\n // goo += new boo(I.bar);\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"I.bar\").WithArguments(\"I.bar()\").WithLocation(16, 24),\n // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used\n // abc p = new abc();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"p\").WithArguments(\"p\").WithLocation(14, 13)\n );\n }\n\n [WorkItem(543950, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543950\")]\n [Fact]\n public void CS0120ERR_ObjectRequired04()\n {\n CreateCompilation(\n@\"using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n var f = new Func(() => ToString());\n var g = new Func(() => GetHashCode());\n }\n}\")\n .VerifyDiagnostics(\n // (7,40): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()'\n // var f = new Func(() => ToString());\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"ToString\").WithArguments(\"object.ToString()\"),\n // (8,37): error CS0120: An object reference is required for the non-static field, method, or property 'object.GetHashCode()'\n // var g = new Func(() => GetHashCode());\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"GetHashCode\").WithArguments(\"object.GetHashCode()\")\n );\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired_ConstructorInitializer()\n {\n CreateCompilation(\n@\"class B\n{\n public B(params int[] p) { }\n}\n\nclass C : B\n{\n int instanceField;\n static int staticField;\n\n int InstanceProperty { get; set; }\n static int StaticProperty { get; set; }\n\n int InstanceMethod() { return 0; }\n static int StaticMethod() { return 0; }\n\n C(int param) : base(\n param,\n instanceField, //CS0120\n staticField,\n InstanceProperty, //CS0120\n StaticProperty,\n InstanceMethod(), //CS0120\n StaticMethod(),\n this.instanceField, //CS0027\n C.staticField,\n this.InstanceProperty, //CS0027\n C.StaticProperty,\n this.InstanceMethod(), //CS0027\n C.StaticMethod()) \n { \n }\n}\n\")\n .VerifyDiagnostics(\n // (19,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.instanceField'\n // instanceField, //CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"instanceField\").WithArguments(\"C.instanceField\").WithLocation(19, 9),\n // (21,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceProperty'\n // InstanceProperty, //CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"InstanceProperty\").WithArguments(\"C.InstanceProperty\").WithLocation(21, 9),\n // (23,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceMethod()'\n // InstanceMethod(), //CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"InstanceMethod\").WithArguments(\"C.InstanceMethod()\").WithLocation(23, 9),\n // (25,9): error CS0027: Keyword 'this' is not available in the current context\n // this.instanceField, //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(25, 9),\n // (27,9): error CS0027: Keyword 'this' is not available in the current context\n // this.InstanceProperty, //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(27, 9),\n // (29,9): error CS0027: Keyword 'this' is not available in the current context\n // this.InstanceMethod(), //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(29, 9),\n // (8,9): warning CS0649: Field 'C.instanceField' is never assigned to, and will always have its default value 0\n // int instanceField;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"instanceField\").WithArguments(\"C.instanceField\", \"0\").WithLocation(8, 9),\n // (9,16): warning CS0649: Field 'C.staticField' is never assigned to, and will always have its default value 0\n // static int staticField;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"staticField\").WithArguments(\"C.staticField\", \"0\").WithLocation(9, 16));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired_StaticConstructor()\n {\n CreateCompilation(\n@\"class C\n{\n object field;\n object Property { get; set; }\n void Method() { }\n static C()\n {\n field = Property;\n C.field = C.Property;\n Method();\n C.Method();\n }\n}\n\")\n .VerifyDiagnostics(\n // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\").WithLocation(8, 9),\n // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // field = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\").WithLocation(8, 17),\n // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.field\").WithArguments(\"C.field\").WithLocation(9, 9),\n // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // C.field = C.Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Property\").WithArguments(\"C.Property\").WithLocation(9, 19),\n // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\").WithLocation(10, 9),\n // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // C.Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"C.Method\").WithArguments(\"C.Method()\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0120ERR_ObjectRequired_NestedClass()\n {\n CreateCompilation(\n@\"\nclass C\n{\n object field;\n object Property { get; set; }\n void Method() { }\n\n class D\n {\n object field2;\n object Property2 { get; set; }\n\n public void Goo() \n {\n object f = field;\n object p = Property;\n Method();\n }\n\n public static void Bar() \n {\n object f1 = field;\n object p1 = Property;\n Method();\n\n object f2 = field2;\n object p2 = Property2;\n Goo();\n }\n }\n\n class E : C\n {\n public void Goo() \n {\n object f3 = field;\n object p3 = Property;\n Method();\n }\n }\n}\")\n .VerifyDiagnostics(\n // (15,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // object f = field;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\"),\n // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // object p = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\"),\n // (17,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\"),\n // (22,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.field'\n // object f1 = field;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field\").WithArguments(\"C.field\"),\n // (23,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property'\n // object p1 = Property;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property\").WithArguments(\"C.Property\"),\n // (24,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()'\n // Method();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Method\").WithArguments(\"C.Method()\"),\n // (26,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.field2'\n // object f2 = field2;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"field2\").WithArguments(\"C.D.field2\"),\n // (27,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Property2'\n // object p2 = Property2;\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Property2\").WithArguments(\"C.D.Property2\"),\n // (28,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Goo()'\n // Goo();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Goo\").WithArguments(\"C.D.Goo()\"),\n // (4,12): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null\n // object field;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"field\").WithArguments(\"C.field\", \"null\"),\n // (10,16): warning CS0649: Field 'C.D.field2' is never assigned to, and will always have its default value null\n // object field2;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"field2\").WithArguments(\"C.D.field2\", \"null\"));\n }\n\n [Fact, WorkItem(541505, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505\")]\n public void CS0120ERR_ObjectRequired_Attribute()\n {\n var text = @\"\nusing System.ComponentModel;\nenum ProtectionLevel\n{\n Privacy = 0\n}\nclass F\n{\n [DefaultValue(Prop.Privacy)] // CS0120\n ProtectionLevel Prop { get { return 0; } }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,17): error CS0120: An object reference is required for the non-static field, method, or property 'F.Prop'\n // [DefaultValue(Prop.Privacy)] // CS0120\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"Prop\").WithArguments(\"F.Prop\"),\n // (9,17): error CS0176: Member 'ProtectionLevel.Privacy' cannot be accessed with an instance reference; qualify it with a type name instead\n // [DefaultValue(Prop.Privacy)] // CS0120\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"Prop.Privacy\").WithArguments(\"ProtectionLevel.Privacy\") // Extra In Roslyn\n );\n }\n\n [Fact]\n public void CS0121ERR_AmbigCall()\n {\n var text = @\"\npublic class C\n{\n void f(int i, double d) { }\n void f(double d, int i) { }\n\n public static void Main()\n {\n new C().f(1, 1); // CS0121\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.f(int, double)' and 'C.f(double, int)'\n // new C().f(1, 1); // CS0121\n Diagnostic(ErrorCode.ERR_AmbigCall, \"f\").WithArguments(\"C.f(int, double)\", \"C.f(double, int)\")\n );\n }\n\n [WorkItem(539817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539817\")]\n [Fact]\n public void CS0122ERR_BadAccess()\n {\n var text = @\"\nclass Base\n{\n private class P { int X; }\n}\n\nclass Test : Base\n{\n void M()\n {\n object o = (P p) => 0;\n int x = P.X;\n int y = (P)null;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,21): error CS0122: 'Base.P' is inaccessible due to its protection level\n // object o = (P p) => 0;\n Diagnostic(ErrorCode.ERR_BadAccess, \"P\").WithArguments(\"Base.P\"),\n // (12,17): error CS0122: 'Base.P' is inaccessible due to its protection level\n // int x = P.X;\n Diagnostic(ErrorCode.ERR_BadAccess, \"P\").WithArguments(\"Base.P\"),\n // (13,18): error CS0122: 'Base.P' is inaccessible due to its protection level\n // int y = (P)null;\n Diagnostic(ErrorCode.ERR_BadAccess, \"P\").WithArguments(\"Base.P\"),\n // (4,27): warning CS0169: The field 'Base.P.X' is never used\n // private class P { int X; }\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"X\").WithArguments(\"Base.P.X\"));\n }\n\n [WorkItem(537683, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537683\")]\n [Fact]\n public void CS0122ERR_BadAccess02()\n {\n var text = @\"public class Outer\n{\n private class base1 { }\n}\n\npublic class MyClass : Outer.base1\n{\n}\n\";\n var comp = CreateCompilation(text);\n var type1 = comp.SourceModule.GlobalNamespace.GetMembers(\"MyClass\").Single() as NamedTypeSymbol;\n var b = type1.BaseType();\n var errs = comp.GetDiagnostics();\n Assert.Equal(1, errs.Count());\n Assert.Equal(122, errs.First().Code);\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [Fact]\n public void CS0122ERR_BadAccess03()\n {\n var text = @\"\nclass C1\n{\n private C1() { }\n}\nclass C2\n{\n protected C2() { }\n private C2(short x) {}\n}\n\nclass C3 : C2\n{\n C3() : base(3) {} // CS0122\n}\n\nclass Test\n{\n public static int Main()\n {\n C1 c1 = new C1(); // CS0122\n C2 c2 = new C2(); // CS0122\n return 1;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,12): error CS0122: 'C2.C2(short)' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"base\").WithArguments(\"C2.C2(short)\"),\n // (21,21): error CS0122: 'C1.C1()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"C1\").WithArguments(\"C1.C1()\"),\n // (22,21): error CS0122: 'C2.C2()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"C2\").WithArguments(\"C2.C2()\"));\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [WorkItem(540336, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540336\")]\n [Fact]\n public void CS0122ERR_BadAccess04()\n {\n var text = @\"\nclass A\n{\n protected class ProtectedClass { }\n\n public class B : I { }\n}\ninterface I { }\n\nclass Error\n{\n static void Goo(I i) { }\n\n static void Main()\n {\n Goo(new A.B());\n }\n}\n\";\n var tree = Parse(text);\n var compilation = CreateCompilation(tree);\n var model = compilation.GetSemanticModel(tree);\n\n var compilationUnit = tree.GetCompilationUnitRoot();\n var classError = (TypeDeclarationSyntax)compilationUnit.Members[2];\n var mainMethod = (MethodDeclarationSyntax)classError.Members[1];\n var callStmt = (ExpressionStatementSyntax)mainMethod.Body.Statements[0];\n var callExpr = callStmt.Expression;\n\n var callPosition = callExpr.SpanStart;\n\n var boundCall = model.GetSpeculativeSymbolInfo(callPosition, callExpr, SpeculativeBindingOption.BindAsExpression);\n\n Assert.Null(boundCall.Symbol);\n Assert.Equal(1, boundCall.CandidateSymbols.Length);\n Assert.Equal(CandidateReason.OverloadResolutionFailure, boundCall.CandidateReason);\n\n var constructedMethodSymbol = (IMethodSymbol)(boundCall.CandidateSymbols[0]);\n Assert.Equal(\"void Error.Goo(I i)\", constructedMethodSymbol.ToTestDisplayString());\n\n var typeArgSymbol = constructedMethodSymbol.TypeArguments.Single();\n Assert.Equal(\"A.ProtectedClass\", typeArgSymbol.ToTestDisplayString());\n Assert.False(model.IsAccessible(callPosition, typeArgSymbol), \"Protected inner class is inaccessible\");\n\n var paramTypeSymbol = constructedMethodSymbol.Parameters.Single().Type;\n Assert.Equal(\"I\", paramTypeSymbol.ToTestDisplayString());\n Assert.False(model.IsAccessible(callPosition, typeArgSymbol), \"Type should be inaccessible since type argument is inaccessible\");\n\n // The original test attempted to verify that \"Error.Goo\" is an \n // inaccessible method when inside Error.Main. The C# specification nowhere gives \n // a special rule for constructed generic methods; the accessibility domain of\n // a method depends only on its declared accessibility and the declared accessibility\n // of its containing type. \n //\n // We should decide whether the answer to \"is this method accessible in Main?\" is \n // yes or no, and if no, change the implementation of IsAccessible accordingly.\n //\n // Assert.False(model.IsAccessible(callPosition, constructedMethodSymbol), \"Method should be inaccessible since parameter type is inaccessible\");\n\n compilation.VerifyDiagnostics(\n // (16,9): error CS0122: 'Error.Goo(I)' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"Goo\").WithArguments(\"Error.Goo(I)\"));\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [Fact]\n public void CS0122ERR_BadAccess05()\n {\n var text = @\"\nclass Base\n{\n private Base() { }\n}\n\nclass Derived : Base\n{\n private Derived() : this(1) { } //fine: can see own private members\n private Derived(int x) : base() { } //CS0122: cannot see base private members\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,30): error CS0122: 'Base.Base()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"base\").WithArguments(\"Base.Base()\"));\n }\n\n [WorkItem(539628, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628\")]\n [Fact]\n public void CS0122ERR_BadAccess06()\n {\n var text = @\"\nclass Base\n{\n private Base() { } //private, but a match\n public Base(int x) { } //public, but not a match\n}\n\nclass Derived : Base\n{\n private Derived() { } //implicit constructor initializer\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,13): error CS0122: 'Base.Base()' is inaccessible due to its protection level\n Diagnostic(ErrorCode.ERR_BadAccess, \"Derived\").WithArguments(\"Base.Base()\"));\n }\n\n [Fact]\n public void CS0123ERR_MethDelegateMismatch()\n {\n var text = @\"\ndelegate void D();\ndelegate void D2(int i);\n\npublic class C\n{\n public static void f(int i) { }\n\n public static void Main()\n {\n D d = new D(f); // CS0123\n D2 d2 = new D2(f); // OK\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethDelegateMismatch, Line = 11, Column = 15 } });\n }\n\n [WorkItem(539909, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909\")]\n [Fact]\n public void CS0123ERR_MethDelegateMismatch_01()\n {\n var text = @\"\ndelegate void boo(short x);\nclass C\n{\n static void far(T x) { }\n static void Main(string[] args)\n {\n C p = new C();\n boo goo = null;\n goo += far;// Invalid\n goo += far;// OK\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,16): error CS0123: No overload for 'C.far(int)' matches delegate 'boo'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"far\").WithArguments(\"C.far(int)\", \"boo\"));\n }\n\n [WorkItem(539909, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909\")]\n [WorkItem(540053, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540053\")]\n [Fact]\n public void CS0123ERR_MethDelegateMismatch_02()\n {\n var text = @\"\ndelegate void boo(short x);\nclass C\n{\n public static void far(T x) { }\n public static void par(U x) { System.Console.WriteLine(\"\"par\"\"); }\n public static boo goo = null;\n\n}\nclass D\n{\n static void Main(string[] args)\n {\n C p = new C();\n C.goo += C.far;\n C.goo += C.par;\n C.goo(byte.MaxValue);\n C.goo(long.MaxValue);\n C.goo(long.MaxValue);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,24): error CS0123: No overload for 'C.far(long)' matches delegate 'boo'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"C.far\").WithArguments(\"C.far(long)\", \"boo\").WithLocation(15, 24),\n // (16,32): error CS0123: No overload for 'par' matches delegate 'boo'\n // C.goo += C.par;\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"par\").WithArguments(\"par\", \"boo\").WithLocation(16, 32),\n // (18,21): error CS1503: Argument 1: cannot convert from 'long' to 'short'\n Diagnostic(ErrorCode.ERR_BadArgType, \"long.MaxValue\").WithArguments(\"1\", \"long\", \"short\").WithLocation(18, 21),\n // (19,22): error CS1503: Argument 1: cannot convert from 'long' to 'short'\n Diagnostic(ErrorCode.ERR_BadArgType, \"long.MaxValue\").WithArguments(\"1\", \"long\", \"short\").WithLocation(19, 22)\n );\n }\n\n [Fact]\n public void CS0123ERR_MethDelegateMismatch_DelegateVariance()\n {\n var text = @\"\ndelegate TOut D(TIn p);\n\nclass A { }\nclass B : A { }\nclass C : B { }\n\nclass Test\n{\n static void Main()\n {\n D d;\n d = F1; //CS0407\n d = F2; //CS0407\n d = F3; //CS0123\n d = F4;\n d = F5;\n d = F6; //CS0123\n d = F7;\n d = F8;\n d = F9; //CS0123\n }\n\n static A F1(A p) { return null; }\n static A F2(B p) { return null; }\n static A F3(C p) { return null; }\n\n static B F4(A p) { return null; }\n static B F5(B p) { return null; }\n static B F6(C p) { return null; }\n\n static C F7(A p) { return null; }\n static C F8(B p) { return null; }\n static C F9(C p) { return null; }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (13,13): error CS0407: 'A Test.F1(A)' has the wrong return type\n Diagnostic(ErrorCode.ERR_BadRetType, \"F1\").WithArguments(\"Test.F1(A)\", \"A\"),\n // (14,13): error CS0407: 'A Test.F2(B)' has the wrong return type\n Diagnostic(ErrorCode.ERR_BadRetType, \"F2\").WithArguments(\"Test.F2(B)\", \"A\"),\n // (15,13): error CS0123: No overload for 'F3' matches delegate 'D'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"F3\").WithArguments(\"F3\", \"D\"),\n // (18,13): error CS0123: No overload for 'F6' matches delegate 'D'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"F6\").WithArguments(\"F6\", \"D\"),\n // (21,13): error CS0123: No overload for 'F9' matches delegate 'D'\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"F9\").WithArguments(\"F9\", \"D\"));\n }\n\n [Fact]\n public void CS0126ERR_RetObjectRequired()\n {\n var source =\n@\"namespace N\n{\n class C\n {\n object F() { return; }\n X G() { return; }\n C P { get { return; } }\n Y Q { get { return; } }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)\n // X G() { return; }\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"X\").WithArguments(\"X\").WithLocation(6, 9),\n // (8,9): error CS0246: The type or namespace name 'Y' could not be found (are you missing a using directive or an assembly reference?)\n // Y Q { get { return; } }\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"Y\").WithArguments(\"Y\").WithLocation(8, 9),\n // (5,22): error CS0126: An object of a type convertible to 'object' is required\n // object F() { return; }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"object\").WithLocation(5, 22),\n // (6,17): error CS0126: An object of a type convertible to 'X' is required\n // X G() { return; }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"X\").WithLocation(6, 17),\n // (7,21): error CS0126: An object of a type convertible to 'C' is required\n // C P { get { return; } }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"N.C\").WithLocation(7, 21),\n // (8,21): error CS0126: An object of a type convertible to 'Y' is required\n // Y Q { get { return; } }\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"Y\").WithLocation(8, 21));\n }\n\n [WorkItem(540115, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540115\")]\n [Fact]\n public void CS0126ERR_RetObjectRequired_02()\n {\n var source =\n@\"namespace Test\n{\n public delegate object D();\n\n public class TestClass\n {\n public static int Test(D src)\n {\n src();\n return 0;\n }\n }\n\n public class MainClass\n {\n public static int Main()\n {\n return TestClass.Test(delegate() { return; });\n// The native compiler produces two errors for this code:\n//\n// CS0126: An object of a type convertible to 'object' is required\n//\n// CS1662: Cannot convert anonymous method to delegate type \n// 'Test.D' because some of the return types in the block are not implicitly \n// convertible to the delegate return type\n//\n// This is not great; the first error is right, but does not tell us anything about\n// the fact that overload resolution has failed on the first argument. The second\n// error is actually incorrect; it is not that 'some of the return types are incorrect',\n// it is that some of the returns do not return anything in the first place! There's\n// no 'type' to get wrong. \n//\n// I would like Roslyn to give two errors:\n//\n// CS1503: Argument 1: cannot convert from 'anonymous method' to 'Test.D'\n// CS0126: An object of a type convertible to 'object' is required\n//\n// Neal Gafter says: I'd like one error instead of two. There is an error inside the\n// body of the lambda. It is enough to report that specific error. This is consistent\n// with our design guideline to suppress errors higher in the tree when it is caused\n// by an error lower in the tree.\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (18,48): error CS0126: An object of a type convertible to 'object' is required\n // return TestClass.Test(delegate() { return; });\n Diagnostic(ErrorCode.ERR_RetObjectRequired, \"return\").WithArguments(\"object\").WithLocation(18, 48));\n }\n\n [Fact]\n public void CS0127ERR_RetNoObjectRequired()\n {\n var source =\n@\"namespace MyNamespace\n{\n public class MyClass\n {\n public void F() { return 0; } // CS0127\n public int P\n {\n get { return 0; }\n set { return 0; } // CS0127, set has an implicit void return type\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,27): error CS0127: Since 'MyClass.F()' returns void, a return keyword must not be followed by an object expression\n // public void F() { return 0; } // CS0127\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"MyNamespace.MyClass.F()\").WithLocation(5, 27),\n // (9,19): error CS0127: Since 'MyClass.P.set' returns void, a return keyword must not be followed by an object expression\n // set { return 0; } // CS0127, set has an implicit void return type\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"MyNamespace.MyClass.P.set\").WithLocation(9, 19));\n }\n\n [Fact]\n public void CS0127ERR_RetNoObjectRequired_StaticConstructor()\n {\n string text = @\"\nclass C\n{\n static C()\n {\n return 1;\n }\n}\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0127: Since 'C.C()' returns void, a return keyword must not be followed by an object expression\n Diagnostic(ErrorCode.ERR_RetNoObjectRequired, \"return\").WithArguments(\"C.C()\"));\n }\n\n [Fact]\n public void CS0128ERR_LocalDuplicate()\n {\n var text = @\"\nnamespace MyNamespace\n{\n public class MyClass\n {\n public static void Main()\n {\n char i = 'a';\n int i = 2; // CS0128\n if (i == 2) {}\n }\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (9,14): error CS0128: A local variable or function named 'i' is already defined in this scope\n // int i = 2; // CS0128\n Diagnostic(ErrorCode.ERR_LocalDuplicate, \"i\").WithArguments(\"i\").WithLocation(9, 14),\n // (9,14): warning CS0219: The variable 'i' is assigned but its value is never used\n // int i = 2; // CS0128\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"i\").WithArguments(\"i\").WithLocation(9, 14)\n );\n }\n\n [Fact]\n public void CS0131ERR_AssgLvalueExpected01()\n {\n CreateCompilation(\n@\"class C\n{\n int i = 0;\n int P { get; set; }\n int this[int x] { get { return x; } set { } }\n void M()\n {\n ++P = 1; // CS0131\n ++i = 1; // CS0131\n ++this[0] = 1; //CS0131\n }\n}\n\")\n .VerifyDiagnostics(\n // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"++P\"),\n // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"++i\"),\n // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"++this[0]\"));\n }\n\n [Fact]\n public void CS0131ERR_AssgLvalueExpected02()\n {\n var source =\n@\"class C\n{\n const object NoObject = null;\n static void M()\n {\n const int i = 0;\n i += 1;\n 3 *= 1;\n (i + 1) -= 1;\n \"\"string\"\" = null;\n null = new object();\n NoObject = \"\"string\"\";\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // i += 1;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"i\").WithLocation(7, 9),\n // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // 3 *= 1;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"3\").WithLocation(8, 9),\n // (9,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // (i + 1) -= 1;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"i + 1\").WithLocation(9, 10),\n // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // \"string\" = null;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, @\"\"\"string\"\"\").WithLocation(10, 9),\n // (11,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // null = new object();\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"null\").WithLocation(11, 9),\n // (12,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // NoObject = \"string\";\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"NoObject\").WithLocation(12, 9));\n }\n\n /// \n /// Breaking change from Dev10. CS0131 is now reported for all value\n /// types, not just struct types. Specifically, CS0131 is now reported\n /// for type parameters constrained to \"struct\". (See also CS1612.)\n /// \n [WorkItem(528763, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528763\")]\n [Fact]\n public void CS0131ERR_AssgLvalueExpected03()\n {\n var source =\n@\"struct S\n{\n public object P { get; set; }\n public object this[object index] { get { return null; } set { } }\n}\ninterface I\n{\n object P { get; set; }\n object this[object index] { get; set; }\n}\nclass C\n{\n static void M()\n where T : struct, I\n {\n default(S).P = null;\n default(T).P = null; // Dev10: no error\n default(S)[0] = null;\n default(T)[0] = null; // Dev10: no error\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(S).P\").WithLocation(16, 9),\n // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T).P\").WithLocation(17, 9),\n // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(S)[0]\").WithLocation(18, 9),\n // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T)[0]\").WithLocation(19, 9));\n }\n\n [WorkItem(538077, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538077\")]\n [Fact]\n public void CS0132ERR_StaticConstParam()\n {\n var text = @\"\nclass A\n{\n static A(int z)\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Parameters = new string[] { \"A.A(int)\" } } });\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression01()\n {\n var source =\n@\"class MyClass\n{\n public const int a = b; //no error since b is declared const\n public const int b = c; //CS0133, c is not constant\n public static int c = 1; //change static to const to correct program\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,25): error CS0133: The expression being assigned to 'MyClass.b' must be constant\n // public const int b = c; //CS0133, c is not constant\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"c\").WithArguments(\"MyClass.b\").WithLocation(4, 25));\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression02()\n {\n var source =\n@\"enum E\n{\n X,\n Y = C.F(),\n Z = C.G() + 1,\n}\nclass C\n{\n public static E F()\n {\n return E.X;\n }\n public static int G()\n {\n return 0;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,9): error CS0266: Cannot implicitly convert type 'E' to 'int'. An explicit conversion exists (are you missing a cast?)\n // Y = C.F(),\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"C.F()\").WithArguments(\"E\", \"int\").WithLocation(4, 9),\n // (4,9): error CS0133: The expression being assigned to 'E.Y' must be constant\n // Y = C.F(),\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"C.F()\").WithArguments(\"E.Y\").WithLocation(4, 9),\n // (5,9): error CS0133: The expression being assigned to 'E.Z' must be constant\n // Z = C.G() + 1,\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"C.G() + 1\").WithArguments(\"E.Z\").WithLocation(5, 9));\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression03()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n int y = 1;\n const int x = 2 * y;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,23): error CS0133: The expression being assigned to 'x' must be constant\n // const int x = 2 * y;\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"2 * y\").WithArguments(\"x\").WithLocation(6, 23));\n }\n\n [Fact]\n public void CS0133ERR_NotConstantExpression04()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n const int x = x + x;\n }\n}\";\n CreateCompilationWithMscorlib45(source).VerifyDiagnostics(\n // (5,27): error CS0110: The evaluation of the constant value for 'x' involves a circular definition\n // const int x = x + x;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"x\").WithArguments(\"x\").WithLocation(5, 27),\n // (5,23): error CS0110: The evaluation of the constant value for 'x' involves a circular definition\n // const int x = x + x;\n Diagnostic(ErrorCode.ERR_CircConstValue, \"x\").WithArguments(\"x\").WithLocation(5, 23));\n }\n\n [Fact]\n public void CS0135ERR_NameIllegallyOverrides()\n {\n // See NameCollisionTests.cs for commentary on this error.\n\n var text = @\"\npublic class MyClass2\n{\n public static int i = 0;\n\n public static void Main()\n {\n {\n int i = 4; // CS0135: Roslyn reports this error here\n i++;\n }\n i = 0; // Native compiler reports the error here\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);\n }\n\n [Fact]\n public void CS0135ERR_NameIllegallyOverrides02()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\n\nclass Test\n{\n static int x;\n static void Main()\n {\n int z = x;\n var y = from x in Enumerable.Range(1, 100) // CS1931\n select x;\n }\n}\").VerifyDiagnostics(\n // (6,16): warning CS0649: Field 'Test.x' is never assigned to, and will always have its default value 0\n // static int x;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"x\").WithArguments(\"Test.x\", \"0\").WithLocation(6, 16)\n);\n }\n\n [Fact]\n public void CS0136ERR_LocalIllegallyOverrides01()\n {\n // See comments in NameCollisionTests for thoughts on this error.\n\n string text =\n@\"class C\n{\n static void M(object x)\n {\n string x = null; // CS0136\n string y = null;\n if (x != null)\n {\n int y = 0; // CS0136\n M(y);\n }\n M(x);\n M(y);\n }\n object P\n {\n get\n {\n int value = 0; // no error\n return value;\n }\n set\n {\n int value = 0; // CS0136\n M(value);\n }\n }\n static void N(int q)\n {\n System.Func f = q=>q; // 0136\n }\n}\";\n var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7_3);\n comp.VerifyDiagnostics(\n // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // string x = null; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"x\").WithArguments(\"x\").WithLocation(5, 16),\n // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int y = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"y\").WithArguments(\"y\").WithLocation(9, 17),\n // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int value = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"value\").WithArguments(\"value\").WithLocation(24, 17),\n // (30,35): error CS0136: A local or parameter named 'q' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // System.Func f = q=>q; // 0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"q\").WithArguments(\"q\").WithLocation(30, 35));\n\n comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // string x = null; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"x\").WithArguments(\"x\").WithLocation(5, 16),\n // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int y = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"y\").WithArguments(\"y\").WithLocation(9, 17),\n // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // int value = 0; // CS0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"value\").WithArguments(\"value\").WithLocation(24, 17));\n }\n\n [Fact]\n public void CS0136ERR_LocalIllegallyOverrides02()\n {\n // See comments in NameCollisionTests for commentary on this error.\n\n CreateCompilation(\n@\"class C\n{\n static void M(object o)\n {\n try\n {\n }\n catch (System.IO.IOException e) \n {\n M(e);\n }\n catch (System.Exception e) // Legal; the two 'e' variables are in non-overlapping declaration spaces\n {\n M(e);\n }\n try\n {\n }\n catch (System.Exception o) // CS0136: Illegal; the two 'o' variables are in overlapping declaration spaces.\n {\n M(o);\n }\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"o\").WithArguments(\"o\").WithLocation(19, 33));\n }\n\n [Fact]\n public void CS0136ERR_LocalIllegallyOverrides03()\n {\n // See comments in NameCollisionTests for commentary on this error.\n\n CreateCompilation(\n@\"class C\n{\n int field = 0;\n int property { get; set; }\n\n static public void Main()\n {\n int[] ints = new int[] { 1, 2, 3 };\n string[] strings = new string[] { \"\"1\"\", \"\"2\"\", \"\"3\"\" };\n int conflict = 1;\n System.Console.WriteLine(conflict);\n foreach (int field in ints) { } // Legal: local hides field but name is used consistently\n foreach (string property in strings) { } // Legal: local hides property but name is used consistently\n foreach (string conflict in strings) { } // 0136: local hides another local in an enclosing local declaration space.\n }\n}\n\")\n .VerifyDiagnostics(\n // (14,25): error CS0136: A local or parameter named 'conflict' cannot be declared in this \n // scope because that name is used in an enclosing local scope to define a local or parameter\n // foreach (string conflict in strings) { } // 0136\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"conflict\").WithArguments(\"conflict\").WithLocation(14, 25),\n // (3,9): warning CS0414: The field 'C.field' is assigned but its value is never used\n // int field = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"field\").WithArguments(\"C.field\"));\n }\n\n [WorkItem(538045, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538045\")]\n [Fact]\n public void CS0139ERR_NoBreakOrCont()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public static void Main(bool b)\n {\n if (b)\n continue; // CS0139\n else\n break; // CS0139\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 9, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 11, Column = 17 }});\n }\n\n [WorkItem(542400, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542400\")]\n [Fact]\n public void CS0140ERR_DuplicateLabel()\n {\n var text = @\"\nnamespace MyNamespace\n{\n public class MyClass\n {\n public static void Main()\n {\n label1: int i = M();\n label1: int j = M(); // CS0140, comment this line to resolve\n goto label1;\n }\n static int M() { return 0; }\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (9,10): error CS0140: The label 'label1' is a duplicate\n // label1: int j = M(); // CS0140, comment this line to resolve\n Diagnostic(ErrorCode.ERR_DuplicateLabel, \"label1\").WithArguments(\"label1\").WithLocation(9, 10)\n );\n }\n\n [WorkItem(542420, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420\")]\n [Fact]\n public void ErrorMeansSuccess_Attribute()\n {\n var text = @\"\nusing A;\nusing B;\nusing System;\n\nnamespace A\n{\n class var { }\n class XAttribute : Attribute { }\n}\nnamespace B\n{\n class var { }\n class XAttribute : Attribute { }\n class X : Attribute { }\n}\nclass Xyzzy\n{\n [X] // 17.2 If an attribute class is found both with and without this suffix, an ambiguity is present and a compile-time error occurs.\n public static void Main(string[] args)\n {\n }\n static int M() { return 0; }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics();\n }\n\n [WorkItem(542420, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420\")]\n [Fact]\n public void ErrorMeansSuccess_var()\n {\n var text = @\"\nusing A;\nusing B;\n\nnamespace A\n{\n class var { }\n}\nnamespace B\n{\n class var { }\n}\nclass Xyzzy\n{\n public static void Main(string[] args)\n {\n var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ...\n }\n static int M() { return 0; }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (21,9): error CS0104: 'var' is an ambiguous reference between 'A.var' and 'B.var'\n // var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ...\n Diagnostic(ErrorCode.ERR_AmbigContext, \"var\").WithArguments(\"var\", \"A.var\", \"B.var\")\n );\n }\n\n [Fact]\n public void CS0144ERR_NoNewAbstract()\n {\n var text = @\"\ninterface ii\n{\n}\n\nabstract class aa\n{\n}\n\npublic class a\n{\n public static void Main()\n {\n ii xx = new ii(); // CS0144\n ii yy = new ii(Error); // CS0144, CS0103\n aa zz = new aa(); // CS0144\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[]\n {\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 14, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 15, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 16, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 15, Column = 22 }\n });\n }\n\n [WorkItem(539583, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539583\")]\n [Fact]\n public void CS0150ERR_ConstantExpected()\n {\n var test = @\"\nclass C\n{\n static void Main()\n {\n byte x = 1;\n int[] a1 = new int[x];\n int[] a2 = new int[x] { 1 }; //CS0150\n\n const sbyte y = 1;\n const short z = 2;\n int[] b1 = new int[y + z];\n int[] b2 = new int[y + z] { 1, 2, 3 };\n }\n}\n\";\n CreateCompilation(test).VerifyDiagnostics(\n // (8,28): error CS0150: A constant value is expected\n Diagnostic(ErrorCode.ERR_ConstantExpected, \"x\"));\n }\n\n [Fact()]\n public void CS0151ERR_IntegralTypeValueExpected()\n {\n var text = @\"\npublic class iii\n{\n public static implicit operator int (iii aa)\n {\n return 0;\n }\n\n public static implicit operator long (iii aa)\n {\n return 0;\n }\n\n public static void Main()\n {\n iii a = new iii();\n\n switch (a) // CS0151, compiler cannot choose between int and long\n {\n case 1:\n break;\n }\n }\n}\";\n var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6);\n comp.VerifyDiagnostics(\n // (18,15): error CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier.\n // switch (a) // CS0151, compiler cannot choose between int and long\n Diagnostic(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, \"a\").WithLocation(18, 15),\n // (20,15): error CS0029: Cannot implicitly convert type 'int' to 'iii'\n // case 1:\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"1\").WithArguments(\"int\", \"iii\").WithLocation(20, 15)\n );\n }\n\n [Fact]\n public void CS0152ERR_DuplicateCaseLabel()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public static void Main()\n {\n int i = 0;\n\n switch (i)\n {\n case 1:\n i++;\n return;\n\n case 1: // CS0152, two case 1 statements\n i++;\n return;\n }\n }\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (16,13): error CS0152: The switch statement contains multiple cases with the label value '1'\n // case 1: // CS0152, two case 1 statements\n Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, \"case 1:\").WithArguments(\"1\").WithLocation(16, 13)\n );\n }\n\n [Fact]\n public void CS0153ERR_InvalidGotoCase()\n {\n var text = @\"\npublic class a\n{\n public static void Main()\n {\n goto case 5; // CS0153\n }\n}\";\n\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,7): error CS0153: A goto case is only valid inside a switch statement\n // goto case 5; // CS0153\n Diagnostic(ErrorCode.ERR_InvalidGotoCase, \"goto case 5;\").WithLocation(6, 7));\n }\n\n [Fact]\n public void CS0153ERR_InvalidGotoCase_2()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n string Fruit = \"\"Apple\"\";\n switch (Fruit)\n {\n case \"\"Banana\"\":\n break;\n default:\n break;\n }\n goto default;\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (14,9): error CS0153: A goto case is only valid inside a switch statement\n // goto default;\n Diagnostic(ErrorCode.ERR_InvalidGotoCase, \"goto default;\").WithLocation(14, 9));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet01()\n {\n CreateCompilation(\n@\"class C\n{\n static object P { set { } }\n static int Q { set { } }\n static void M(object o)\n {\n C.P = null;\n o = C.P; // CS0154\n M(P); // CS0154\n ++C.Q; // CS0154\n }\n}\n\")\n .VerifyDiagnostics(\n // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"C.P\").WithArguments(\"C.P\"),\n // (9,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\"),\n // (10,11): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"C.Q\").WithArguments(\"C.Q\"));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet02()\n {\n var source =\n@\"class A\n{\n public virtual A P { get; set; }\n public object Q { set { } }\n}\nclass B : A\n{\n public override A P { set { } }\n void M()\n {\n M(Q); // CS0154, no get method\n }\n static void M(B b)\n {\n object o = b.P; // no error\n o = b.Q; // CS0154, no get method\n b.P.Q = null; // no error\n o = b.P.Q; // CS0154, no get method\n }\n static void M(object o) { }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (11,11): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor\n // M(Q); // CS0154, no get method\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"A.Q\").WithLocation(11, 11),\n // (16,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor\n // o = b.Q; // CS0154, no get method\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"b.Q\").WithArguments(\"A.Q\").WithLocation(16, 13),\n // (18,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor\n // o = b.P.Q; // CS0154, no get method\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"b.P.Q\").WithArguments(\"A.Q\").WithLocation(18, 13));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet03()\n {\n var source =\n@\"class C\n{\n int P { set { } }\n void M()\n {\n P += 1;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,9): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n // P += 1;\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet04()\n {\n var source =\n@\"class C\n{\n object p;\n object P { set { p = P; } }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,26): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n // object P { set { p = P; } }\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(4, 26));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet05()\n {\n CreateCompilation(\n@\"class C\n{\n object P { set { } }\n static bool Q { set { } }\n void M()\n {\n object o = P as string;\n o = P ?? Q;\n o = (o != null) ? P : Q;\n o = !Q;\n }\n}\")\n .VerifyDiagnostics(\n // (7,20): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(7, 20),\n // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(8, 13),\n // (8,18): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"C.Q\").WithLocation(8, 18),\n // (9,27): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"P\").WithArguments(\"C.P\").WithLocation(9, 27),\n // (9,31): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"C.Q\").WithLocation(9, 31),\n // (10,14): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"Q\").WithArguments(\"C.Q\").WithLocation(10, 14));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet06()\n {\n CreateCompilation(\n@\"class C\n{\n int this[int x] { set { } }\n void M(int b)\n {\n b = this[0];\n b = 1 + this[1];\n M(this[2]);\n this[3]++;\n this[4] += 1;\n }\n}\")\n .VerifyDiagnostics(\n // (6,13): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[0]\").WithArguments(\"C.this[int]\"),\n // (7,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[1]\").WithArguments(\"C.this[int]\"),\n // (8,11): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[2]\").WithArguments(\"C.this[int]\"),\n // (9,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[3]\").WithArguments(\"C.this[int]\"),\n // (10,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"this[4]\").WithArguments(\"C.this[int]\"));\n }\n\n [Fact]\n public void CS0154ERR_PropertyLacksGet07()\n {\n var source1 =\n@\"public class A\n{\n public virtual object P { private get { return null; } set { } }\n}\npublic class B : A\n{\n public override object P { set { } }\n}\";\n var compilation1 = CreateCompilation(source1);\n compilation1.VerifyDiagnostics();\n var compilationVerifier = CompileAndVerify(compilation1);\n var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData);\n var source2 =\n@\"class C\n{\n static void M(B b)\n {\n var o = b.P;\n b.P = o;\n }\n}\";\n var compilation2 = CreateCompilation(source2, references: new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (5,17): error CS0154: The property or indexer 'B.P' cannot be used in this context because it lacks the get accessor\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"b.P\").WithArguments(\"B.P\").WithLocation(5, 17));\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType()\n {\n var text =\n@\"interface IA { }\ninterface IB : IA { }\nstruct S { }\nclass C\n{\n static void M()\n {\n try { }\n catch (object) { }\n catch (System.Exception) { }\n catch (System.DateTime) { }\n catch (System.Int32) { }\n catch (IA) { }\n catch (IB) { }\n catch (S) { }\n catch (S) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"object\").WithLocation(9, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"System.Exception\").WithArguments(\"object\").WithLocation(10, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"System.DateTime\").WithLocation(11, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"System.Int32\").WithLocation(12, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"IA\").WithLocation(13, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"IB\").WithLocation(14, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"S\").WithLocation(15, 16),\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"S\").WithLocation(16, 16));\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_Null()\n {\n var text = @\"class C\n{\n static readonly bool False = false;\n const string T = null;\n\n static void M(object o) \n {\n const string s = null;\n if (False) throw null;\n if (False) throw (string)null; //CS0155\n if (False) throw s; //CS0155\n if (False) throw T; //CS0155\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception'\n // if (False) throw (string)null; //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"(string)null\").WithArguments(\"string\", \"System.Exception\").WithLocation(10, 26),\n // (11,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception'\n // if (False) throw s; //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"s\").WithArguments(\"string\", \"System.Exception\").WithLocation(11, 26),\n // (12,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception'\n // if (False) throw T; //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"T\").WithArguments(\"string\", \"System.Exception\").WithLocation(12, 26)\n );\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_FailingAs()\n {\n var text = @\"\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n {\n if (False) throw new C() as D; //CS0155, though always null\n }\n}\n\nclass D : C { }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,26): error CS0029: Cannot implicitly convert type 'D' to 'System.Exception'\n // if (False) throw new C() as D; //CS0155, though always null\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"new C() as D\").WithArguments(\"D\", \"System.Exception\").WithLocation(8, 26)\n );\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_TypeParameters()\n {\n var text = @\"using System;\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n where TC : class\n where TS : struct\n where TE : Exception, new()\n {\n if (False) throw default(T); //CS0155\n if (False) throw default(TC); //CS0155\n if (False) throw default(TS); //CS0155\n if (False) throw default(TE);\n if (False) throw new TE();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,26): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception'\n // if (False) throw default(T); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"default(T)\").WithArguments(\"T\", \"System.Exception\").WithLocation(11, 26),\n // (12,26): error CS0029: Cannot implicitly convert type 'TC' to 'System.Exception'\n // if (False) throw default(TC); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"default(TC)\").WithArguments(\"TC\", \"System.Exception\").WithLocation(12, 26),\n // (13,26): error CS0029: Cannot implicitly convert type 'TS' to 'System.Exception'\n // if (False) throw default(TS); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"default(TS)\").WithArguments(\"TS\", \"System.Exception\").WithLocation(13, 26)\n );\n }\n\n [Fact()]\n public void CS0155ERR_BadExceptionType_UserDefinedConversions()\n {\n var text = @\"using System;\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n {\n if (False) throw new Implicit(); //CS0155\n if (False) throw new Explicit(); //CS0155\n if (False) throw (Exception)new Implicit();\n if (False) throw (Exception)new Explicit();\n }\n}\n\nclass Implicit\n{\n public static implicit operator Exception(Implicit i)\n {\n return null;\n }\n}\n\nclass Explicit\n{\n public static explicit operator Exception(Explicit i)\n {\n return null;\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"new Implicit()\"),\n // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"new Explicit()\")\n );\n CreateCompilation(text).VerifyDiagnostics(\n // (9,26): error CS0266: Cannot implicitly convert type 'Explicit' to 'System.Exception'. An explicit conversion exists (are you missing a cast?)\n // if (False) throw new Explicit(); //CS0155\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"new Explicit()\").WithArguments(\"Explicit\", \"System.Exception\").WithLocation(9, 26)\n );\n }\n\n [Fact]\n public void CS0155ERR_BadExceptionType_Dynamic()\n {\n var text = @\"\nclass C\n{\n static readonly bool False = false;\n\n static void M(object o) \n {\n dynamic d = null;\n if (False) throw d; //CS0155\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (9,26): error CS0155: The type caught or thrown must be derived from System.Exception\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"d\"));\n CreateCompilation(text).VerifyDiagnostics(); // dynamic conversion to Exception\n }\n\n [WorkItem(542995, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542995\")]\n [Fact]\n public void CS0155ERR_BadExceptionType_Struct()\n {\n var text = @\"\npublic class Test\n{\n public static void Main(string[] args)\n {\n }\n private void Method()\n {\n try\n {\n }\n catch (s1 s)\n {\n }\n }\n}\nstruct s1\n{ }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,16): error CS0155: The type caught or thrown must be derived from System.Exception\n // catch (s1 s)\n Diagnostic(ErrorCode.ERR_BadExceptionType, \"s1\"),\n // (12,19): warning CS0168: The variable 's' is declared but never used\n // catch (s1 s)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"s\").WithArguments(\"s\")\n );\n }\n\n [Fact]\n public void CS0156ERR_BadEmptyThrow()\n {\n var text = @\"\nusing System;\n\nnamespace x\n{\n public class b : Exception\n {\n }\n\n public class a\n {\n public static void Main()\n {\n try\n {\n throw; // CS0156\n }\n\n catch(b)\n {\n throw; // this throw is valid\n }\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEmptyThrow, Line = 16, Column = 13 } });\n }\n\n [Fact]\n public void CS0156ERR_BadEmptyThrow_Nesting()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n bool b = System.DateTime.Now.Second > 1; //avoid unreachable code\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n }\n catch\n {\n if (b) throw; //fine\n try\n {\n if (b) throw; //fine\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0724\n\n try\n {\n if (b) throw; //CS0724\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0724\n }\n }\n }\n finally\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (9,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (12,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (20,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (41,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (44,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (52,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"));\n }\n\n [Fact]\n public void CS0156ERR_BadEmptyThrow_Lambdas()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n bool b = System.DateTime.Now.Second > 1; // avoid unreachable code\n System.Action a;\n a = () => { throw; }; //CS0156\n try\n {\n a = () =>\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n };\n }\n catch\n {\n a = () =>\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n };\n }\n finally\n {\n a = () =>\n {\n if (b) throw; //CS0156\n try\n {\n if (b) throw; //CS0156\n }\n catch\n {\n if (b) throw; //fine\n }\n finally\n {\n if (b) throw; //CS0156\n }\n };\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,21): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (13,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (16,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (24,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (32,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (35,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (43,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (51,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (54,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"),\n // (62,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrow, \"throw\"));\n }\n\n [WorkItem(540817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817\")]\n [Fact]\n public void CS0157ERR_BadFinallyLeave01()\n {\n var text =\n@\"class C\n{\n static int F;\n static void M()\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n Before:\n ;\n try\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n else if (F == 2)\n goto TryBlock;\n else if (F == 3)\n return;\n TryBlock:\n ;\n }\n catch (System.Exception)\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n else if (F == 2)\n goto CatchBlock;\n else if (F == 3)\n return;\n CatchBlock:\n ;\n }\n finally\n {\n if (F == 0)\n goto Before;\n else if (F == 1)\n goto After;\n else if (F == 2)\n goto FinallyBlock;\n else if (F == 3)\n return;\n FinallyBlock:\n ;\n }\n After:\n ;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (41,17): error CS0157: Control cannot leave the body of a finally clause\n // goto Before;\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"goto\"),\n // (43,17): error CS0157: Control cannot leave the body of a finally clause\n // goto After;\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"goto\"),\n // (47,17): error CS0157: Control cannot leave the body of a finally clause\n // return;\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"return\"),\n // (3,16): warning CS0649: Field 'C.F' is never assigned to, and will always have its default value 0\n // static int F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"C.F\", \"0\")\n );\n }\n\n [WorkItem(540817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817\")]\n [Fact]\n public void CS0157ERR_BadFinallyLeave02()\n {\n var text =\n@\"using System;\nclass C\n{\n static void F(int i)\n {\n }\n static void M()\n {\n for (int i = 0; i < 10;)\n {\n if (i < 5)\n {\n try { F(i); }\n catch (Exception) { continue; }\n finally { break; }\n }\n else\n {\n try { F(i); }\n catch (Exception) { break; }\n finally { continue; }\n }\n }\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"break\").WithLocation(15, 27),\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"continue\").WithLocation(21, 27));\n }\n\n [WorkItem(540817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817\")]\n [Fact]\n public void CS0157ERR_BadFinallyLeave03()\n {\n var text = @\"\nclass C\n{\n static void Main(string[] args)\n {\n int i = 0;\n try { i = 1; }\n catch { i = 2; }\n finally { i = 3; goto lab1; }// invalid\n lab1:\n return;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (9,26): error CS0157: Control cannot leave the body of a finally clause\n // finally { i = 3; goto lab1; }// invalid\n Diagnostic(ErrorCode.ERR_BadFinallyLeave, \"goto\"),\n // (6,13): warning CS0219: The variable 'i' is assigned but its value is never used\n // int i = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"i\").WithArguments(\"i\")\n );\n }\n\n [WorkItem(539890, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890\")]\n [Fact]\n public void CS0158ERR_LabelShadow()\n {\n var text = @\"\nnamespace MyNamespace\n{\n public class MyClass\n {\n public static void Main()\n {\n goto lab1;\n lab1:\n {\n lab1:\n goto lab1; // CS0158\n }\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelShadow, Line = 11, Column = 13 } });\n }\n\n [WorkItem(539890, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890\")]\n [Fact]\n public void CS0158ERR_LabelShadow_02()\n {\n var text = @\"\ndelegate int del(int i);\nclass C\n{\n static void Main(string[] args)\n {\n del p = x =>\n {\n goto label1;\n label1: // invalid\n return x * x;\n };\n label1:\n return;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (10,9): error CS0158: The label 'label1' shadows another label by the same name in a contained scope\n // label1: // invalid\n Diagnostic(ErrorCode.ERR_LabelShadow, \"label1\").WithArguments(\"label1\"),\n // (13,5): warning CS0164: This label has not been referenced\n // label1:\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label1\")\n );\n }\n\n [WorkItem(539875, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539875\")]\n [Fact]\n public void CS0159ERR_LabelNotFound()\n {\n var text = @\"\npublic class Cls\n{\n public static void Main()\n {\n goto Label2;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelNotFound, Line = 6, Column = 14 }\n });\n }\n\n [WorkItem(528799, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528799\")]\n [Fact()]\n public void CS0159ERR_LabelNotFound_2()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int s = 23;\n switch (s)\n {\n case 21:\n break;\n case 23:\n goto default;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,17): error CS0159: No such label 'default:' within the scope of the goto statement\n // goto default;\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"goto default;\").WithArguments(\"default:\"),\n // (11,13): error CS8070: Control cannot fall out of switch from final case label ('case 23:')\n // case 23:\n Diagnostic(ErrorCode.ERR_SwitchFallOut, \"case 23:\").WithArguments(\"case 23:\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_3()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n goto Label;\n }\n public static void Goo()\n {\n Label:\n ;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label\").WithArguments(\"Label\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_4()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n for (int i = 0; i < 10; i++)\n {\n Label:\n i++;\n }\n goto Label;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label\").WithArguments(\"Label\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_5()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n if (true)\n {\n Label1:\n goto Label2;\n }\n else\n {\n Label2:\n goto Label1;\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label2\").WithArguments(\"Label2\"),\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"Label1\").WithArguments(\"Label1\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"Label2\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label1\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"Label2\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_6()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n { goto L; }\n { L: return; }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"L\").WithArguments(\"L\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"L\"));\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_7()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n int i = 3;\n if (true)\n {\n label1:\n goto label3;\n if (!false)\n {\n label2:\n goto label5;\n if (i > 2)\n {\n label3:\n goto label2;\n if (i == 3)\n {\n label4:\n if (i < 5)\n {\n label5:\n if (i == 4)\n {\n }\n else\n {\n System.Console.WriteLine(\"\"a\"\");\n }\n }\n }\n }\n }\n }\n }\n}\n\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"label3\").WithArguments(\"label3\"),\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"label5\").WithArguments(\"label5\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"if\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"label4\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"label5\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label1\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label3\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label4\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label5\"));\n }\n\n [WorkItem(540818, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540818\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_8()\n {\n var text = @\"\ndelegate int del(int i);\nclass C\n{\n static void Main(string[] args)\n {\n del q = x =>\n {\n goto label2; // invalid\n return x * x;\n };\n label2:\n return;\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (10,17): warning CS0162: Unreachable code detected\n // return x * x;\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"),\n // (9,17): error CS0159: No such label 'label2' within the scope of the goto statement\n // goto label2; // invalid\n Diagnostic(ErrorCode.ERR_LabelNotFound, \"goto\").WithArguments(\"label2\"),\n // (12,5): warning CS0164: This label has not been referenced\n // label2:\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"label2\")\n );\n }\n\n [WorkItem(539876, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876\")]\n [Fact]\n public void CS0159ERR_LabelNotFound_9()\n {\n var text = @\"\npublic class Test\n{\n static public void Main(string[] args)\n {\n string[] S = new string[] { \"\"ABC\"\", \"\"XYZ\"\" };\n foreach (string x in S)\n {\n goto innerLoop;\n foreach (char y in x)\n {\n innerLoop:\n return;\n }\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, \"innerLoop\").WithArguments(\"innerLoop\"),\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"innerLoop\"));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch()\n {\n var text =\n@\"using System;\nusing System.IO;\nclass A : Exception { }\nclass B : A { }\nclass C : IOException { }\ninterface I { }\nclass D : Exception, I { }\nclass E : IOException, I { }\nclass F : Exception { }\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) { }\n catch (D) { }\n catch (E) { }\n catch (IOException) { }\n catch (C) { }\n catch (F) { }\n catch (F) { }\n catch (Exception) { }\n catch (B) { }\n catch (StackOverflowException) { }\n catch (F) { }\n catch (F) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"C\").WithArguments(\"System.IO.IOException\").WithLocation(19, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"B\").WithArguments(\"A\").WithLocation(23, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"StackOverflowException\").WithArguments(\"System.Exception\").WithLocation(24, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"F\").WithArguments(\"F\").WithLocation(25, 16),\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"F\").WithArguments(\"System.Exception\").WithLocation(26, 16));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_Filter1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n int a = 1;\n try { }\n catch when (a == 1) { }\n catch (Exception e) when (e.Message == null) { }\n catch (A) { }\n catch (B e) when (e.Message == null) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('A')\n // catch (B e) when (e.Message == null) { }\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"B\").WithArguments(\"A\").WithLocation(15, 16));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse_NonBoolean()\n {\n // Non-boolean constant filters are not considered for WRN_FilterIsConstant warnings. \n\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (1) { }\n catch (B) when (0) { }\n catch (B) when (\"\"false\"\") { }\n catch (B) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): error CS0029: Cannot implicitly convert type 'int' to 'bool'\n // catch (A) when (1) { }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"1\").WithArguments(\"int\", \"bool\").WithLocation(11, 25),\n // (12,25): error CS0029: Cannot implicitly convert type 'int' to 'bool'\n // catch (B) when (0) { }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"0\").WithArguments(\"int\", \"bool\").WithLocation(12, 25),\n // (13,25): error CS0029: Cannot implicitly convert type 'string' to 'bool'\n // catch (B) when (\"false\") { }\n Diagnostic(ErrorCode.ERR_NoImplicitConv, @\"\"\"false\"\"\").WithArguments(\"string\", \"bool\").WithLocation(13, 25),\n // (14,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (B) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(14, 25));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) { }\n catch (B) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(11, 25),\n // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (B) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(12, 25));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse2()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when ((1+1)!=2) { }\n catch (B) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"(1+1)!=2\").WithLocation(11, 25),\n // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (B) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(12, 25));\n }\n\n [Fact]\n public void CS8359WRN_FilterIsConstantFalse3()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) { }\n finally { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(10, 25));\n }\n\n [Fact]\n public void CS8360WRN_FilterIsConstantRedundantTryCatch1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, \"false\").WithLocation(10, 25));\n }\n\n [Fact]\n public void CS8360WRN_FilterIsConstantRedundantTryCatch2()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when ((1+1)!=2) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block\n // catch (A) when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, \"(1+1)!=2\").WithLocation(10, 25));\n }\n\n [Fact]\n public void CS7095WRN_FilterIsConstantTrue1()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (true) { }\n catch (B) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch (A) when (true) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"true\").WithLocation(11, 25));\n }\n\n [Fact]\n public void CS7095WRN_FilterIsConstantTrue2()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch when (true) { }\n catch (A) { }\n catch when (false) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch when (true) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"true\").WithLocation(10, 21),\n // (12,19): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch when (false) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(12, 21));\n }\n\n [Fact]\n public void CS7095WRN_FilterIsConstantTrue3()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch when ((1+1)==2) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch when (true) { }\n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"(1+1)==2\").WithLocation(10, 21));\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode_Filter_ConstantCondition()\n {\n var text = @\"\nusing System;\nclass A : Exception { }\nclass B : A { }\n\nclass Program\n{\n static void M()\n {\n try { }\n catch (A) when (false) \n {\n Console.WriteLine(1); \n }\n catch (B) { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause\n // catch (A) when (false) \n Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, \"false\").WithLocation(11, 25),\n // (13,13): warning CS0162: Unreachable code detected\n // Console.WriteLine(1); \n Diagnostic(ErrorCode.WRN_UnreachableCode, \"Console\").WithLocation(13, 13)\n );\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode_Filter_ConstantCondition2()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n static void M()\n {\n int x;\n try { }\n catch (Exception) when (false) \n {\n Console.WriteLine(x);\n }\n }\n}\n\";\n // Unlike an unreachable code in if statement block we don't allow using\n // a variable that's not definitely assigned. The reason why we allow it in an if statement\n // is to make conditional compilation easier. Such scenario doesn't apply to filters.\n\n CreateCompilation(text).VerifyDiagnostics(\n // (10,33): warning CS7105: Filter expression is a constant 'false', consider removing the try-catch block\n // catch (Exception) when (false) \n Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, \"false\").WithLocation(10, 33),\n // (12,13): warning CS0162: Unreachable code detected\n // Console.WriteLine(x);\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"Console\").WithLocation(12, 13)\n );\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode_Filter_ConstantCondition3()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n static void M()\n {\n int x;\n try { }\n catch (Exception) when (true) \n {\n Console.WriteLine(x);\n }\n }\n}\n\";\n // Unlike an unreachable code in if statement block we don't allow using\n // a variable that's not definitely assigned. The reason why we allow it in an if statement\n // is to make conditional compilation easier. Such scenario doesn't apply to filters.\n\n CreateCompilation(text).VerifyDiagnostics(\n // (10,33): warning CS7095: Filter expression is a constant 'true', consider removing the filter\n // catch (Exception) when (true) \n Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, \"true\").WithLocation(10, 33),\n // (12,31): error CS0165: Use of unassigned local variable 'x'\n // Console.WriteLine(x);\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(12, 31)\n );\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_Dynamic()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic class A\n{\n public void M1()\n {\n try\n {\n Goo();\n }\n catch (EG)\n {\n }\n catch (EG)\n {\n }\n }\n\n void Goo() { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"EG\").WithArguments(\"EG\"));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_TypeParameter()\n {\n string source = @\"\nusing System;\n\npublic class EA : Exception { }\npublic class EB : EA { }\n\npublic class A where T : EB\n{\n public void M1()\n {\n try\n {\n Goo();\n }\n catch (EA)\n {\n }\n catch (T)\n {\n }\n }\n\n void Goo() { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (18,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EA')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"T\").WithArguments(\"EA\"));\n }\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic1()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic abstract class A\n{\n public abstract void M() where U : T;\n}\n\npublic class B : A> where V : EG\n{\n public override void M()\n {\n try\n {\n Goo();\n }\n catch (EG)\n {\n }\n catch (V)\n {\n }\n catch (U)\n {\n }\n }\n\n void Goo() { } \n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"V\").WithArguments(\"EG\"),\n // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"U\").WithArguments(\"EG\"));\n }\n\n [Fact]\n public void TypeParameter_DynamicConversions()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic abstract class A\n{\n public abstract void M() where U : T;\n}\n\npublic class B : A> where V : EG\n{\n public override void M()\n {\n V v = default(V);\n U u = default(U);\n\n // implicit\n EG egd = v;\n // implicit\n egd = u;\n\n //explicit\n v = (V)egd;\n //explicit\n u = (U)egd;\n\n //implicit array\n V[] va = null; \n EG[] egda = va;\n\n // explicit array\n va = (V[])egda; \n }\n\n void Goo() { } \n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();\n }\n\n\n [Fact]\n public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic2()\n {\n string source = @\"\nusing System;\n\npublic class EG : Exception { }\n\npublic abstract class A\n{\n public abstract void M() where U : T;\n}\n\npublic class B : A> where V : EG\n{\n public override void M()\n {\n try\n {\n Goo();\n }\n catch (EG)\n {\n }\n catch (V)\n {\n }\n catch (U)\n {\n }\n }\n\n void Goo() { } \n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"V\").WithArguments(\"EG\"),\n // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG')\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"U\").WithArguments(\"EG\"));\n }\n\n [Fact]\n public void CS0161ERR_ReturnExpected()\n {\n var text = @\"\npublic class Test\n{\n public static int Main() // CS0161\n {\n int i = 10;\n if (i < 10)\n {\n return i;\n }\n else\n {\n // uncomment the following line to resolve\n // return 1;\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnExpected, Line = 4, Column = 22 } });\n }\n\n [Fact]\n public void CS0163ERR_SwitchFallThrough()\n {\n var text = @\"\npublic class MyClass\n{\n public static void Main()\n {\n int i = 0;\n\n switch (i) // CS0163\n {\n case 1:\n i++;\n // uncomment one of the following lines to resolve\n // return;\n // break;\n // goto case 3;\n\n case 2:\n i++;\n return;\n\n case 3:\n i = 0;\n return;\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SwitchFallThrough, Line = 10, Column = 10 } });\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation01()\n {\n var text = @\"\nclass MyClass\n{\n public int i;\n}\n\nclass MyClass2\n{\n public static void Main(string [] args)\n {\n int i, j;\n if (args[0] == \"\"test\"\")\n {\n i = 0;\n }\n\n /*\n // to resolve, either initialize the variables when declared\n // or provide for logic to initialize them, as follows:\n else\n {\n i = 1;\n }\n */\n\n j = i; // CS0165, i might be uninitialized\n\n MyClass myClass;\n myClass.i = 0; // CS0165\n // use new as follows\n // MyClass myClass = new MyClass();\n // myClass.i = 0;\n i = j;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 26, Column = 11 } ,\n new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 29, Column = 7 }});\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation02()\n {\n CreateCompilation(\n@\"class C\n{\n static void M(int m)\n {\n int v;\n for (int i = 0; i < m; ++i)\n {\n v = 0;\n }\n M(v);\n int w;\n for (; ; )\n {\n w = 0;\n break;\n }\n M(w);\n for (int x; x < 1; ++x)\n {\n }\n for (int y; m < 1; ++y)\n {\n }\n for (int z; ; )\n {\n M(z);\n }\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"v\").WithArguments(\"v\").WithLocation(10, 11),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(18, 21),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(21, 30),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"z\").WithArguments(\"z\").WithLocation(26, 15));\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation03()\n {\n CreateCompilation(\n@\"class C\n{\n static int F()\n {\n return 0;\n }\n static void M0()\n {\n int a, b, c, d;\n for (a = 1; (b = F()) < 2; c = 3) { d = 4; }\n if (a == 0) { }\n if (b == 0) { }\n if (c == 0) { } // Use of unassigned 'c'\n if (d == 0) { } // Use of unassigned 'd'\n }\n static void M1()\n {\n int x, y;\n for (x = 0; (y = x) < 10; ) { }\n if (y == 0) { } // no error\n }\n static void M2()\n {\n int x, y;\n for (x = 0; x < 10; y = x) { }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M3()\n {\n int x, y;\n for (x = 0; x < 10; ) { y = x; }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M4()\n {\n int x, y;\n for (y = x; (x = 0) < 10; ) { } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M5()\n {\n int x, y;\n for (; (x = 0) < 10; y = x) { }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M6()\n {\n int x, y;\n for (; (x = 0) < 10; ) { y = x; }\n if (y == 0) { } // Use of unassigned 'y'\n }\n static void M7()\n {\n int x, y;\n for (y = x; F() < 10; x = 0) { } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M8()\n {\n int x, y;\n for (; (y = x) < 10; x = 0) { } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M9()\n {\n int x, y;\n for (; F() < 10; x = 0) { y = x; } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M10()\n {\n int x, y;\n for (y = x; F() < 10; ) { x = 0; } // Use of unassigned 'x'\n if (y == 0) { } // no error\n }\n static void M11()\n {\n int x, y;\n for (; F() < 10; y = x) { x = 0; }\n if (y == 0) { } // Use of unassigned 'y'\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"c\").WithArguments(\"c\").WithLocation(13, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"d\").WithArguments(\"d\").WithLocation(14, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(26, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(32, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(37, 18),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(44, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(50, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(55, 18),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(61, 21),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(67, 39),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(68, 13),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\").WithLocation(73, 18),\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(80, 13));\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation04()\n {\n CreateCompilation(\n@\"class C\n{\n static int M()\n {\n int x, y, z;\n try\n {\n x = 0;\n y = 1;\n }\n catch (System.Exception)\n {\n x = 1;\n }\n finally\n {\n z = 1;\n }\n return (x + y + z);\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"y\").WithArguments(\"y\").WithLocation(19, 21));\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation05()\n {\n // This is a \"negative\" test case; we should *not* be producing a \"use of unassigned\n // local variable\" error here. In an earlier revision we were doing so because we were\n // losing the information about the first argument being \"out\" when the bad call node\n // was created. Later flow analysis then did not know that \"x\" need not be assigned\n // before it was used, and we'd produce a wrong error.\n CreateCompilation(\n@\"class C\n{\n static int N(out int q) { q = 1; return 2;}\n static void M()\n {\n int x = N(out x, 123);\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_BadArgCount, \"N\").WithArguments(\"N\", \"2\"));\n }\n\n [WorkItem(540860, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540860\")]\n [Fact]\n public void CS0165ERR_UseDefViolation06()\n {\n // Should not generate \"unassigned local variable\" for struct.\n CreateCompilation(\n@\"struct S\n{\n public void M() { }\n}\nclass C\n{\n void M()\n {\n S s;\n s.M();\n }\n}\")\n .VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0165ERR_UseDefViolation07()\n {\n // Make sure flow analysis is hooked up for indexers\n CreateCompilation(\n@\"struct S\n{\n public int this[int x] { get { return 0; } }\n}\nclass C\n{\n public int this[int x] { get { return 0; } }\n}\nclass Test\n{\n static void Main()\n {\n int unassigned1;\n int unassigned2;\n int sink;\n\n C c;\n sink = c[1]; //CS0165\n\n c = new C();\n sink = c[1]; //fine\n sink = c[unassigned1]; //CS0165\n\n S s;\n sink = s[1]; //fine - struct with no fields\n\n s = new S();\n sink = s[1]; //fine\n sink = s[unassigned2]; //CS0165\n }\n}\")\n .VerifyDiagnostics(\n // (18,16): error CS0165: Use of unassigned local variable 'c'\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"c\").WithArguments(\"c\"),\n // (22,18): error CS0165: Use of unassigned local variable 'unassigned1'\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"unassigned1\").WithArguments(\"unassigned1\"),\n // (29,18): error CS0165: Use of unassigned local variable 'unassigned2'\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"unassigned2\").WithArguments(\"unassigned2\"));\n }\n\n [WorkItem(3402, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0170ERR_UseDefViolationField()\n {\n var text = @\"\npublic struct error\n{\n public int i;\n}\n\npublic class MyClass\n{\n public static void Main()\n {\n error e;\n // uncomment the next line to resolve this error\n // e.i = 0;\n System.Console.WriteLine( e.i ); // CS0170 because \n //e.i was never assigned\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationField, Line = 14, Column = 33 } });\n }\n\n [Fact]\n public void CS0171ERR_UnassignedThis()\n {\n var text = @\"\nstruct MyStruct\n{\n MyStruct(int initField) // CS0171\n {\n // i = initField; // uncomment this line to resolve this error\n }\n public int i;\n}\n\nclass MyClass\n{\n public static void Main()\n {\n MyStruct aStruct = new MyStruct();\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (4,4): error CS0171: Field 'MyStruct.i' must be fully assigned before control is returned to the caller\n // MyStruct(int initField) // CS0171\n Diagnostic(ErrorCode.ERR_UnassignedThis, \"MyStruct\").WithArguments(\"MyStruct.i\"),\n // (15,16): warning CS0219: The variable 'aStruct' is assigned but its value is never used\n // MyStruct aStruct = new MyStruct();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"aStruct\").WithArguments(\"aStruct\"),\n // (8,15): warning CS0649: Field 'MyStruct.i' is never assigned to, and will always have its default value 0\n // public int i;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"i\").WithArguments(\"MyStruct.i\", \"0\")\n );\n }\n\n [Fact]\n public void FieldAssignedInReferencedConstructor()\n {\n var text =\n@\"struct S\n{\n private readonly object _x;\n S(object o)\n {\n _x = o;\n }\n S(object x, object y) : this(x ?? y)\n {\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(); // No CS0171 for S._x\n }\n\n [Fact()]\n public void CS0172ERR_AmbigQM()\n {\n var text = @\"\npublic class Square\n{\n public class Circle\n {\n public static implicit operator Circle(Square aa)\n {\n return null;\n }\n\n public static implicit operator Square(Circle aa)\n {\n return null;\n }\n }\n\n public static void Main()\n {\n Circle aa = new Circle();\n Square ii = new Square();\n var o1 = (1 == 1) ? aa : ii; // CS0172\n object o2 = (1 == 1) ? aa : ii; // CS8652\n }\n}\";\n CreateCompilation(text, parseOptions: TestOptions.Regular8).VerifyDiagnostics(\n // (21,16): error CS0172: Type of conditional expression cannot be determined because 'Square.Circle' and 'Square' implicitly convert to one another\n // var o1 = (1 == 1) ? aa : ii; // CS0172\n Diagnostic(ErrorCode.ERR_AmbigQM, \"(1 == 1) ? aa : ii\").WithArguments(\"Square.Circle\", \"Square\").WithLocation(21, 16),\n // (22,19): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between 'Square.Circle' and 'Square'. To use a target-typed conversion, upgrade to language version 9.0 or greater.\n // object o2 = (1 == 1) ? aa : ii; // CS8652\n Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, \"(1 == 1) ? aa : ii\").WithArguments(\"8.0\", \"Square.Circle\", \"Square\", \"9.0\").WithLocation(22, 19)\n );\n }\n\n [Fact]\n public void CS0173ERR_InvalidQM()\n {\n var text = @\"\npublic class C {}\npublic class A {}\n\npublic class MyClass\n{\n public static void F(bool b)\n {\n A a = new A();\n C c = new C();\n var o = b ? a : c; // CS0173\n }\n\n public static void Main()\n {\n F(true);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,15): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C'\n // var o = b ? a : c; // CS0173\n Diagnostic(ErrorCode.ERR_InvalidQM, \"b ? a : c\").WithArguments(\"A\", \"C\").WithLocation(11, 15)\n );\n }\n\n [WorkItem(528331, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528331\")]\n [Fact]\n public void CS0173ERR_InvalidQM_FuncCall()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n var s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1);\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1)\").WithArguments(\"void\").WithLocation(6, 13));\n }\n\n [Fact]\n public void CS0173ERR_InvalidQM_GeneralType()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n A a = new A();\n A b = new A();\n var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert\n }\n}\nclass A\n{\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'A'\n // var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert\n Diagnostic(ErrorCode.ERR_InvalidQM, \"1 > 2 ? a : b\").WithArguments(\"A\", \"A\").WithLocation(8, 17)\n );\n }\n\n [WorkItem(540902, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540902\")]\n [Fact]\n public void CS0173ERR_InvalidQM_foreach()\n {\n var text = @\"\npublic class Test\n{\n public static void Main()\n {\n S[] x = null;\n foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY\n { }\n C[] y= null;\n foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY\n { }\n }\n}\nstruct S { }\nclass C { }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'S[]' and 'int'\n // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY\n Diagnostic(ErrorCode.ERR_InvalidQM, \"true ? x : 1\").WithArguments(\"S[]\", \"int\"),\n // (7,20): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"x\").WithArguments(\"x\"),\n // (11,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'C[]'\n // foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY\n Diagnostic(ErrorCode.ERR_InvalidQM, \"false ? 1 : y\").WithArguments(\"int\", \"C[]\")\n );\n }\n\n // /// Scenarios? \n // [Fact]\n // public void CS0174ERR_NoBaseClass()\n // {\n // var text = @\"\n // \";\n // CreateCompilationWithMscorlib(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoBaseClass, \"?\"));\n // }\n\n [WorkItem(543360, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543360\")]\n [Fact()]\n public void CS0175ERR_BaseIllegal()\n {\n var text = @\"\nusing System;\nclass Base\n{\n public int TestInt = 0;\n}\n\nclass MyClass : Base\n{\n public void BaseTest()\n {\n Console.WriteLine(base); // CS0175\n base = 9; // CS0175\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,27): error CS0175: Use of keyword 'base' is not valid in this context\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\").WithLocation(12, 27),\n // (12,9): error CS0175: Use of keyword 'base' is not valid in this context\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\").WithLocation(13, 9)\n );\n }\n\n [WorkItem(528624, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528624\")]\n [Fact()]\n public void CS0175ERR_BaseIllegal_02()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nclass MyClass : List\n{\n public void BaseTest()\n {\n var x = from i in base select i;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,27): error CS0175: Use of keyword 'base' is not valid in this context\n // var x = from i in base select i;\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\")\n );\n }\n\n [Fact]\n public void CS0176ERR_ObjectProhibited01()\n {\n var source = @\"\nclass A\n{\n class B\n {\n static void Method() { }\n void M()\n {\n this.Method();\n }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,13): error CS0176: Member 'A.B.Method()' cannot be accessed with an instance reference; qualify it with a type name instead\n // this.Method();\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"this.Method\").WithArguments(\"A.B.Method()\").WithLocation(9, 13)\n );\n }\n\n [Fact]\n public void CS0176ERR_ObjectProhibited02()\n {\n var source = @\"\nclass C\n{\n static object field;\n static object Property { get; set; }\n void M(C c)\n {\n Property = field; // no error\n C.Property = C.field; // no error\n this.field = this.Property;\n c.Property = c.field;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,9): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead\n // this.field = this.Property;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"this.field\").WithArguments(\"C.field\"),\n // (9,22): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead\n // this.field = this.Property;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"this.Property\").WithArguments(\"C.Property\"),\n // (10,9): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead\n // c.Property = c.field;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"c.Property\").WithArguments(\"C.Property\"),\n // (10,22): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead\n // c.Property = c.field;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"c.field\").WithArguments(\"C.field\")\n );\n }\n\n [Fact]\n public void CS0176ERR_ObjectProhibited03()\n {\n var source =\n@\"class A\n{\n internal static object F;\n}\nclass B where T : A\n{\n static void M(T t)\n {\n object q = t.F;\n t.ReferenceEquals(q, null);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,20): error CS0176: Member 'A.F' cannot be accessed with an instance reference; qualify it with a type name instead\n // object q = t.F;\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"t.F\").WithArguments(\"A.F\").WithLocation(9, 20),\n // (10,9): error CS0176: Member 'object.ReferenceEquals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead\n // t.ReferenceEquals(q, null);\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"t.ReferenceEquals\").WithArguments(\"object.ReferenceEquals(object, object)\").WithLocation(10, 9),\n // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null\n // internal static object F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"A.F\", \"null\").WithLocation(3, 28));\n }\n\n [WorkItem(543361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361\")]\n [Fact]\n public void CS0176ERR_ObjectProhibited04()\n {\n var source = @\"\npublic delegate void D();\nclass Test\n{\n public event D D;\n\n public void TestIdenticalEventName()\n {\n D.CreateDelegate(null, null, null); // CS0176\n }\n}\n\";\n CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics(\n // (9,9): error CS0176: Member 'Delegate.CreateDelegate(Type, object, string)' cannot be accessed with an instance reference; qualify it with a type name instead\n // D.CreateDelegate(null, null, null); // CS0176\n Diagnostic(ErrorCode.ERR_ObjectProhibited, \"D.CreateDelegate\").WithArguments(\"System.Delegate.CreateDelegate(System.Type, object, string)\").WithLocation(9, 9)\n );\n }\n\n // Identical to CS0176ERR_ObjectProhibited04, but with event keyword removed (i.e. field instead of field-like event).\n [WorkItem(543361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361\")]\n [Fact]\n public void CS0176ERR_ObjectProhibited05()\n {\n var source = @\"\npublic delegate void D();\nclass Test\n{\n public D D;\n\n public void TestIdenticalEventName()\n {\n D.CreateDelegate(null, null, null); // CS0176\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,14): warning CS0649: Field 'Test.D' is never assigned to, and will always have its default value null\n // public D D;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"D\").WithArguments(\"Test.D\", \"null\")\n );\n }\n\n [Fact]\n public void CS0177ERR_ParamUnassigned01()\n {\n var text =\n@\"class C\n{\n static void M(out int x, out int y, out int z)\n {\n try\n {\n x = 0;\n y = 1;\n }\n catch (System.Exception)\n {\n x = 1;\n }\n finally\n {\n z = 1;\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"M\").WithArguments(\"y\").WithLocation(3, 17));\n }\n\n [WorkItem(528243, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528243\")]\n [Fact]\n public void CS0177ERR_ParamUnassigned02()\n {\n var text =\n@\"class C\n{\n static bool P { get { return false; } }\n static object M(out object x)\n {\n if (P)\n {\n object o = P ? M(out x) : null;\n return o;\n }\n return P ? null : M(out x);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method\n // return o;\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"return o;\").WithArguments(\"x\").WithLocation(9, 13),\n // (11,9): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method\n // return P ? null : M(out x);\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"return P ? null : M(out x);\").WithArguments(\"x\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0185ERR_LockNeedsReference()\n {\n var text = @\"\npublic class MainClass\n{\n public static void Main ()\n {\n lock (1) // CS0185\n // try the following lines instead\n // MainClass x = new MainClass();\n // lock(x)\n {\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LockNeedsReference, Line = 6, Column = 15 } });\n }\n\n [Fact]\n public void CS0186ERR_NullNotValid()\n {\n var text = @\"\nusing System.Collections;\n\nclass MyClass\n{\n static void Main()\n {\n // Each of the following lines generates CS0186:\n foreach (int i in null) { } // CS0186\n foreach (int i in (IEnumerable)null) { }; // CS0186\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 9, Column = 27 } ,\n new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 10, Column = 27 }});\n }\n\n [Fact]\n public void CS0186ERR_NullNotValid02()\n {\n var text = @\"\npublic class Test\n{\n public static void Main(string[] args)\n {\n foreach (var x in default(int[])) { }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NullNotValid, \"default(int[])\"));\n }\n\n [WorkItem(540983, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540983\")]\n [Fact]\n public void CS0188ERR_UseDefViolationThis()\n {\n var text = @\"\nnamespace MyNamespace\n{\n class MyClass\n {\n struct S\n {\n public int a;\n\n void Goo()\n {\n }\n\n S(int i)\n {\n // a = i;\n Goo(); // CS0188\n }\n }\n public static void Main()\n { }\n\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (17,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n // Goo(); // CS0188\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"Goo\").WithArguments(\"this\"),\n // (8,24): warning CS0649: Field 'MyNamespace.MyClass.S.a' is never assigned to, and will always have its default value 0\n // public int a;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"a\").WithArguments(\"MyNamespace.MyClass.S.a\", \"0\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\"), WorkItem(864605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605\")]\n public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ImplicitReceiver()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n\tint value;\n\n public S(int v)\n {\n var b1 = F is Action;\n value = v;\n }\n \n void F()\n {\n \n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"F is Action\").WithLocation(10, 18),\n // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"F\").WithArguments(\"this\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\"), WorkItem(864605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605\")]\n public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ExplicitReceiver()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n\tint value;\n\n public S(int v)\n {\n var b1 = this.F is Action;\n value = v;\n }\n \n void F()\n {\n \n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // var b1 = this.F is Action;\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"this.F is Action\").WithLocation(10, 18),\n // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n // var b1 = this.F is Action;\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"this\").WithArguments(\"this\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\")]\n public void CS0188ERR_UseDefViolationThis_ImplicitReceiverInDynamic()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n dynamic value;\n \n public S(dynamic d)\n {\n /*this.*/ Add(d);\n throw new NotImplementedException();\n }\n \n void Add(int value)\n {\n this.value += value;\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,19): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"Add\").WithArguments(\"this\"));\n }\n\n [Fact, WorkItem(579533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533\")]\n public void CS0188ERR_UseDefViolationThis_ExplicitReceiverInDynamic()\n {\n string source = @\"\nusing System;\n \nstruct S\n{\n dynamic value;\n \n public S(dynamic d)\n {\n this.Add(d);\n throw new NotImplementedException();\n }\n \n void Add(int value)\n {\n this.value += value;\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (10,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to\n Diagnostic(ErrorCode.ERR_UseDefViolationThis, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS0190ERR_ArgsInvalid()\n {\n string source = @\"\nusing System;\npublic class C\n{\n static void M(__arglist)\n {\n ArgIterator ai = new ArgIterator(__arglist); \n }\n static void Main()\n {\n M(__arglist);\n }\n}\";\n var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45);\n comp.VerifyDiagnostics(\n // (11,7): error CS0190: The __arglist construct is valid only within a variable argument method\n // M(__arglist);\n Diagnostic(ErrorCode.ERR_ArgsInvalid, \"__arglist\")\n );\n }\n\n [Fact]\n public void CS4013ERR_SpecialByRefInLambda01()\n {\n // Note that the native compiler does *not* produce an error when you illegally\n // use __arglist inside a lambda, oddly enough. Roslyn does.\n\n string source = @\"\nusing System;\nusing System.Linq;\npublic class C\n{\n delegate int D(RuntimeArgumentHandle r);\n static void M(__arglist)\n {\n D f = null;\n f = x=>f(__arglist);\n f = delegate { return f(__arglist); };\n var q = from x in new int[10] select f(__arglist);\n }\n static void Main()\n {\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(source);\n comp.VerifyDiagnostics(\n // (10,14): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // f = x=>f(__arglist);\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (11,29): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // f = delegate { return f(__arglist); };\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (12,44): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // var q = from x in new int[10] select f(__arglist);\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\")\n );\n }\n\n [Fact]\n public void CS4013ERR_SpecialByRefInLambda02()\n {\n string source = @\"\nusing System;\npublic class C\n{\n static void M(__arglist)\n {\n RuntimeArgumentHandle h = __arglist;\n Action action = ()=> \n { \n RuntimeArgumentHandle h2 = h; // Bad use of h\n ArgIterator args1 = new ArgIterator(h); // Bad use of h\n RuntimeArgumentHandle h3 = h2; // no error; does not create field\n ArgIterator args2 = new ArgIterator(h2); // no error; does not create field\n };\n }\n static void Main()\n {\n }\n}\";\n CreateCompilationWithMscorlib45(source).VerifyEmitDiagnostics(\n // (10,34): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // RuntimeArgumentHandle h2 = h; // Bad use of h\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (11,43): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // ArgIterator args1 = new ArgIterator(h); // Bad use of h\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h\").WithArguments(\"System.RuntimeArgumentHandle\"));\n }\n\n [Fact]\n public void CS4013ERR_SpecialByRefInLambda03()\n {\n string source = @\"\nusing System;\nusing System.Collections.Generic;\npublic class C\n{\n static void N(RuntimeArgumentHandle x) {}\n static IEnumerable M(RuntimeArgumentHandle h1) // Error: hoisted to field\n {\n N(h1);\n yield return 1;\n RuntimeArgumentHandle h2 = default(RuntimeArgumentHandle);\n yield return 2;\n N(h2); // Error: hoisted to field\n yield return 3;\n RuntimeArgumentHandle h3 = default(RuntimeArgumentHandle);\n N(h3); // No error; we don't need to hoist this one to a field\n }\n static void Main()\n {\n }\n}\";\n\n CreateCompilation(source).Emit(new System.IO.MemoryStream()).Diagnostics\n .Verify(\n // (7,51): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // static IEnumerable M(RuntimeArgumentHandle h1) // Error: hoisted to field\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h1\").WithArguments(\"System.RuntimeArgumentHandle\"),\n // (13,7): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method\n // N(h2); // Error: hoisted to field\n Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, \"h2\").WithArguments(\"System.RuntimeArgumentHandle\")\n );\n }\n\n [Fact, WorkItem(538008, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538008\")]\n public void CS0191ERR_AssgReadonly()\n {\n var source =\n@\"class MyClass\n{\n public readonly int TestInt = 6; // OK to assign to readonly field in declaration\n\n public MyClass()\n {\n TestInt = 11; // OK to assign to readonly field in constructor\n TestInt = 12; // OK to assign to readonly field multiple times in constructor\n this.TestInt = 13; // OK to assign with explicit this receiver\n MyClass t = this;\n t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this\n }\n\n public void TestReadOnly()\n {\n TestInt = 19; // CS0191\n }\n\n public static void Main()\n {\n }\n}\n\nclass MyDerived : MyClass\n{\n MyDerived()\n {\n TestInt = 15; // CS0191 - not in declaring class\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (28,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer))\n // TestInt = 15; // CS0191 - not in declaring class\n Diagnostic(ErrorCode.ERR_AssgReadonly, \"TestInt\").WithLocation(28, 9),\n // (11,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer))\n // t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this\n Diagnostic(ErrorCode.ERR_AssgReadonly, \"t.TestInt\").WithLocation(11, 9),\n // (16,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer))\n // TestInt = 19; // CS0191\n Diagnostic(ErrorCode.ERR_AssgReadonly, \"TestInt\").WithLocation(16, 9));\n }\n\n [WorkItem(538009, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538009\")]\n [Fact]\n public void CS0192ERR_RefReadonly()\n {\n var text = @\"\n class MyClass\n{\n public readonly int TestInt = 6;\n static void TestMethod(ref int testInt)\n {\n testInt = 0;\n }\n\n MyClass()\n {\n TestMethod(ref TestInt); // OK\n }\n\n public void PassReadOnlyRef()\n {\n TestMethod(ref TestInt); // CS0192\n }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonly, Line = 17, Column = 24 } });\n }\n\n [Fact]\n public void CS0193ERR_PtrExpected()\n {\n var text = @\"\nusing System;\n\npublic struct Age\n{\n public int AgeYears;\n public int AgeMonths;\n public int AgeDays;\n}\n\npublic class MyClass\n{\n public static void SetAge(ref Age anAge, int years, int months, int days)\n {\n anAge->Months = 3; // CS0193, anAge is not a pointer\n // try the following line instead\n // anAge.AgeMonths = 3;\n }\n\n public static void Main()\n {\n Age MyAge = new Age();\n Console.WriteLine(MyAge.AgeMonths);\n SetAge(ref MyAge, 22, 4, 15);\n Console.WriteLine(MyAge.AgeMonths);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PtrExpected, Line = 15, Column = 7 } });\n }\n\n [CompilerTrait(CompilerFeature.IOperation)]\n [Fact]\n public void CS0196ERR_PtrIndexSingle()\n {\n var text = @\"\nunsafe public class MyClass\n{\n public static void Main ()\n {\n int *i = null;\n int j = 0;\n j = i[1,2]; // CS0196\n // try the following line instead\n // j = i[1];\n }\n}\";\n var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (8,11): error CS0196: A pointer must be indexed by only one value\n // j = i[1,2]; // CS0196\n Diagnostic(ErrorCode.ERR_PtrIndexSingle, \"i[1,2]\"));\n\n\n var tree = compilation.SyntaxTrees.Single();\n var node = tree.GetRoot().DescendantNodes().OfType().First();\n\n Assert.Equal(\"i[1,2]\", node.ToString());\n\n compilation.VerifyOperationTree(node, expectedOperationTree:\n@\"\nIOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1,2]')\n Children(2):\n ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32*, IsInvalid) (Syntax: 'i')\n IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1,2]')\n Children(2):\n ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')\n ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')\n\");\n }\n\n [Fact]\n public void CS0198ERR_AssgReadonlyStatic()\n {\n var text = @\"\npublic class MyClass\n{\n public static readonly int TestInt = 6;\n\n static MyClass()\n {\n TestInt = 7;\n TestInt = 8;\n MyClass.TestInt = 7;\n }\n\n public MyClass()\n {\n TestInt = 11; // CS0198, constructor is not static and readonly field is\n }\n\n private void InstanceMethod()\n {\n TestInt = 12; // CS0198\n }\n\n private void StaticMethod()\n {\n TestInt = 13; // CS0198\n }\n\n public static void Main()\n {\n }\n}\n\nclass MyDerived : MyClass\n{\n static MyDerived()\n {\n MyClass.TestInt = 14; // CS0198, not in declaring class\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[]\n {\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 15, Column = 7 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 20, Column = 8 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 25, Column = 8 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 37, Column = 9 },\n });\n }\n\n [Fact, WorkItem(990, \"https://github.com/dotnet/roslyn/issues/990\")]\n public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01()\n {\n var text =\n@\"public static class Goo\n{\n static Goo()\n {\n Goo.X = 1;\n Goo.Y = 2;\n Goo.Y = 3;\n }\n\n public static readonly int X;\n public static int Y { get; }\n}\";\n CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (6,9): error CS0200: Property or indexer 'Goo.Y' cannot be assigned to -- it is read only\n // Goo.Y = 2;\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"Goo.Y\").WithArguments(\"Goo.Y\").WithLocation(6, 9)\n );\n CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (5,9): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)\n // Goo.X = 1;\n Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, \"Goo.X\").WithLocation(5, 9),\n // (6,9): error CS0200: Property or indexer 'Goo.Y' cannot be assigned to -- it is read only\n // Goo.Y = 2;\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"Goo.Y\").WithArguments(\"Goo.Y\").WithLocation(6, 9)\n );\n }\n\n [Fact, WorkItem(990, \"https://github.com/dotnet/roslyn/issues/990\")]\n public void WriteOfReadonlyStaticMemberOfAnotherInstantiation02()\n {\n var text =\n@\"using System;\nusing System.Threading;\nclass Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(Goo.x);\n Console.WriteLine(Goo.x);\n Console.WriteLine(Goo.x);\n Console.WriteLine(Goo.x);\n }\n}\n\npublic static class Goo\n{\n static Goo()\n {\n Console.WriteLine(\"\"initializing for \"\" + typeof(T));\n Goo.x = typeof(T).Name;\n }\n\n public static readonly string x;\n}\";\n var expectedOutput =\n@\"initializing for System.Int64\ninitializing for System.Int32\n\nInt64\ninitializing for System.String\n\nString\n\";\n // Although we accept this nasty code, it will not verify.\n CompileAndVerify(text, expectedOutput: expectedOutput, verify: Verification.Fails);\n }\n\n [Fact]\n public void CS0199ERR_RefReadonlyStatic()\n {\n var text = @\"\nclass MyClass\n{\n public static readonly int TestInt = 6;\n\n static void TestMethod(ref int testInt)\n {\n testInt = 0;\n }\n\n MyClass()\n {\n TestMethod(ref TestInt); // CS0199, TestInt is static\n }\n\n public static void Main()\n {\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonlyStatic, Line = 13, Column = 24 } });\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp01()\n {\n var source =\n@\"abstract class A\n{\n internal static A P { get { return null; } }\n internal object Q { get; set; }\n public abstract object R { get; }\n}\nclass B : A\n{\n public override object R { get { return null; } }\n}\nclass Program\n{\n static void M(B b)\n {\n B.P.Q = null;\n B.P = null; // CS0200\n b.R = null; // CS0200\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,9): error CS0200: Property or indexer 'A.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"B.P\").WithArguments(\"A.P\").WithLocation(16, 9),\n // (17,9): error CS0200: Property or indexer 'B.R' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.R\").WithArguments(\"B.R\").WithLocation(17, 9));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp02()\n {\n var source =\n@\"class A\n{\n public virtual A P { get; set; }\n public A Q { get { return null; } }\n}\nclass B : A\n{\n public override A P { get { return null; } }\n}\nclass Program\n{\n static void M(B b)\n {\n b.P = null;\n b.Q = null; // CS0200\n b.Q.P = null;\n b.P.Q = null; // CS0200\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (15,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.Q\").WithArguments(\"A.Q\").WithLocation(15, 9),\n // (17,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.P.Q\").WithArguments(\"A.Q\").WithLocation(17, 9));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp03()\n {\n var source =\n@\"class C\n{\n static int P { get { return 0; } }\n int Q { get { return 0; } }\n static void M(C c)\n {\n ++P;\n ++c.Q;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,11): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"P\").WithArguments(\"C.P\").WithLocation(7, 11),\n // (8,11): error CS0200: Property or indexer 'C.Q' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"c.Q\").WithArguments(\"C.Q\").WithLocation(8, 11));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp04()\n {\n var source =\n@\"class C\n{\n object P { get { P = null; return null; } }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,22): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"P\").WithArguments(\"C.P\").WithLocation(3, 22));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp05()\n {\n CreateCompilation(\n@\"class C\n{\n int this[int x] { get { return x; } }\n void M(int b)\n {\n this[0] = b;\n this[1]++;\n this[2] += 1;\n }\n}\")\n .VerifyDiagnostics(\n // (6,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"this[0]\").WithArguments(\"C.this[int]\"),\n // (7,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"this[1]\").WithArguments(\"C.this[int]\"),\n // (8,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"this[2]\").WithArguments(\"C.this[int]\"));\n }\n\n [Fact]\n public void CS0200ERR_AssgReadonlyProp06()\n {\n var source1 =\n@\"public class A\n{\n public virtual object P { get { return null; } private set { } }\n}\npublic class B : A\n{\n public override object P { get { return null; } }\n}\";\n var compilation1 = CreateCompilation(source1);\n compilation1.VerifyDiagnostics();\n var compilationVerifier = CompileAndVerify(compilation1);\n var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData);\n var source2 =\n@\"class C\n{\n static void M(B b)\n {\n var o = b.P;\n b.P = o;\n }\n}\";\n var compilation2 = CreateCompilation(source2, references: new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (6,9): error CS0200: Property or indexer 'B.P' cannot be assigned to -- it is read only\n Diagnostic(ErrorCode.ERR_AssgReadonlyProp, \"b.P\").WithArguments(\"B.P\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0201ERR_IllegalStatement1()\n {\n var text = @\"\npublic class MyList \n{\n public void Add(T x)\n {\n int i = 0;\n if ( (object)x == null)\n {\n checked(i++); // CS0201\n\n // OK\n checked {\n i++; \n }\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,10): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"checked(i++)\"));\n }\n\n [Fact, WorkItem(536863, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863\")]\n public void CS0201ERR_IllegalStatement2()\n {\n var text = @\"\nclass A\n{\n public static int Main()\n {\n (a) => a;\n (a, b) => { };\n int x = 0; int y = 0;\n x + y; x == 1;\n }\n}\";\n CreateCompilation(text, parseOptions: TestOptions.Regular.WithTuplesFeature()).VerifyDiagnostics(\n // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a) => a;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a) => a\").WithLocation(6, 9),\n // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a, b) => { };\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a, b) => { }\").WithLocation(7, 9),\n // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x + y\").WithLocation(9, 9),\n // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x == 1\").WithLocation(9, 16),\n // (4,23): error CS0161: 'A.Main()': not all code paths return a value\n // public static int Main()\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"Main\").WithArguments(\"A.Main()\").WithLocation(4, 23)\n );\n }\n\n [Fact, WorkItem(536863, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863\")]\n public void CS0201ERR_IllegalStatement2WithCSharp6()\n {\n var test = @\"\nclass A\n{\n public static int Main()\n {\n (a) => a;\n (a, b) => { };\n int x = 0; int y = 0;\n x + y; x == 1;\n }\n}\";\n var comp = CreateCompilation(new[] { Parse(test, options: TestOptions.Regular6) }, new MetadataReference[] { });\n comp.VerifyDiagnostics(\n // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a) => a;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a) => a\").WithLocation(6, 9),\n // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // (a, b) => { };\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"(a, b) => { }\").WithLocation(7, 9),\n // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x + y\").WithLocation(9, 9),\n // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x + y; x == 1;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x == 1\").WithLocation(9, 16),\n // (4,23): error CS0161: 'A.Main()': not all code paths return a value\n // public static int Main()\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"Main\").WithArguments(\"A.Main()\").WithLocation(4, 23)\n );\n }\n\n [Fact]\n public void CS0202ERR_BadGetEnumerator()\n {\n var text = @\"\npublic class C1\n{\n public int Current\n {\n get\n {\n return 0;\n }\n }\n\n public bool MoveNext ()\n {\n return false;\n }\n\n public static implicit operator C1 (int c1)\n {\n return 0;\n }\n}\n\npublic class C2\n{\n public int Current\n {\n get\n {\n return 0;\n }\n }\n\n public bool MoveNext ()\n {\n return false;\n }\n\n public C1[] GetEnumerator ()\n {\n return null;\n }\n}\n\npublic class MainClass\n{\n public static void Main ()\n {\n C2 c2 = new C2();\n\n foreach (C1 x in c2) // CS0202\n {\n System.Console.WriteLine(x.Current);\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadGetEnumerator, Line = 50, Column = 24 } });\n }\n\n // [Fact()]\n // public void CS0204ERR_TooManyLocals()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_TooManyLocals, Line = 8, Column = 13 } }\n // );\n // }\n\n [Fact()]\n public void CS0205ERR_AbstractBaseCall()\n {\n var text =\n@\"abstract class A\n{\n abstract public void M();\n abstract protected object P { get; }\n}\nclass B : A\n{\n public override void M()\n {\n base.M(); // CS0205\n object o = base.P; // CS0205\n }\n protected override object P { get { return null; } }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 10, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 11, Column = 20 });\n }\n\n [Fact]\n public void CS0205ERR_AbstractBaseCall_Override()\n {\n var text =\n@\"\npublic class Base1\n{\n public virtual long Property1 { get { return 0; } set { } }\n}\nabstract public class Base2 : Base1\n{\n public abstract override long Property1 { get; }\n void test1()\n {\n Property1 += 1;\n }\n}\npublic class Derived : Base2\n{\n public override long Property1 { get { return 1; } set { } }\n void test2()\n {\n base.Property1++;\n base.Property1 = 2;\n long x = base.Property1;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1'\n Diagnostic(ErrorCode.ERR_AbstractBaseCall, \"base.Property1\").WithArguments(\"Base2.Property1\"),\n // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1'\n Diagnostic(ErrorCode.ERR_AbstractBaseCall, \"base.Property1\").WithArguments(\"Base2.Property1\"));\n }\n\n [Fact]\n public void CS0206ERR_RefProperty()\n {\n var text =\n@\"class C\n{\n static int P { get; set; }\n object Q { get; set; }\n static void M(ref int i)\n {\n }\n static void M(out object o)\n {\n o = null;\n }\n void M()\n {\n M(ref P); // CS0206\n M(out this.Q); // CS0206\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"P\").WithArguments(\"C.P\"),\n // (15,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"this.Q\").WithArguments(\"C.Q\"));\n }\n\n [Fact]\n public void CS0206ERR_RefProperty_Indexers()\n {\n var text =\n@\"class C\n{\n int this[int x] { get { return x; } set { } }\n static void R(ref int i)\n {\n }\n static void O(out int o)\n {\n o = 0;\n }\n void M()\n {\n R(ref this[0]); // CS0206\n O(out this[0]); // CS0206\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"this[0]\").WithArguments(\"C.this[int]\"),\n // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter\n Diagnostic(ErrorCode.ERR_RefProperty, \"this[0]\").WithArguments(\"C.this[int]\"));\n }\n\n [Fact]\n public void CS0208ERR_ManagedAddr01()\n {\n var text = @\"\nclass myClass\n{\n public int a = 98;\n}\n\nstruct myProblemStruct\n{\n string s;\n float f;\n}\n\nstruct myGoodStruct\n{\n int i;\n float f;\n}\n\npublic class MyClass\n{\n unsafe public static void Main()\n {\n // myClass is a class, a managed type.\n myClass s = new myClass(); \n myClass* s2 = &s; // CS0208\n\n // The struct contains a string, a managed type.\n int i = sizeof(myProblemStruct); //CS0208\n \n // The struct contains only value types.\n i = sizeof(myGoodStruct); //OK\n \n }\n}\n\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (25,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass')\n // myClass* s2 = &s; // CS0208\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"myClass*\").WithArguments(\"myClass\"),\n // (25,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass')\n // myClass* s2 = &s; // CS0208\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"&s\").WithArguments(\"myClass\"),\n // (28,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myProblemStruct')\n // int i = sizeof(myProblemStruct); //CS0208\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"sizeof(myProblemStruct)\").WithArguments(\"myProblemStruct\"),\n\n // (9,12): warning CS0169: The field 'myProblemStruct.s' is never used\n // string s;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"s\").WithArguments(\"myProblemStruct.s\"),\n // (10,11): warning CS0169: The field 'myProblemStruct.f' is never used\n // float f;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"f\").WithArguments(\"myProblemStruct.f\"),\n // (15,9): warning CS0169: The field 'myGoodStruct.i' is never used\n // int i;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"i\").WithArguments(\"myGoodStruct.i\"),\n // (16,11): warning CS0169: The field 'myGoodStruct.f' is never used\n // float f;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"f\").WithArguments(\"myGoodStruct.f\"));\n }\n\n [Fact]\n public void CS0208ERR_ManagedAddr02()\n {\n var source =\n@\"enum E { }\ndelegate void D();\nstruct S { }\ninterface I { }\nunsafe class C\n{\n object* _object;\n void* _void;\n bool* _bool;\n char* _char;\n sbyte* _sbyte;\n byte* _byte;\n short* _short;\n ushort* _ushort;\n int* _int;\n uint* _uint;\n long* _long;\n ulong* _ulong;\n decimal* _decimal;\n float* _float;\n double* _double;\n string* _string;\n System.IntPtr* _intptr;\n System.UIntPtr* _uintptr;\n int** _intptr2;\n int?* _nullable;\n dynamic* _dynamic;\n E* e;\n D* d;\n S* s;\n I* i;\n C* c;\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll)\n .GetDiagnostics()\n .Where(d => d.Severity == DiagnosticSeverity.Error)\n .Verify(\n // (22,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')\n // string* _string;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"_string\").WithArguments(\"string\").WithLocation(22, 13),\n // (27,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic')\n // dynamic* _dynamic;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"_dynamic\").WithArguments(\"dynamic\").WithLocation(27, 14),\n // (29,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('D')\n // D* d;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"d\").WithArguments(\"D\").WithLocation(29, 8),\n // (31,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('I')\n // I* i;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"i\").WithArguments(\"I\").WithLocation(31, 8),\n // (32,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')\n // C* c;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"c\").WithArguments(\"C\").WithLocation(32, 8),\n // (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object')\n // object* _object;\n Diagnostic(ErrorCode.ERR_ManagedAddr, \"_object\").WithArguments(\"object\").WithLocation(7, 13));\n }\n\n [Fact]\n public void CS0209ERR_BadFixedInitType()\n {\n var text = @\"\nclass Point\n{\n public int x, y;\n}\n\npublic class MyClass\n{\n unsafe public static void Main()\n {\n Point pt = new Point();\n\n fixed (int i) // CS0209\n {\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (13,18): error CS0209: The type of a local declared in a fixed statement must be a pointer type\n // fixed (int i) // CS0209\n Diagnostic(ErrorCode.ERR_BadFixedInitType, \"i\"),\n // (13,18): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // fixed (int i) // CS0209\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"i\"),\n\n // (4,15): warning CS0649: Field 'Point.x' is never assigned to, and will always have its default value 0\n // public int x, y;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"x\").WithArguments(\"Point.x\", \"0\"),\n // (4,18): warning CS0649: Field 'Point.y' is never assigned to, and will always have its default value 0\n // public int x, y;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"y\").WithArguments(\"Point.y\", \"0\"));\n }\n\n [Fact]\n public void CS0210ERR_FixedMustInit()\n {\n var text = @\"\nusing System.IO;\nclass Test \n{\n static void Main() \n {\n using (StreamWriter w) // CS0210\n {\n w.WriteLine(\"\"Hello there\"\");\n }\n\n using (StreamWriter x, y) // CS0210, CS0210\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // using (StreamWriter w) // CS0210\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"w\").WithLocation(7, 27),\n // (12,27): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // using (StreamWriter x, y) // CS0210, CS0210\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"x\").WithLocation(12, 27),\n // (12,30): error CS0210: You must provide an initializer in a fixed or using statement declaration\n // using (StreamWriter x, y) // CS0210, CS0210\n Diagnostic(ErrorCode.ERR_FixedMustInit, \"y\").WithLocation(12, 30),\n // (9,10): error CS0165: Use of unassigned local variable 'w'\n // w.WriteLine(\"Hello there\");\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"w\").WithArguments(\"w\").WithLocation(9, 10)\n );\n }\n\n [Fact]\n public void CS0211ERR_InvalidAddrOp()\n {\n var text = @\"\npublic class MyClass\n{\n unsafe public void M()\n {\n int a = 0, b = 0;\n int *i = &(a + b); // CS0211, the addition of two local variables\n // try the following line instead\n // int *i = &a;\n }\n\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,18): error CS0211: Cannot take the address of the given expression\n // int *i = &(a + b); // CS0211, the addition of two local variables\n Diagnostic(ErrorCode.ERR_InvalidAddrOp, \"a + b\"));\n }\n\n [Fact]\n public void CS0212ERR_FixedNeeded()\n {\n var text = @\"\npublic class A {\n public int iField = 5;\n \n unsafe public void M() { \n A a = new A();\n int* ptr = &a.iField; // CS0212 \n }\n\n // OK\n unsafe public void M2() {\n A a = new A();\n fixed (int* ptr = &a.iField) {}\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer\n // int* ptr = &a.iField; // CS0212 \n Diagnostic(ErrorCode.ERR_FixedNeeded, \"&a.iField\"));\n }\n\n [Fact]\n public void CS0213ERR_FixedNotNeeded()\n {\n var text = @\"\npublic class MyClass\n{\n unsafe public static void Main()\n {\n int i = 45;\n fixed (int *j = &i) { } // CS0213\n // try the following line instead\n // int* j = &i;\n\n int[] a = new int[] {1,2,3};\n fixed (int *b = a)\n {\n fixed (int *c = b) { } // CS0213\n // try the following line instead\n // int *c = b;\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,23): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression\n // fixed (int *j = &i) { } // CS0213\n Diagnostic(ErrorCode.ERR_FixedNotNeeded, \"&i\").WithLocation(7, 23),\n // (14,26): error CS9385: The given expression cannot be used in a fixed statement\n // fixed (int *c = b) { } // CS0213\n Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, \"b\").WithLocation(14, 26));\n }\n\n [Fact]\n public void CS0217ERR_BadBoolOp()\n {\n // Note that the wording of this error message has changed.\n\n var text = @\"\npublic class MyClass\n{\n public static bool operator true (MyClass f)\n {\n return false;\n }\n\n public static bool operator false (MyClass f)\n {\n return false;\n }\n\n public static int operator & (MyClass f1, MyClass f2) \n {\n return 0;\n }\n\n public static void Main()\n {\n MyClass f = new MyClass();\n int i = f && f; // CS0217\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (22,15): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('MyClass.operator &(MyClass, MyClass)') must have the same return type and parameter types\n // int i = f && f; // CS0217\n Diagnostic(ErrorCode.ERR_BadBoolOp, \"f && f\").WithArguments(\"MyClass.operator &(MyClass, MyClass)\"));\n }\n\n // CS0220 ERR_CheckedOverflow - see ConstantTests\n\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked01()\n {\n string text =\n@\"class MyClass\n{\n static void F(int x) { }\n static void M()\n {\n F((int)0xFFFFFFFF); // CS0221\n F(unchecked((int)uint.MaxValue));\n F(checked((int)(uint.MaxValue - 1))); // CS0221\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,11): error CS0221: Constant value '4294967295' cannot be converted to a 'int' (use 'unchecked' syntax to override)\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"(int)0xFFFFFFFF\").WithArguments(\"4294967295\", \"int\"),\n // (8,19): error CS0221: Constant value '4294967294' cannot be converted to a 'int' (use 'unchecked' syntax to override)\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"(int)(uint.MaxValue - 1)\").WithArguments(\"4294967294\", \"int\"));\n }\n\n [Fact]\n public void CS0221ERR_ConstOutOfRangeChecked02()\n {\n string text =\n@\"enum E : byte { A, B = 0xfe, C }\nclass C\n{\n const int F = (int)(E.C + 1); // CS0221\n const int G = (int)unchecked(1 + E.C);\n const int H = (int)checked(E.A - 1); // CS0221\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,25): error CS0031: Constant value '256' cannot be converted to a 'E'\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"E.C + 1\").WithArguments(\"256\", \"E\"),\n // (6,32): error CS0221: Constant value '-1' cannot be converted to a 'E' (use 'unchecked' syntax to override)\n Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, \"E.A - 1\").WithArguments(\"-1\", \"E\"));\n }\n\n [WorkItem(1119609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609\")]\n [Fact(Skip = \"1119609\")]\n public void CS0221ERR_ConstOutOfRangeChecked03()\n {\n var text =\n@\"public class MyClass\n{\n decimal x1 = (decimal)double.PositiveInfinity; //CS0221\n decimal x2 = (decimal)double.NegativeInfinity; //CS0221\n decimal x3 = (decimal)double.NaN; //CS0221\n decimal x4 = (decimal)double.MaxValue; //CS0221\n\n public static void Main() {}\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (3,18): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal'\n // decimal x1 = (decimal)double.PositiveInfinity; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.PositiveInfinity\").WithArguments(\"Infinity\", \"decimal\"),\n // (4,18): error CS0031: Constant value '-Infinity' cannot be converted to a 'decimal'\n // decimal x2 = (decimal)double.NegativeInfinity; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.NegativeInfinity\").WithArguments(\"-Infinity\", \"decimal\"),\n // (5,18): error CS0031: Constant value 'NaN' cannot be converted to a 'decimal'\n // decimal x3 = (decimal)double.NaN; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.NaN\").WithArguments(\"NaN\", \"decimal\"),\n // (6,18): error CS0031: Constant value '1.79769313486232E+308' cannot be converted to a 'decimal'\n // decimal x4 = (decimal)double.MaxValue; //CS0221\n Diagnostic(ErrorCode.ERR_ConstOutOfRange, \"(decimal)double.MaxValue\").WithArguments(\"1.79769313486232E+308\", \"decimal\"),\n // (3,13): warning CS0414: The field 'MyClass.x1' is assigned but its value is never used\n // decimal x1 = (decimal)double.PositiveInfinity; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x1\").WithArguments(\"MyClass.x1\"),\n // (4,13): warning CS0414: The field 'MyClass.x2' is assigned but its value is never used\n // decimal x2 = (decimal)double.NegativeInfinity; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x2\").WithArguments(\"MyClass.x2\"),\n // (5,13): warning CS0414: The field 'MyClass.x3' is assigned but its value is never used\n // decimal x3 = (decimal)double.NaN; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x3\").WithArguments(\"MyClass.x3\"),\n // (6,13): warning CS0414: The field 'MyClass.x4' is assigned but its value is never used\n // decimal x4 = (decimal)double.MaxValue; //CS0221\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x4\").WithArguments(\"MyClass.x4\"));\n }\n\n [Fact]\n public void CS0226ERR_IllegalArglist()\n {\n var text = @\"\npublic class C\n {\n public static int Main ()\n {\n __arglist(1,\"\"This is a string\"\"); // CS0226\n return 0;\n }\n }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_IllegalArglist, @\"__arglist(1,\"\"This is a string\"\")\"));\n }\n\n // [Fact()]\n // public void CS0228ERR_NoAccessibleMember()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoAccessibleMember, Line = 31, Column = 17 } }\n // );\n // }\n\n [Fact]\n public void CS0229ERR_AmbigMember()\n {\n var text = @\"\ninterface IList\n{\n int Count\n {\n get;\n set;\n }\n\n void Counter();\n}\n\ninterface Icounter\n{\n double Count\n {\n get;\n set;\n }\n}\n\ninterface IListCounter : IList , Icounter {}\n\nclass MyClass\n{\n void Test(IListCounter x)\n {\n x.Count = 1; // CS0229\n // Try one of the following lines instead:\n // ((IList)x).Count = 1;\n // or\n // ((Icounter)x).Count = 1;\n }\n\n public static void Main() {}\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigMember, Line = 28, Column = 11 } });\n }\n\n [Fact]\n public void CS0233ERR_SizeofUnsafe()\n {\n var text = @\"\nusing System;\nusing System.Runtime.InteropServices;\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct S\n{\n public int a;\n}\n\npublic class MyClass\n{\n public static void Main()\n {\n S myS = new S();\n Console.WriteLine(sizeof(S)); // CS0233\n // Try the following line instead:\n // Console.WriteLine(Marshal.SizeOf(myS));\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,27): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)\n // Console.WriteLine(sizeof(S)); // CS0233\n Diagnostic(ErrorCode.ERR_SizeofUnsafe, \"sizeof(S)\").WithArguments(\"S\"),\n\n // (15,11): warning CS0219: The variable 'myS' is assigned but its value is never used\n // S myS = new S();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"myS\").WithArguments(\"myS\"));\n }\n\n [Fact]\n public void CS0236ERR_FieldInitRefNonstatic()\n {\n var text = @\"\npublic class MyClass\n{\n int[] instanceArray;\n static int[] staticArray;\n\n static int staticField = 1;\n const int constField = 1;\n\n int a;\n int b = 1;\n int c = b; //CS0236\n int d = this.b; //CS0027\n int e = InstanceMethod(); //CS0236\n int f = this.InstanceMethod(); //CS0027\n int g = StaticMethod();\n int h = MyClass.StaticMethod();\n int i = GenericInstanceMethod(1); //CS0236\n int j = this.GenericInstanceMethod(1); //CS0027\n int k = GenericStaticMethod(1);\n int l = MyClass.GenericStaticMethod(1);\n int m = InstanceProperty; //CS0236\n int n = this.InstanceProperty; //CS0027\n int o = StaticProperty;\n int p = MyClass.StaticProperty;\n int q = instanceArray[0]; //CS0236\n int r = this.instanceArray[0]; //CS0027\n int s = staticArray[0];\n int t = MyClass.staticArray[0];\n int u = staticField;\n int v = MyClass.staticField;\n int w = constField;\n int x = MyClass.constField;\n\n MyClass()\n {\n a = b;\n }\n\n int InstanceMethod()\n {\n return a;\n }\n\n static int StaticMethod()\n {\n return 1;\n }\n\n T GenericInstanceMethod(T t)\n {\n return t;\n }\n\n static T GenericStaticMethod(T t)\n {\n return t;\n }\n\n int InstanceProperty { get { return a; } }\n\n static int StaticProperty { get { return 1; } }\n\n public static void Main()\n {\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (12,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.b'\n // int c = b; //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"b\").WithArguments(\"MyClass.b\").WithLocation(12, 13),\n // (13,13): error CS0027: Keyword 'this' is not available in the current context\n // int d = this.b; //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(13, 13),\n // (14,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceMethod()'\n // int e = InstanceMethod(); //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"InstanceMethod\").WithArguments(\"MyClass.InstanceMethod()\").WithLocation(14, 13),\n // (15,13): error CS0027: Keyword 'this' is not available in the current context\n // int f = this.InstanceMethod(); //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(15, 13),\n // (18,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.GenericInstanceMethod(int)'\n // int i = GenericInstanceMethod(1); //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"GenericInstanceMethod\").WithArguments(\"MyClass.GenericInstanceMethod(int)\").WithLocation(18, 13),\n // (19,13): error CS0027: Keyword 'this' is not available in the current context\n // int j = this.GenericInstanceMethod(1); //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(19, 13),\n // (22,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceProperty'\n // int m = InstanceProperty; //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"InstanceProperty\").WithArguments(\"MyClass.InstanceProperty\").WithLocation(22, 13),\n // (23,13): error CS0027: Keyword 'this' is not available in the current context\n // int n = this.InstanceProperty; //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(23, 13),\n // (26,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.instanceArray'\n // int q = instanceArray[0]; //CS0236\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"instanceArray\").WithArguments(\"MyClass.instanceArray\").WithLocation(26, 13),\n // (27,13): error CS0027: Keyword 'this' is not available in the current context\n // int r = this.instanceArray[0]; //CS0027\n Diagnostic(ErrorCode.ERR_ThisInBadContext, \"this\").WithLocation(27, 13),\n // (4,11): warning CS0649: Field 'MyClass.instanceArray' is never assigned to, and will always have its default value null\n // int[] instanceArray;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"instanceArray\").WithArguments(\"MyClass.instanceArray\", \"null\").WithLocation(4, 11),\n // (5,18): warning CS0649: Field 'MyClass.staticArray' is never assigned to, and will always have its default value null\n // static int[] staticArray;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"staticArray\").WithArguments(\"MyClass.staticArray\", \"null\").WithLocation(5, 18),\n // (33,9): warning CS0414: The field 'MyClass.x' is assigned but its value is never used\n // int x = MyClass.constField;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"x\").WithArguments(\"MyClass.x\").WithLocation(33, 9),\n // (32,9): warning CS0414: The field 'MyClass.w' is assigned but its value is never used\n // int w = constField;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"w\").WithArguments(\"MyClass.w\").WithLocation(32, 9)\n );\n }\n\n [Fact]\n public void CS0236ERR_FieldInitRefNonstaticMethodGroups()\n {\n var text = @\"\ndelegate void F();\npublic class MyClass\n{\n F a = Static;\n F b = MyClass.Static;\n F c = Static;\n F d = MyClass.Static;\n F e = Instance;\n F f = this.Instance;\n F g = Instance;\n F h = this.Instance;\n\n static void Static() { }\n static void Static() { }\n\n void Instance() { }\n void Instance() { }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(\n text,\n new ErrorDescription[]\n {\n new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 9, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 10, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 11, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 12, Column = 11 },\n });\n }\n\n [WorkItem(541501, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501\")]\n [Fact]\n public void CS0236ERR_FieldInitRefNonstaticProperty()\n {\n CreateCompilation(\n@\"\nenum ProtectionLevel\n{\n Privacy = 0\n}\n \nclass F\n{\n const ProtectionLevel p = ProtectionLevel.Privacy; // CS0236\n \n int ProtectionLevel { get { return 0; } }\n}\n\")\n .VerifyDiagnostics(\n // (9,29): error CS0236: A field initializer cannot reference the non-static field, method, or property 'F.ProtectionLevel'\n // const ProtectionLevel p = ProtectionLevel.Privacy; // CS0120\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"ProtectionLevel\").WithArguments(\"F.ProtectionLevel\"));\n }\n\n [WorkItem(541501, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501\")]\n [Fact]\n public void CS0236ERR_FieldInitRefNonstatic_ObjectInitializer()\n {\n CreateCompilation(\n@\"\npublic class Goo\n{\n public int i;\n public string s;\n}\n\npublic class MemberInitializerTest\n{\n private int i =10;\n private string s = \"\"abc\"\";\n private Goo f = new Goo{i = i, s = s};\n\n public static void Main()\n {\n }\n}\n\")\n .VerifyDiagnostics(\n // (12,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.i'\n // private Goo f = new Goo{i = i, s = s};\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"i\").WithArguments(\"MemberInitializerTest.i\").WithLocation(12, 33),\n // (12,40): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.s'\n // private Goo f = new Goo{i = i, s = s};\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"s\").WithArguments(\"MemberInitializerTest.s\").WithLocation(12, 40));\n }\n\n [Fact]\n public void CS0236ERR_FieldInitRefNonstatic_AnotherInitializer()\n {\n CreateCompilation(\n@\"\nclass TestClass\n{\n int P1 { get; }\n\n int y = (P1 = 123);\n int y1 { get; } = (P1 = 123);\n\n static void Main()\n {\n }\n}\n\")\n .VerifyDiagnostics(\n // (6,14): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1'\n // int y = (P1 = 123);\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"P1\").WithArguments(\"TestClass.P1\").WithLocation(6, 14),\n // (7,24): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1'\n // int y1 { get; } = (P1 = 123);\n Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, \"P1\").WithArguments(\"TestClass.P1\").WithLocation(7, 24)\n );\n }\n\n\n [Fact]\n public void CS0242ERR_VoidError()\n {\n var text = @\"\nclass TestClass\n{\n public unsafe void Test()\n {\n void* p = null;\n p++; //CS0242\n p += 2; //CS0242\n void* q = p + 1; //CS0242\n long diff = q - p; //CS0242\n var v = *p;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,9): error CS0242: The operation in question is undefined on void pointers\n // p++; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"p++\"),\n // (8,9): error CS0242: The operation in question is undefined on void pointers\n // p += 2; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"p += 2\"),\n // (9,19): error CS0242: The operation in question is undefined on void pointers\n // void* q = p + 1; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"p + 1\"),\n // (10,21): error CS0242: The operation in question is undefined on void pointers\n // long diff = q - p; //CS0242\n Diagnostic(ErrorCode.ERR_VoidError, \"q - p\"),\n // (11,17): error CS0242: The operation in question is undefined on void pointers\n // var v = *p;\n Diagnostic(ErrorCode.ERR_VoidError, \"*p\"));\n }\n\n [Fact]\n public void CS0244ERR_PointerInAsOrIs()\n {\n var text = @\"\nclass UnsafeTest\n{\n unsafe static void SquarePtrParam (int* p)\n {\n bool b = p is object; // CS0244 p is pointer\n }\n\n unsafe public static void Main()\n {\n int i = 5;\n SquarePtrParam (&i);\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,16): error CS0244: Neither 'is' nor 'as' is valid on pointer types\n // bool b = p is object; // CS0244 p is pointer\n Diagnostic(ErrorCode.ERR_PointerInAsOrIs, \"p is object\"));\n }\n\n [Fact]\n public void CS0245ERR_CallingFinalizeDeprecated()\n {\n var text = @\"\nclass MyClass // : IDisposable\n{\n /*\n public void Dispose()\n {\n // cleanup code goes here\n }\n */\n\n void m()\n {\n this.Finalize(); // CS0245\n // this.Dispose();\n }\n\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,7): error CS0245: Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.\n Diagnostic(ErrorCode.ERR_CallingFinalizeDeprecated, \"this.Finalize()\"));\n }\n\n [WorkItem(540722, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540722\")]\n [Fact]\n public void CS0246ERR_SingleTypeNameNotFound05()\n {\n CreateCompilation(@\"\nnamespace nms\n{\n public class Mine\n {\n private static int retval = 5;\n public static int Main()\n {\n try { }\n catch (e) { }\n return retval;\n }\n };\n}\n\")\n .VerifyDiagnostics(\n // (10,20): error CS0246: The type or namespace name 'e' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"e\").WithArguments(\"e\"));\n }\n\n [WorkItem(528446, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528446\")]\n [Fact]\n public void CS0246ERR_SingleTypeNameNotFoundNoCS8000()\n {\n CreateCompilation(@\"\nclass Test\n{\n void Main()\n {\n var sum = new j();\n }\n}\n\")\n .VerifyDiagnostics(\n // (11,20): error CS0246: The type or namespace name 'j' could not be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"j\").WithArguments(\"j\"));\n }\n\n [Fact]\n public void CS0247ERR_NegativeStackAllocSize()\n {\n var text = @\"\npublic class MyClass\n{\n unsafe public static void Main()\n {\n int *p = stackalloc int [-30]; // CS0247\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,32): error CS0247: Cannot use a negative size with stackalloc\n // int *p = stackalloc int [-30]; // CS0247\n Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, \"-30\"));\n }\n\n [Fact]\n public void CS0248ERR_NegativeArraySize()\n {\n var text = @\"\nclass MyClass\n{\n public static void Main()\n {\n int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number\n int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes\n int[] myArray3 = new int[3000000000u]; // slightly different code path for uint array sizes\n var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}};\n var myArray5 = new object[-1L] {null};\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,33): error CS0248: Cannot create an array with a negative size\n // int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-3\").WithLocation(6, 33),\n // (7,34): error CS0248: Cannot create an array with a negative size\n // int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-5000000000\").WithLocation(7, 34),\n // (9,35): error CS0248: Cannot create an array with a negative size\n // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}};\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-2\").WithLocation(9, 35),\n // (9,42): error CS0248: Cannot create an array with a negative size\n // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}};\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-1\").WithLocation(9, 42),\n // (10,35): error CS0248: Cannot create an array with a negative size\n // var myArray5 = new object[-1L] {null};\n Diagnostic(ErrorCode.ERR_NegativeArraySize, \"-1L\").WithLocation(10, 35),\n // (10,35): error CS0150: A constant value is expected\n // var myArray5 = new object[-1L] {null};\n Diagnostic(ErrorCode.ERR_ConstantExpected, \"-1L\").WithLocation(10, 35));\n }\n\n [WorkItem(528912, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528912\")]\n [Fact]\n public void CS0250ERR_CallingBaseFinalizeDeprecated()\n {\n var text = @\"\nclass B\n{\n}\n\nclass C : B\n{\n ~C()\n {\n base.Finalize(); // CS0250\n }\n\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor.\n Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, \"base.Finalize()\"));\n }\n\n [Fact]\n public void CS0254ERR_BadCastInFixed()\n {\n var text = @\"\nclass Point\n{\n public uint x, y;\n}\n\nclass FixedTest\n{\n unsafe static void SquarePtrParam (int* p)\n {\n *p *= *p;\n }\n\n unsafe public static void Main()\n {\n Point pt = new Point();\n pt.x = 5;\n pt.y = 6;\n\n fixed (int* p = (int*)&pt.x) // CS0254\n // try the following line instead\n // fixed (uint* p = &pt.x)\n {\n SquarePtrParam ((int*)p);\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (20,23): error CS9385: The given expression cannot be used in a fixed statement\n // fixed (int* p = (int*)&pt.x) // CS0254\n Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, \"(int*)&pt.x\").WithLocation(20, 23));\n }\n\n [Fact]\n public void CS0255ERR_StackallocInFinally()\n {\n var text = @\"\nunsafe class Test\n{\n void M()\n {\n try\n {\n // Something \n }\n finally\n {\n int* fib = stackalloc int[100];\n }\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (12,24): error CS0255: stackalloc may not be used in a catch or finally block\n // int* fib = stackalloc int[100];\n Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, \"stackalloc int[100]\").WithLocation(12, 24));\n }\n\n [Fact]\n public void CS0255ERR_StackallocInCatch()\n {\n var text = @\"\nunsafe class Test\n{\n void M()\n {\n try\n {\n // Something \n }\n catch\n {\n int* fib = stackalloc int[100];\n }\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (12,24): error CS0255: stackalloc may not be used in a catch or finally block\n // int* fib = stackalloc int[100];\n Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, \"stackalloc int[100]\").WithLocation(12, 24));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast01()\n {\n var text = @\"\nclass MyClass\n{\n public static void Main()\n {\n object obj = \"\"MyString\"\";\n // Cannot implicitly convert 'object' to 'MyClass'\n MyClass myClass = obj; // CS0266\n // Try this line instead\n // MyClass c = ( MyClass )obj;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConvCast, Line = 8, Column = 27 } });\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast02()\n {\n var source =\n@\"class C\n{\n const int f = 0L;\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,19): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // const int f = 0L;\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"0L\").WithArguments(\"long\", \"int\").WithLocation(3, 19));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast03()\n {\n var source =\n@\"class C\n{\n static void M()\n {\n const short s = 1L;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,25): error CS0266: Cannot implicitly convert type 'long' to 'short'. An explicit conversion exists (are you missing a cast?)\n // const short s = 1L;\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1L\").WithArguments(\"long\", \"short\").WithLocation(5, 25),\n // (5,21): warning CS0219: The variable 's' is assigned but its value is never used\n // const short s = 1L;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"s\").WithArguments(\"s\").WithLocation(5, 21));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast04()\n {\n var source =\n@\"enum E { A = 1 }\nclass C\n{\n E f = 2; // CS0266\n E g = E.A;\n void M()\n {\n f = E.A;\n g = 'c'; // CS0266\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,11): error CS0266: Cannot implicitly convert type 'int' to 'E'. An explicit conversion exists (are you missing a cast?)\n // E f = 2; // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"2\").WithArguments(\"int\", \"E\").WithLocation(4, 11),\n // (9,13): error CS0266: Cannot implicitly convert type 'char' to 'E'. An explicit conversion exists (are you missing a cast?)\n // g = 'c'; // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"'c'\").WithArguments(\"char\", \"E\").WithLocation(9, 13),\n // (4,7): warning CS0414: The field 'C.f' is assigned but its value is never used\n // E f = 2; // CS0266\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"f\").WithArguments(\"C.f\").WithLocation(4, 7),\n // (5,7): warning CS0414: The field 'C.g' is assigned but its value is never used\n // E g = E.A;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"g\").WithArguments(\"C.g\").WithLocation(5, 7));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast05()\n {\n var source =\n@\"enum E : byte\n{\n A = 'a', // CS0266\n B = 0xff,\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,9): error CS0266: Cannot implicitly convert type 'char' to 'byte'. An explicit conversion exists (are you missing a cast?)\n // A = 'a', // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"'a'\").WithArguments(\"char\", \"byte\").WithLocation(3, 9));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast06()\n {\n var source =\n@\"enum E\n{\n A = 1,\n B = 1L // CS0266\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (4,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // B = 1L // CS0266\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1L\").WithArguments(\"long\", \"int\").WithLocation(4, 9));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast07()\n {\n // No errors\n var source = \"enum E { A, B = A }\";\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast08()\n {\n // No errors\n var source =\n@\"enum E { A = 1, B }\nenum F { X = E.A + 1, Y }\n\";\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast09()\n {\n var source =\n@\"enum E\n{\n A = F.A,\n B = F.B,\n C = G.A,\n D = G.B,\n}\nenum F : short { A = 1, B }\nenum G : long { A = 1, B }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // C = G.A,\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"G.A\").WithArguments(\"long\", \"int\").WithLocation(5, 9),\n // (6,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // D = G.B,\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"G.B\").WithArguments(\"long\", \"int\").WithLocation(6, 9));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast10()\n {\n var source =\n@\"class C\n{\n public const int F = D.G + 1;\n}\nclass D\n{\n public const int G = E.H + 1;\n}\nclass E\n{\n public const int H = 1L;\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (11,26): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)\n // public const int H = 1L;\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1L\").WithArguments(\"long\", \"int\").WithLocation(11, 26));\n }\n\n [Fact()]\n public void CS0266ERR_NoImplicitConvCast11()\n {\n string text = @\"class Program\n{\n static void Main(string[] args)\n {\n bool? b = true;\n int result = b ? 0 : 1; // Compiler error\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"b\").WithArguments(\"bool?\", \"bool\"));\n }\n\n [WorkItem(541718, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718\")]\n [Fact]\n public void CS0266ERR_NoImplicitConvCast12()\n {\n string text = @\"\nclass C1\n{\n public static void Main()\n {\n var cube = new int[Number.One][];\n }\n}\nenum Number\n{\n One,\n Two\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,28): error CS0266: Cannot implicitly convert type 'Number' to 'int'. An explicit conversion exists (are you missing a cast?)\n // var cube = new int[Number.One][];\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"Number.One\").WithArguments(\"Number\", \"int\").WithLocation(6, 28));\n }\n\n [WorkItem(541718, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718\")]\n [Fact]\n public void CS0266ERR_NoImplicitConvCast13()\n {\n string text = @\"\nclass C1\n{\n public static void Main()\n {\n double x = 5;\n int[] arr4 = new int[x];// Invalid\n\n float y = 5;\n int[] arr5 = new int[y];// Invalid\n\n decimal z = 5;\n int[] arr6 = new int[z];// Invalid\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (7,30): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[] arr4 = new int[x];// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"x\").WithArguments(\"double\", \"int\").WithLocation(7, 30),\n // (10,30): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[] arr5 = new int[y];// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"y\").WithArguments(\"float\", \"int\").WithLocation(10, 30),\n // (13,30): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[] arr6 = new int[z];// Invalid\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"z\").WithArguments(\"decimal\", \"int\").WithLocation(13, 30));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast14()\n {\n string source = @\"\nclass C\n{\n public unsafe void M(int* p, object o)\n {\n _ = p[o]; // error with span on 'o'\n _ = p[0]; // ok\n }\n}\n\";\n CreateCompilation(source, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(\n // (6,15): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)\n // _ = p[o]; // error with span on 'o'\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"o\").WithArguments(\"object\", \"int\").WithLocation(6, 15));\n }\n\n [Fact]\n public void CS0266ERR_NoImplicitConvCast15()\n {\n string source = @\"\nclass C\n{\n public void M(object o)\n {\n int[o] x;\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)\n // int[o];\n Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, \"[o]\").WithLocation(6, 12),\n // (6,13): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)\n // int[o];\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"o\").WithArguments(\"object\", \"int\").WithLocation(6, 13),\n // (6,16): warning CS0168: The variable 'x' is declared but never used\n // int[o] x;\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"x\").WithArguments(\"x\").WithLocation(6, 16));\n }\n\n [Fact]\n public void CS0269ERR_UseDefViolationOut()\n {\n var text = @\"\nclass C\n{\n public static void F(out int i)\n {\n try\n {\n // Assignment occurs, but compiler can't verify it\n i = 1;\n }\n catch\n {\n }\n\n int k = i; // CS0269\n i = 1;\n }\n\n public static void Main()\n {\n int myInt;\n F(out myInt);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationOut, Line = 15, Column = 17 } });\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter01()\n {\n var source =\n@\"class C\n{\n internal static object P { private get; set; }\n public C Q { protected get { return null; } set { } }\n}\nclass P\n{\n static void M(C c)\n {\n object o = C.P;\n M(c.Q);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,20): error CS0271: The property or indexer 'C.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"C.P\").WithArguments(\"C.P\").WithLocation(10, 20),\n // (11,11): error CS0271: The property or indexer 'C.Q' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"c.Q\").WithArguments(\"C.Q\").WithLocation(11, 11));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter02()\n {\n var source =\n@\"class A\n{\n public virtual object P { protected get; set; }\n}\nclass B : A\n{\n public override object P { set { } }\n void M()\n {\n object o = P; // no error\n }\n}\nclass C\n{\n void M(B b)\n {\n object o = b.P; // CS0271\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,20): error CS0271: The property or indexer 'B.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"b.P\").WithArguments(\"B.P\").WithLocation(17, 20));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter03()\n {\n var source =\n@\"namespace N1\n{\n class A\n {\n void M(N2.B b)\n {\n object o = b.P;\n }\n }\n}\nnamespace N2\n{\n class B : N1.A\n {\n public object P { protected get; set; }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,24): error CS0271: The property or indexer 'N2.B.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"b.P\").WithArguments(\"N2.B.P\").WithLocation(7, 24));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter04()\n {\n var source =\n@\"class A\n{\n static public object P { protected get; set; }\n static internal object Q { private get; set; }\n static void M()\n {\n object o = B.Q; // no error\n o = A.Q; // no error\n }\n}\nclass B : A\n{\n static void M()\n {\n object o = B.P; // no error\n o = P; // no error\n o = Q; // CS0271\n }\n}\nclass C\n{\n static void M()\n {\n object o = B.P; // CS0271\n o = A.Q; // CS0271\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"Q\").WithArguments(\"A.Q\").WithLocation(17, 13),\n // (24,20): error CS0271: The property or indexer 'A.P' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"B.P\").WithArguments(\"A.P\").WithLocation(24, 20),\n // (25,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"A.Q\").WithArguments(\"A.Q\").WithLocation(25, 13));\n }\n\n [Fact]\n public void CS0271ERR_InaccessibleGetter05()\n {\n CreateCompilation(\n@\"class A\n{\n public object this[int x] { protected get { return null; } set { } }\n internal object this[string s] { private get { return null; } set { } }\n void M()\n {\n object o = new B()[\"\"hello\"\"]; // no error\n o = new A()[\"\"hello\"\"]; // no error\n }\n}\nclass B : A\n{\n void M()\n {\n object o = new B()[0]; // no error\n o = this[0]; // no error\n o = this[\"\"hello\"\"]; // CS0271\n }\n}\nclass C\n{\n void M()\n {\n object o = new B()[0]; // CS0271\n o = new A()[\"\"hello\"\"]; // CS0271\n }\n}\")\n .VerifyDiagnostics(\n // (17,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, @\"this[\"\"hello\"\"]\").WithArguments(\"A.this[string]\"),\n // (24,20): error CS0271: The property or indexer 'A.this[int]' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"new B()[0]\").WithArguments(\"A.this[int]\"),\n // (25,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, @\"new A()[\"\"hello\"\"]\").WithArguments(\"A.this[string]\"));\n }\n\n [Fact]\n public void CS0272ERR_InaccessibleSetter01()\n {\n var source =\n@\"namespace N\n{\n class C\n {\n internal object P { get; private set; }\n static public C Q { get { return null; } protected set { } }\n }\n class P\n {\n static void M(C c)\n {\n c.P = c;\n C.Q = c;\n }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (12,13): error CS0272: The property or indexer 'N.C.P' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"c.P\").WithArguments(\"N.C.P\").WithLocation(12, 13),\n // (13,13): error CS0272: The property or indexer 'N.C.Q' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"C.Q\").WithArguments(\"N.C.Q\").WithLocation(13, 13));\n }\n\n [Fact]\n public void CS0272ERR_InaccessibleSetter02()\n {\n var source =\n@\"namespace N1\n{\n abstract class A\n {\n public virtual object P { get; protected set; }\n }\n}\nnamespace N2\n{\n class B : N1.A\n {\n public override object P { get { return null; } }\n void M()\n {\n P = null; // no error\n }\n }\n}\nclass C\n{\n void M(N2.B b)\n {\n b.P = null; // CS0272\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (23,9): error CS0272: The property or indexer 'N2.B.P' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"b.P\").WithArguments(\"N2.B.P\").WithLocation(23, 9));\n }\n\n [Fact]\n public void CS0272ERR_InaccessibleSetter03()\n {\n CreateCompilation(\n@\"namespace N1\n{\n abstract class A\n {\n public virtual object this[int x] { get { return null; } protected set { } }\n }\n}\nnamespace N2\n{\n class B : N1.A\n {\n public override object this[int x] { get { return null; } }\n void M()\n {\n this[0] = null; // no error\n }\n }\n}\nclass C\n{\n void M(N2.B b)\n {\n b[0] = null; // CS0272\n }\n}\n\")\n .VerifyDiagnostics(\n // (23,9): error CS0272: The property or indexer 'N2.B.this[int]' cannot be used in this context because the set accessor is inaccessible\n Diagnostic(ErrorCode.ERR_InaccessibleSetter, \"b[0]\").WithArguments(\"N2.B.this[int]\"));\n }\n\n [Fact]\n public void CS0283ERR_BadConstType()\n {\n // Test for both ERR_BadConstType and an error for RHS to ensure\n // the RHS is not reported multiple times (when calculating the\n // constant value for the symbol and also when binding).\n var source =\n@\"struct S\n{\n static void M(object o)\n {\n const S s = 2;\n M(s);\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,15): error CS0283: The type 'S' cannot be declared const\n // const S s = 2;\n Diagnostic(ErrorCode.ERR_BadConstType, \"S\").WithArguments(\"S\").WithLocation(5, 15),\n // (5,21): error CS0029: Cannot implicitly convert type 'int' to 'S'\n // const S s = 2;\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"2\").WithArguments(\"int\", \"S\").WithLocation(5, 21));\n }\n\n [Fact]\n public void CS0304ERR_NoNewTyvar01()\n {\n var source =\n@\"struct S where U : new()\n{\n void M()\n {\n object o;\n o = new T();\n o = new U();\n o = new V();\n }\n}\nclass C\n where T : struct\n where U : class\n{\n void M()\n where V : struct\n where W : class, new()\n {\n object o;\n o = new T();\n o = new U();\n o = new V();\n o = new W();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,13): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new T()\").WithArguments(\"T\").WithLocation(6, 13),\n // (8, 13): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new V()\").WithArguments(\"V\").WithLocation(8, 13),\n // (21,13): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new U()\").WithArguments(\"U\").WithLocation(21, 13));\n }\n\n [WorkItem(542377, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542377\")]\n [Fact]\n public void CS0304ERR_NoNewTyvar02()\n {\n var source =\n@\"struct S { }\nclass C { }\nabstract class A\n{\n public abstract U F() where U : T;\n}\nclass B1 : A\n{\n public override U F() { return new U(); }\n}\nclass B2 : A\n{\n public override U F() { return new U(); }\n}\nclass B3 : A\n{\n public override U F() { return new U(); }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (17,39): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint\n Diagnostic(ErrorCode.ERR_NoNewTyvar, \"new U()\").WithArguments(\"U\").WithLocation(17, 39));\n }\n\n [WorkItem(542547, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542547\")]\n [Fact]\n public void CS0305ERR_BadArity()\n {\n var text = @\"\npublic class NormalType\n{\n public static int M1(T1 p1, T1 p2) { return 0; }\n public static int Main()\n {\n M1(10, 11);\n return -1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,17): error CS1031: Type expected\n Diagnostic(ErrorCode.ERR_TypeExpected, \">\"),\n // (7,9): error CS0305: Using the generic method 'NormalType.M1(T1, T1)' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"M1\").WithArguments(\"NormalType.M1(T1, T1)\", \"method\", \"1\"));\n }\n\n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied01()\n {\n var text =\n@\"class A { }\nclass B\n{\n private B() { }\n}\ndelegate void D();\nenum E { }\nstruct S { }\nclass C where T : new()\n{\n static void M() where V : new()\n {\n M>();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n M();\n }\n static void M()\n where V : new()\n where W : new()\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"B\").WithLocation(14, 9),\n // (15,9): error CS0310: 'D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"D\").WithLocation(15, 9),\n // (21,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"U\").WithLocation(21, 9),\n // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"B\").WithLocation(22, 9),\n // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"W\", \"B\").WithLocation(22, 9),\n // (23,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"W\", \"U\").WithLocation(23, 9),\n // (25,9): error CS0310: 'T[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M()'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"V\", \"T[]\").WithLocation(25, 9));\n }\n\n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied02()\n {\n var text =\n@\"class A { }\nclass B\n{\n internal B() { }\n}\nclass C where T : new()\n{\n internal static void M() where U : new() { }\n internal static void E(D d) { } // Error: missing constraint on E to satisfy constraint on D\n}\ndelegate T D() where T : new();\nstatic class E\n{\n internal static void M(this object o) where T : new() { }\n internal static void F(D d) where T : new() { }\n}\nclass F where U : new()\n{\n}\nabstract class G { }\nclass H : G { }\ninterface I { }\nstruct S\n{\n private S(object o) { }\n static void M()\n {\n C.M();\n C.M();\n C.M();\n C.M();\n C.M();\n C.M();\n C.M();\n E.F(S.F);\n E.F(S.F);\n E.F(S.F>);\n E.F(S.F>);\n var o = new object();\n o.M();\n o.M();\n o = new F();\n o = new F();\n }\n static T F() { return default(T); }\n}\";\n\n // Note that none of these errors except the first one are reported by the native compiler, because\n // it does not report additional errors after an error is found in a formal parameter of a method.\n\n CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (9,36): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D'\n // internal static void E(D d) { } // Error: missing constraint on E to satisfy constraint on D\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"d\").WithArguments(\"D\", \"T\", \"U\").WithLocation(9, 36),\n // (29,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"U\", \"B\").WithLocation(29, 14),\n // (30,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"C\", \"T\", \"B\").WithLocation(30, 11),\n // (31,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"C\", \"T\", \"B\").WithLocation(31, 11),\n // (31,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"U\", \"B\").WithLocation(31, 14),\n // (32,11): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"G\").WithArguments(\"C\", \"T\", \"G\").WithLocation(32, 11),\n // (33,14): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M()\", \"U\", \"G\").WithLocation(33, 14),\n // (34,11): error CS0310: 'I' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"I\").WithArguments(\"C\", \"T\", \"I\").WithLocation(34, 11),\n // (36,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.F(D)'\n // E.F(S.F);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"F\").WithArguments(\"E.F(D)\", \"T\", \"B\").WithLocation(36, 11),\n // (38,19): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // E.F(S.F>);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"C\", \"T\", \"B\").WithLocation(38, 19),\n\n // This invocation of E.F(S.F>) is an extremely interesting one. \n\n // First off, obviously the type argument for S.F is prima facie wrong, so we give an error for that above.\n // But what about the overload resolution problem in error recovery? Even though the argument is bad we still\n // might want to try to get an overload resolution result. Thus we must infer a type for T in E.F(D). \n // We must do overload resolution on an invocation S.F>(). Overload resolution succeeds; it has no reason\n // to fail. (Overload resolution would fail if a formal parameter type of S.F>() did not satisfy one of its\n // constraints, but there are no formal parameters. Also, there are no constraints at all on T in S.F.)\n //\n // Thus T in D is inferred to be C, and thus T in E.F is inferred to be C. \n //\n // Now we check to see whether E.F>(D>) is applicable. It is inapplicable because\n // B fails to meet the constraints of T in C. (C does not fail to meet the constraints\n // of T in D because C has a public default parameterless ctor.)\n //\n // Therefore E.F(S.F>) fails overload resolution. Why? Because B is not valid for T in C.\n // (We cannot say that the constraints on T in E.F is unmet because again, C meets the\n // constraint; it has a ctor.) So that is the error we report.\n //\n // This is arguably a \"cascading\" error; we have already reported an error for C when the \n // argument was bound. Normally we avoid reporting \"cascading\" errors in overload resolution by\n // saying that an erroneous argument is implicitly convertible to any formal parameter type;\n // thus we avoid an erroneous expression from causing overload resolution to make every\n // candidate method inapplicable. (Though it might cause overload resolution to fail by making\n // every candidate method applicable, causing an ambiguity!) But the overload resolution \n // error here is not caused by an argument *conversion* in the first place; the overload\n // resolution error is caused because *the deduced formal parameter type is illegal.*\n //\n // We might want to put some gear in place to suppress this cascading error. It is not\n // entirely clear what that machinery might look like.\n\n // (38,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // E.F(S.F>);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"F\").WithArguments(\"C\", \"T\", \"B\").WithLocation(38, 11),\n\n // (41,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.M(object)'\n // o.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"E.M(object)\", \"T\", \"B\").WithLocation(41, 11),\n // (42,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'F'\n // o = new F();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"F\", \"U\", \"B\").WithLocation(42, 22));\n }\n\n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied03()\n {\n var text =\n@\"class A { }\nclass B\n{\n private B() { }\n}\nclass C where U : struct\n{\n internal static void M(V v) where V : new() { }\n void M()\n {\n A a = default(A);\n M(a);\n a.E();\n B b = default(B);\n M(b);\n b.E();\n T t = default(T);\n M(t);\n t.E();\n U u1 = default(U);\n M(u1);\n u1.E();\n U? u2 = null;\n M(u2);\n u2.E();\n }\n}\nstatic class S\n{\n internal static void E(this T t) where T : new() { }\n}\";\n CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (15,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M(V)'\n // M(b);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M(V)\", \"V\", \"B\").WithLocation(15, 9),\n // (16,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E(T)'\n // b.E();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"E\").WithArguments(\"S.E(T)\", \"T\", \"B\").WithLocation(16, 11),\n // (18,9): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C.M(V)'\n // M(t);\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"C.M(V)\", \"V\", \"T\").WithLocation(18, 9),\n // (19,11): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E(T)'\n // t.E();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"E\").WithArguments(\"S.E(T)\", \"T\", \"T\").WithLocation(19, 11)\n);\n }\n\n /// \n /// Constraint errors within aliases.\n /// \n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied04()\n {\n var text =\n@\"using NA = N.A;\nusing NB = N.B;\nusing CA = N.C;\nusing CB = N.C;\nnamespace N\n{\n using CAD = C.D;\n using CBD = C.D;\n class A { } // public (default) .ctor\n class B { private B() { } } // private .ctor\n class C where T : new()\n {\n internal static void M() where U : new() { }\n internal class D\n {\n private D() { } // private .ctor\n internal static void M() where U : new() { }\n }\n }\n class E\n {\n static void M()\n {\n C.M();\n C.M();\n C.D>.M();\n C.D.M();\n C.D.M();\n CA.M();\n CB.M();\n CAD.M();\n CBD.M();\n C.M();\n C.M();\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,7): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // using CB = N.C;\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CB\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(4, 7),\n // (8,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // using CBD = C.D;\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CBD\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(8, 11),\n // (24,20): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.M()\", \"U\", \"N.B\").WithLocation(24, 20),\n // (25,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"NB\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(25, 15),\n // (26,15): error CS0310: 'C.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.D>.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"C.D\").WithArguments(\"N.C\", \"T\", \"N.C.D\").WithLocation(26, 15),\n // (27,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.D.M()'\n // C.D.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.D.M()\", \"U\", \"N.B\").WithLocation(27, 22),\n // (28,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.D.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"N.B\").WithArguments(\"N.C\", \"T\", \"N.B\").WithLocation(28, 15),\n // (29,16): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.M()'\n // CA.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.M()\", \"U\", \"N.B\").WithLocation(29, 16),\n // (31,17): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C.D.M()'\n // CAD.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"M\").WithArguments(\"N.C.D.M()\", \"U\", \"N.B\").WithLocation(31, 17),\n // (33,15): error CS0310: 'C.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CAD\").WithArguments(\"N.C\", \"T\", \"N.C.D\").WithLocation(33, 15),\n // (34,15): error CS0310: 'C.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C'\n // C.M();\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"CBD\").WithArguments(\"N.C\", \"T\", \"N.C.D\").WithLocation(34, 15));\n }\n\n /// \n /// Constructors with optional and params args\n /// should not be considered parameterless.\n /// \n [Fact]\n public void CS0310ERR_NewConstraintNotSatisfied05()\n {\n var text =\n@\"class A\n{\n public A() { }\n}\nclass B\n{\n public B(object o = null) { }\n}\nclass C\n{\n public C(params object[] args) { }\n}\nclass D where T : new()\n{\n static void M()\n {\n D.M();\n D.M();\n D.M();\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"B\").WithArguments(\"D\", \"T\", \"B\").WithLocation(18, 11),\n // (19,11): error CS0310: 'C' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D'\n Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, \"C\").WithArguments(\"D\", \"T\", \"C\").WithLocation(19, 11));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType01()\n {\n var source =\n@\"class A { }\nclass B { }\nclass C where T : A { }\nclass D\n{\n static void M() where T : A { }\n static void M()\n {\n object o = new C();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,26): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C'. There is no implicit reference conversion from 'B' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"B\").WithArguments(\"C\", \"A\", \"T\", \"B\").WithLocation(9, 26),\n // (10,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'D.M()'. There is no implicit reference conversion from 'B' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"M\").WithArguments(\"D.M()\", \"A\", \"T\", \"B\").WithLocation(10, 9));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType02()\n {\n var source =\n@\"class C where U : T\n{\n void M() where V : C { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,12): error CS0311: The type 'V' cannot be used as type parameter 'U' in the generic type or method 'C'. There is no implicit reference conversion from 'V' to 'T'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"V\").WithArguments(\"C\", \"T\", \"U\", \"V\").WithLocation(3, 12));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType03()\n {\n var source =\n@\"interface I where T : I> { }\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,13): error CS0311: The type 'I' cannot be used as type parameter 'T' in the generic type or method 'I'. There is no implicit reference conversion from 'I' to 'I>>'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"T\").WithArguments(\"I\", \"I>>\", \"T\", \"I\").WithLocation(1, 13));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType04()\n {\n var source =\n@\"interface IA { }\ninterface IB where T : IA { }\nclass C\n where T1 : IB\n where T2 : IB\n where T3 : IB[]>, IA\n{\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,9): error CS0311: The type 'object[]' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no implicit reference conversion from 'object[]' to 'IA'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"T1\").WithArguments(\"IB\", \"IA\", \"T\", \"object[]\").WithLocation(3, 9),\n // (3,13): error CS0311: The type 'T2' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no boxing conversion or type parameter conversion from 'T2' to 'IA'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T2\").WithArguments(\"IB\", \"IA\", \"T\", \"T2\").WithLocation(3, 13),\n // (3,17): error CS0311: The type 'IB[]' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no implicit reference conversion from 'IB[]' to 'IA[]>'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"T3\").WithArguments(\"IB\", \"IA[]>\", \"T\", \"IB[]\").WithLocation(3, 17));\n }\n\n [Fact]\n public void CS0311ERR_GenericConstraintNotSatisfiedRefType05()\n {\n var source =\n@\"namespace N\n{\n class C where U : T\n {\n static object F()\n {\n return null;\n }\n static object G() where V : T\n {\n return null;\n }\n static void M()\n {\n object o;\n o = C.F();\n o = N.C.G();\n }\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,24): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'C'. There is no implicit reference conversion from 'object' to 'int'.\n // o = C.F();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"object\").WithArguments(\"N.C\", \"int\", \"U\", \"object\").WithLocation(16, 24),\n // (17,31): error CS0311: The type 'string' cannot be used as type parameter 'V' in the generic type or method 'C.G()'. There is no implicit reference conversion from 'string' to 'int'.\n // o = N.C.G();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, \"G\").WithArguments(\"N.C.G()\", \"int\", \"V\", \"string\").WithLocation(17, 31));\n }\n\n [Fact]\n public void CS0312ERR_GenericConstraintNotSatisfiedNullableEnum()\n {\n var source =\n@\"class A where T : U { }\nclass B\n{\n static void M() where U : T { }\n static void M()\n {\n object o = new A();\n B.M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,26): error CS0312: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A'. The nullable type 'int?' does not satisfy the constraint of 'int'.\n // object o = new A();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, \"int?\").WithArguments(\"A\", \"int\", \"T\", \"int?\").WithLocation(7, 26),\n // (8,16): error CS0312: The type 'int?' cannot be used as type parameter 'U' in the generic type or method 'B.M()'. The nullable type 'int?' does not satisfy the constraint of 'int'.\n // B.M();\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, \"M\").WithArguments(\"B.M()\", \"int\", \"U\", \"int?\").WithLocation(8, 16));\n }\n\n [Fact]\n public void CS0313ERR_GenericConstraintNotSatisfiedNullableInterface()\n {\n var source =\n@\"interface I { }\nstruct S : I { }\nclass A where T : I { }\nclass B\n{\n static void M() where T : I { }\n static void M()\n {\n object o = new A();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,26): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'A'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, \"S?\").WithArguments(\"A\", \"I\", \"T\", \"S?\").WithLocation(9, 26),\n // (10,9): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'B.M()'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, \"M\").WithArguments(\"B.M()\", \"I\", \"T\", \"S?\").WithLocation(10, 9));\n }\n\n [Fact]\n public void CS0314ERR_GenericConstraintNotSatisfiedTyVar01()\n {\n var source =\n@\"class A { }\nclass B where T : A { }\nclass C where T : struct\n{\n static void M() where U : A { }\n static void M()\n {\n object o = new B();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,26): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B'. There is no boxing conversion or type parameter conversion from 'T' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T\").WithArguments(\"B\", \"A\", \"T\", \"T\").WithLocation(8, 26),\n // (9,9): error CS0314: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'C.M()'. There is no boxing conversion or type parameter conversion from 'T' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"M\").WithArguments(\"C.M()\", \"A\", \"U\", \"T\").WithLocation(9, 9));\n }\n\n [Fact]\n public void CS0314ERR_GenericConstraintNotSatisfiedTyVar02()\n {\n var source =\n@\"class C where U : T\n{\n void M() where V : C { }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,12): error CS0314: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'C'. There is no boxing conversion or type parameter conversion from 'U' to 'V'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"V\").WithArguments(\"C\", \"V\", \"U\", \"U\").WithLocation(3, 12));\n }\n\n [Fact]\n public void CS0314ERR_GenericConstraintNotSatisfiedTyVar03()\n {\n var source =\n@\"interface IA where T : IB { }\ninterface IB where T : IA { }\";\n CreateCompilation(source).VerifyDiagnostics(\n // (1,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IB'. There is no boxing conversion or type parameter conversion from 'T' to 'IA'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T\").WithArguments(\"IB\", \"IA\", \"T\", \"T\").WithLocation(1, 14),\n // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IA'. There is no boxing conversion or type parameter conversion from 'T' to 'IB'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, \"T\").WithArguments(\"IA\", \"IB\", \"T\", \"T\").WithLocation(2, 14));\n }\n\n [Fact]\n public void CS0315ERR_GenericConstraintNotSatisfiedValType()\n {\n var source =\n@\"class A { }\nclass B where T : A { }\nstruct S { }\nclass C\n{\n static void M() where U : A { }\n static void M()\n {\n object o = new B();\n M();\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,26): error CS0315: The type 'S' cannot be used as type parameter 'T' in the generic type or method 'B'. There is no boxing conversion from 'S' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, \"S\").WithArguments(\"B\", \"A\", \"T\", \"S\").WithLocation(9, 26),\n // (10,9): error CS0315: The type 'double?' cannot be used as type parameter 'U' in the generic type or method 'C.M()'. There is no boxing conversion from 'double?' to 'A'.\n Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, \"M\").WithArguments(\"C.M()\", \"A\", \"U\", \"double\").WithLocation(10, 9));\n }\n\n [Fact]\n public void CS0316ERR_DuplicateGeneratedName()\n {\n var text = @\"\npublic class Test\n{\n public int this[int value] // CS0316\n {\n get { return 1; }\n set { }\n }\n\n public int this[char @value] // CS0316\n {\n get { return 1; }\n set { }\n }\n\n public int this[string value] // no error since no setter\n {\n get { return 1; }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,26): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name\n // public int this[char @value] // CS0316\n Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, \"@value\").WithArguments(\"value\").WithLocation(10, 26),\n // (4,25): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name\n // public int this[int value] // CS0316\n Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, \"value\").WithArguments(\"value\").WithLocation(4, 25));\n }\n\n [Fact]\n public void CS0403ERR_TypeVarCantBeNull()\n {\n var source =\n@\"interface I { }\nclass A { }\nclass B\n where T2 : class\n where T3 : struct\n where T4 : new()\n where T5 : I\n where T6 : A\n where T7 : T1\n{\n static void M()\n {\n T1 t1 = null;\n T2 t2 = null;\n T3 t3 = null;\n T4 t4 = null;\n T5 t5 = null;\n T6 t6 = null;\n T7 t7 = null;\n }\n static T1 F1() { return null; }\n static T2 F2() { return null; }\n static T3 F3() { return null; }\n static T4 F4() { return null; }\n static T5 F5() { return null; }\n static T6 F6() { return null; }\n static T7 F7() { return null; }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,17): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead.\n // T1 t1 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T1\"),\n // (15,17): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead.\n // T3 t3 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T3\"),\n // (16,17): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead.\n // T4 t4 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T4\"),\n // (17,17): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead.\n // T5 t5 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T5\"),\n // (19,17): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead.\n // T7 t7 = null;\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T7\"),\n // (14,12): warning CS0219: The variable 't2' is assigned but its value is never used\n // T2 t2 = null;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"t2\").WithArguments(\"t2\"),\n // (18,12): warning CS0219: The variable 't6' is assigned but its value is never used\n // T6 t6 = null;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"t6\").WithArguments(\"t6\"),\n // (21,29): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead.\n // static T1 F1() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T1\"),\n // (23,29): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead.\n // static T3 F3() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T3\"),\n // (24,29): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead.\n // static T4 F4() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T4\"),\n // (25,29): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead.\n // static T5 F5() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T5\"),\n // (27,29): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead.\n // static T7 F7() { return null; }\n Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, \"null\").WithArguments(\"T7\")\n );\n }\n\n [WorkItem(539901, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539901\")]\n [Fact]\n public void CS0407ERR_BadRetType_01()\n {\n var text = @\"\npublic delegate int MyDelegate();\n\nclass C\n{\n MyDelegate d;\n\n public C()\n {\n d = new MyDelegate(F); // OK: F returns int\n d = new MyDelegate(G); // CS0407 - G doesn't return int\n }\n\n public int F()\n {\n return 1;\n }\n\n public void G()\n {\n }\n\n public static void Main()\n {\n C c1 = new C();\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(\n // (11,28): error CS0407: 'void C.G()' has the wrong return type\n // d = new MyDelegate(G); // CS0407 - G doesn't return int\n Diagnostic(ErrorCode.ERR_BadRetType, \"G\").WithArguments(\"C.G()\", \"void\").WithLocation(11, 28)\n );\n CreateCompilation(text).VerifyDiagnostics(\n // (11,28): error CS0407: 'void C.G()' has the wrong return type\n // d = new MyDelegate(G); // CS0407 - G doesn't return int\n Diagnostic(ErrorCode.ERR_BadRetType, \"G\").WithArguments(\"C.G()\", \"void\").WithLocation(11, 28)\n );\n }\n\n [WorkItem(925899, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925899\")]\n [Fact]\n public void CS0407ERR_BadRetType_02()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n public static void Main()\n {\n var oo = new Func(x => 1);\n \n var os = new Func(oo);\n var ss = new Func(oo);\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(\n // (10,43): error CS0407: 'object System.Func.Invoke(object)' has the wrong return type\n // var os = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(10, 43),\n // (11,43): error CS0407: 'object System.Func.Invoke(object)' has the wrong return type\n // var ss = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(11, 43)\n );\n CreateCompilation(text).VerifyDiagnostics(\n // (10,43): error CS0407: 'object Func.Invoke(object)' has the wrong return type\n // var os = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(10, 43),\n // (11,43): error CS0407: 'object Func.Invoke(object)' has the wrong return type\n // var ss = new Func(oo);\n Diagnostic(ErrorCode.ERR_BadRetType, \"oo\").WithArguments(\"System.Func.Invoke(object)\", \"object\").WithLocation(11, 43)\n );\n }\n\n [WorkItem(539924, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539924\")]\n [Fact]\n public void CS0407ERR_BadRetType_03()\n {\n var text = @\"\ndelegate DerivedClass MyDerivedDelegate(DerivedClass x);\npublic class BaseClass\n{\n public static BaseClass DelegatedMethod(BaseClass x)\n {\n System.Console.WriteLine(\"\"Base\"\");\n return x;\n }\n}\npublic class DerivedClass : BaseClass\n{\n public static DerivedClass DelegatedMethod(DerivedClass x)\n {\n System.Console.WriteLine(\"\"Derived\"\");\n return x;\n }\n static void Main(string[] args)\n {\n MyDerivedDelegate goo1 = null;\n goo1 += BaseClass.DelegatedMethod;\n goo1 += DerivedClass.DelegatedMethod;\n goo1(new DerivedClass());\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (21,17): error CS0407: 'BaseClass BaseClass.DelegatedMethod(BaseClass)' has the wrong return type\n Diagnostic(ErrorCode.ERR_BadRetType, \"BaseClass.DelegatedMethod\").WithArguments(\"BaseClass.DelegatedMethod(BaseClass)\", \"BaseClass\"));\n }\n\n [WorkItem(3401, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0411ERR_CantInferMethTypeArgs01()\n {\n var text = @\"\nclass C\n{\n public void F(T t) where T : C \n {\n }\n\n public static void Main()\n {\n C c = new C();\n c.F(null); // CS0411\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantInferMethTypeArgs, Line = 11, Column = 11 } });\n }\n\n [WorkItem(2099, \"https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2099\")]\n [Fact(Skip = \"529560\")]\n public void CS0411ERR_CantInferMethTypeArgs02()\n {\n var text = @\"\npublic class MemberInitializerTest\n{\n delegate void D();\n public static void GenericMethod() { }\n public static void Run()\n {\n var genD = (D)GenericMethod;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,20): error CS0030: The type arguments for method 'MemberInitializerTest.GenericMethod()' cannot be inferred from the usage. Try specifying the type arguments explicitly.\n // var genD = (D)GenericMethod;\n Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, \"(D)GenericMethod\").WithArguments(\"MemberInitializerTest.GenericMethod()\")\n );\n }\n\n [Fact]\n public void CS0412ERR_LocalSameNameAsTypeParam()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n // Parameter name is the same as method type parameter name\n public void G(int T) // CS0412\n {\n }\n public void F()\n {\n // Method local variable name is the same as method type\n // parameter name\n double T = 0.0; // CS0412\n Console.WriteLine(T);\n }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 7, Column = 26 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 14, Column = 16 } });\n }\n\n [Fact]\n public void CS0413ERR_AsWithTypeVar()\n {\n var source =\n@\"interface I { }\nclass A { }\nclass B\n where T2 : class\n where T3 : struct\n where T4 : new()\n where T5 : I\n where T6 : A\n where T7 : T1\n{\n static void M(object o)\n {\n o = o as T1;\n o = o as T2;\n o = o as T3;\n o = o as T4;\n o = o as T5;\n o = o as T6;\n o = o as T7;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,13): error CS0413: The type parameter 'T1' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T1\").WithArguments(\"T1\").WithLocation(13, 13),\n // (15,13): error CS0413: The type parameter 'T3' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T3\").WithArguments(\"T3\").WithLocation(15, 13),\n // (16,13): error CS0413: The type parameter 'T4' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T4\").WithArguments(\"T4\").WithLocation(16, 13),\n // (17,13): error CS0413: The type parameter 'T5' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T5\").WithArguments(\"T5\").WithLocation(17, 13),\n // (19,13): error CS0413: The type parameter 'T7' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint\n Diagnostic(ErrorCode.ERR_AsWithTypeVar, \"o as T7\").WithArguments(\"T7\").WithLocation(19, 13));\n }\n\n [Fact]\n public void CS0417ERR_NewTyvarWithArgs01()\n {\n var source =\n@\"struct S where T : new()\n{\n T F(object o)\n {\n return new T(o);\n }\n U G(object o)\n where U : new()\n where V : struct\n {\n return new U(new V(o));\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,16): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new T(o)\").WithArguments(\"T\").WithLocation(5, 16),\n // (11,16): error CS0417: 'U': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new U(new V(o))\").WithArguments(\"U\").WithLocation(11, 16),\n // (11,22): error CS0417: 'V': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new V(o)\").WithArguments(\"V\").WithLocation(11, 22));\n }\n\n [Fact]\n public void CS0417ERR_NewTyvarWithArgs02()\n {\n var source =\n@\"class C\n{\n public C() { }\n public C(object o) { }\n static void M() where T : C, new()\n {\n new T();\n new T(null);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,9): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type\n Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, \"new T(null)\").WithArguments(\"T\").WithLocation(8, 9));\n }\n\n [Fact]\n public void CS0428ERR_MethGrpToNonDel()\n {\n var text = @\"\nnamespace ConsoleApplication1\n{\n class Program\n {\n delegate int Del1();\n delegate object Del2();\n\n static void Main(string[] args)\n {\n ExampleClass ec = new ExampleClass();\n int i = ec.Method1;\n Del1 d1 = ec.Method1;\n i = ec.Method1();\n ec = ExampleClass.Method2;\n Del2 d2 = ExampleClass.Method2;\n ec = ExampleClass.Method2();\n }\n }\n\n public class ExampleClass\n {\n public int Method1() { return 1; }\n public static ExampleClass Method2() { return null; }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 12, Column = 24 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 15, Column = 31 }});\n }\n\n [Fact, WorkItem(528649, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528649\")]\n public void CS0431ERR_ColColWithTypeAlias()\n {\n var text = @\"\nusing AliasC = C;\nclass C\n{\n public class Goo { }\n}\nclass Test\n{\n class C { }\n static int Main()\n {\n AliasC::Goo goo = new AliasC::Goo();\n return 0;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, \"AliasC\").WithArguments(\"AliasC\"),\n Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, \"AliasC\").WithArguments(\"AliasC\"));\n }\n\n [WorkItem(3402, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0445ERR_UnboxNotLValue()\n {\n var text = @\"\nnamespace ConsoleApplication1\n{\n // CS0445.CS\n class UnboxingTest\n {\n public static void Main()\n {\n Point p = new Point();\n p.x = 1;\n p.y = 5;\n object obj = p;\n\n // Generates CS0445:\n ((Point)obj).x = 2;\n }\n }\n\n public struct Point\n {\n public int x;\n public int y;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnboxNotLValue, Line = 15, Column = 13 } });\n }\n\n [Fact]\n public void CS0446ERR_AnonMethGrpInForEach()\n {\n var text = @\"\nclass Tester \n{\n static void Main() \n {\n int[] intArray = new int[5];\n foreach (int i in M) { } // CS0446\n }\n static void M() { }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethGrpInForEach, Line = 7, Column = 27 } });\n }\n\n [Fact]\n [WorkItem(36203, \"https://github.com/dotnet/roslyn/issues/36203\")]\n public void CS0452_GenericConstraintError_HasHigherPriorityThanMethodOverloadError()\n {\n var code = @\"\nclass Code\n{\n void GenericMethod(int i) where T: class => throw null;\n void GenericMethod(string s) => throw null;\n\n void IncorrectMethodCall()\n {\n GenericMethod(1);\n }\n}\";\n CreateCompilation(code).VerifyDiagnostics(\n // (9,9): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Code.GenericMethod(int)'\n Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, \"GenericMethod\").WithArguments(\"Code.GenericMethod(int)\", \"T\", \"int\").WithLocation(9, 9));\n }\n\n [Fact]\n public void CS0457ERR_AmbigUDConv()\n {\n var text = @\"\npublic class A { }\n\npublic class G0 { }\npublic class G1 : G0 { }\n\npublic class H0 {\n public static implicit operator G0(H0 h) {\n return new G0();\n }\n}\npublic class H1 : H0 {\n public static implicit operator G1(H1 h) {\n return new G1();\n }\n}\n\npublic class Test \n{\n public static void F0(G0 g) { }\n public static void Main() \n {\n H1 h1a = new H1();\n F0(h1a); // CS0457\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (24,10): error CS0457: Ambiguous user defined conversions 'H1.implicit operator G1(H1)' and 'H0.implicit operator G0(H0)' when converting from 'H1' to 'G0'\n Diagnostic(ErrorCode.ERR_AmbigUDConv, \"h1a\").WithArguments(\"H1.implicit operator G1(H1)\", \"H0.implicit operator G0(H0)\", \"H1\", \"G0\"));\n }\n\n [WorkItem(22306, \"https://github.com/dotnet/roslyn/issues/22306\")]\n [Fact]\n public void AddrOnReadOnlyLocal()\n {\n var text = @\"\nclass A\n{\n public unsafe void M1()\n {\n int[] ints = new int[] { 1, 2, 3 };\n foreach (int i in ints)\n {\n int *j = &i; \n }\n\n fixed (int *i = &_i)\n {\n int **j = &i; \n }\n }\n\n private int _i = 0;\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0463ERR_DecConstError()\n {\n var text = @\"\nusing System; \nclass MyClass \n{\n public static void Main() \n {\n const decimal myDec = 79000000000000000000000000000.0m + 79000000000000000000000000000.0m; // CS0463\n Console.WriteLine(myDec.ToString());\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DecConstError, Line = 7, Column = 31 } });\n }\n\n [WorkItem(543272, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543272\")]\n [Fact]\n public void CS0463ERR_DecConstError_02()\n {\n var text = @\"\nclass MyClass \n{\n public static void Main() \n {\n decimal x1 = decimal.MaxValue + 1; // CS0463\n decimal x2 = decimal.MaxValue + decimal.One; // CS0463\n decimal x3 = decimal.MinValue - decimal.One; // CS0463\n decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463\n decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 \n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x1 = decimal.MaxValue + 1; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MaxValue + 1\"),\n // (7,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x2 = decimal.MaxValue + decimal.One; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MaxValue + decimal.One\"),\n // (8,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x3 = decimal.MinValue - decimal.One; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MinValue - decimal.One\"),\n // (9,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463\n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MinValue + decimal.MinusOne\"),\n // (10,22): error CS0463: Evaluation of the decimal constant expression failed\n // decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 \n Diagnostic(ErrorCode.ERR_DecConstError, \"decimal.MaxValue - decimal.MinValue\"));\n }\n\n [Fact()]\n public void CS0471ERR_TypeArgsNotAllowedAmbig()\n {\n var text = @\"\nclass Test\n{\n public void F(bool x, bool y) {}\n public void F1()\n {\n int a = 1, b = 2, c = 3;\n F(a(3)); // CS0471\n // To resolve, try the following instead:\n // F((a(3));\n }\n}\n\n\";\n //Dev11 used to give 'The {1} '{0}' is not a generic method. If you intended an expression list, use parentheses around the &lt; expression.'\n //Roslyn will be satisfied with something less helpful.\n\n var noWarns = new Dictionary();\n noWarns.Add(MessageProvider.Instance.GetIdForErrorCode(219), ReportDiagnostic.Suppress);\n\n CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(noWarns)).VerifyDiagnostics(\n // (8,13): error CS0118: 'b' is a variable but is used like a type\n // F(a(3)); // CS0471\n Diagnostic(ErrorCode.ERR_BadSKknown, \"b\").WithArguments(\"b\", \"variable\", \"type\"),\n // (8,16): error CS0118: 'c' is a variable but is used like a type\n // F(a(3)); // CS0471\n Diagnostic(ErrorCode.ERR_BadSKknown, \"c\").WithArguments(\"c\", \"variable\", \"type\"),\n // (8,11): error CS0307: The variable 'a' cannot be used with type arguments\n // F(a(3)); // CS0471\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"a\").WithArguments(\"a\", \"variable\"));\n }\n\n [Fact]\n public void CS0516ERR_RecursiveConstructorCall()\n {\n var text = @\"\nnamespace x\n{\n public class clx\n {\n public clx() : this() // CS0516\n {\n }\n\n public static void Main()\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,22): error CS0516: Constructor 'x.clx.clx()' cannot call itself\n Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, \"this\").WithArguments(\"x.clx.clx()\"));\n }\n\n [WorkItem(751825, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751825\")]\n [Fact]\n public void Repro751825()\n {\n var text = @\"\npublic class A : A\n{\n public A() : base() { }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (2,18): error CS0308: The non-generic type 'A' cannot be used with type arguments\n // public class A : A\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"A\").WithArguments(\"A\", \"type\"),\n // (4,18): error CS0516: Constructor 'A.A()' cannot call itself\n // public A() : base() { }\n Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, \"base\").WithArguments(\"A.A()\"));\n }\n\n [WorkItem(366, \"https://github.com/dotnet/roslyn/issues/366\")]\n [Fact]\n public void IndirectConstructorCycle()\n {\n var text = @\"\npublic class A\n{\n public A() : this(1) {}\n public A(int x) : this(string.Empty) {}\n public A(string s) : this(1) {}\n public A(long l) : this(double.MaxValue) {}\n public A(double d) : this(char.MaxValue) {}\n public A(char c) : this(long.MaxValue) {}\n public A(short s) : this() {}\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,24): error CS0768: Constructor 'A.A(string)' cannot call itself through another constructor\n // public A(string s) : this(1) {}\n Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, \": this(1)\").WithArguments(\"A.A(string)\").WithLocation(6, 24),\n // (9,22): error CS0768: Constructor 'A.A(char)' cannot call itself through another constructor\n // public A(char c) : this(long.MaxValue) {}\n Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, \": this(long.MaxValue)\").WithArguments(\"A.A(char)\").WithLocation(9, 22)\n );\n }\n\n [Fact]\n public void CS0517ERR_ObjectCallingBaseConstructor()\n {\n var text = @\"namespace System\n{\n public class Void { } //just need the type to be defined\n\n public class Object\n {\n public Object() : base() { }\n }\n}\n\";\n CreateEmptyCompilation(text).VerifyDiagnostics(\n // (7,16): error CS0517: 'object' has no base class and cannot call a base constructor\n Diagnostic(ErrorCode.ERR_ObjectCallingBaseConstructor, \"Object\").WithArguments(\"object\"));\n }\n\n [Fact]\n public void CS0522ERR_StructWithBaseConstructorCall()\n {\n var text = @\"\npublic class clx\n{\n public clx(int i)\n {\n }\n\n public static void Main()\n {\n }\n}\n\npublic struct cly\n{\n public cly(int i):base(0) // CS0522\n // try the following line instead\n // public cly(int i)\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,11): error CS0522: 'cly': structs cannot call base class constructors\n Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, \"cly\").WithArguments(\"cly\"));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow01()\n {\n var source =\n@\"enum E\n{\n A = int.MaxValue - 1,\n B,\n C, // CS0543\n D,\n E = C,\n F,\n G = B,\n H, // CS0543\n I\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (5,5): error CS0543: 'E.C': the enumerator value is too large to fit in its type\n // C, // CS0543\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"C\").WithArguments(\"E.C\").WithLocation(5, 5),\n // (10,5): error CS0543: 'E.H': the enumerator value is too large to fit in its type\n // H, // CS0543\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"H\").WithArguments(\"E.H\").WithLocation(10, 5));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow02()\n {\n var source =\n@\"namespace N\n{\n enum E : byte { A = 255, B, C }\n enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D }\n enum G : int { X = int.MinValue, Y = X - 1, Z }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,30): error CS0543: 'E.B': the enumerator value is too large to fit in its type\n // enum E : byte { A = 255, B, C }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"B\").WithArguments(\"N.E.B\").WithLocation(3, 30),\n // (5,42): error CS0220: The operation overflows at compile time in checked mode\n // enum G : int { X = int.MinValue, Y = X - 1, Z }\n Diagnostic(ErrorCode.ERR_CheckedOverflow, \"X - 1\").WithLocation(5, 42),\n // (4,57): error CS0543: 'F.D': the enumerator value is too large to fit in its type\n // enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"D\").WithArguments(\"N.F.D\").WithLocation(4, 57));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow03()\n {\n var source =\n@\"enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K }\nenum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K }\nenum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K }\nenum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K }\nenum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H }\nenum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H }\nenum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H }\nenum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H }\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,84): error CS0543: 'S32.J': the enumerator value is too large to fit in its type\n // enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S32.J\").WithLocation(3, 84),\n // (4,87): error CS0543: 'S64.J': the enumerator value is too large to fit in its type\n // enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S64.J\").WithLocation(4, 87),\n // (7,61): error CS0543: 'U32.G': the enumerator value is too large to fit in its type\n // enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U32.G\").WithLocation(7, 61),\n // (6,65): error CS0543: 'U16.G': the enumerator value is too large to fit in its type\n // enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U16.G\").WithLocation(6, 65),\n // (5,60): error CS0543: 'U8.G': the enumerator value is too large to fit in its type\n // enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U8.G\").WithLocation(5, 60),\n // (2,90): error CS0543: 'S16.J': the enumerator value is too large to fit in its type\n // enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S16.J\").WithLocation(2, 90),\n // (1,89): error CS0543: 'S8.J': the enumerator value is too large to fit in its type\n // enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"J\").WithArguments(\"S8.J\").WithLocation(1, 89),\n // (8,63): error CS0543: 'U64.G': the enumerator value is too large to fit in its type\n // enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"G\").WithArguments(\"U64.G\").WithLocation(8, 63));\n }\n\n [Fact]\n public void CS0543ERR_EnumeratorOverflow04()\n {\n string source = string.Format(\n@\"enum A {0}\nenum B : byte {1}\nenum C : byte {2}\nenum D : sbyte {3}\",\n CreateEnumValues(300, \"E\"),\n CreateEnumValues(256, \"E\"),\n CreateEnumValues(300, \"E\"),\n CreateEnumValues(300, \"E\", sbyte.MinValue));\n\n CreateCompilation(source).VerifyDiagnostics(\n // (3,1443): error CS0543: 'C.E256': the enumerator value is too large to fit in its type\n // enum C : byte { E0, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"E256\").WithArguments(\"C.E256\").WithLocation(3, 1443),\n // (4,1451): error CS0543: 'D.E256': the enumerator value is too large to fit in its type\n // enum D : sbyte { E0 = -128, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, }\n Diagnostic(ErrorCode.ERR_EnumeratorOverflow, \"E256\").WithArguments(\"D.E256\").WithLocation(4, 1451));\n }\n\n // Create string \"{ E0, E1, ..., En }\"\n private static string CreateEnumValues(int count, string prefix, int? initialValue = null)\n {\n var builder = new System.Text.StringBuilder(\"{ \");\n for (int i = 0; i < count; i++)\n {\n builder.Append(prefix);\n builder.Append(i);\n if ((i == 0) && (initialValue != null))\n {\n builder.AppendFormat(\" = {0}\", initialValue.Value);\n }\n builder.Append(\", \");\n }\n builder.Append(\" }\");\n return builder.ToString();\n }\n\n // CS0570 --> Symbols\\OverriddenOrHiddenMembersTests.cs\n\n [Fact]\n public void CS0571ERR_CantCallSpecialMethod01()\n {\n var source =\n@\"class C\n{\n protected virtual object P { get; set; }\n static object Q { get; set; }\n void M(D d)\n {\n this.set_P(get_Q());\n D.set_Q(d.get_P());\n ((this.get_P))();\n }\n}\nclass D : C\n{\n protected override object P { get { return null; } set { } }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,20): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor\n // this.set_P(get_Q());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_Q\").WithArguments(\"C.Q.get\").WithLocation(7, 20),\n // (7,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor\n // this.set_P(get_Q());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_P\").WithArguments(\"C.P.set\").WithLocation(7, 14),\n // (8,19): error CS0571: 'D.P.get': cannot explicitly call operator or accessor\n // D.set_Q(d.get_P());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_P\").WithArguments(\"D.P.get\").WithLocation(8, 19),\n // (8,11): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor\n // D.set_Q(d.get_P());\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_Q\").WithArguments(\"C.Q.set\").WithLocation(8, 11),\n // (9,16): error CS0571: 'C.P.get': cannot explicitly call operator or accessor\n // ((this.get_P))();\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_P\").WithArguments(\"C.P.get\").WithLocation(9, 16));\n\n // CONSIDER: Dev10 reports 'C.P.get' for the fourth error. Roslyn reports 'D.P.get'\n // because it is in the more-derived type and because Binder.LookupMembersInClass\n // calls MergeHidingLookups(D.P.get, C.P.get) with both arguments non-viable\n // (i.e. keeps current, since new value isn't better).\n }\n\n [Fact]\n public void CS0571ERR_CantCallSpecialMethod02()\n {\n var source =\n@\"using System;\nnamespace A.B\n{\n class C\n {\n object P { get; set; }\n static object Q { get { return 0; } set { } }\n void M(C c)\n {\n Func f = get_P;\n f = C.get_Q;\n Action a = c.set_P;\n a = set_Q;\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,30): error CS0571: 'C.P.get': cannot explicitly call operator or accessor\n // Func f = get_P;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_P\").WithArguments(\"A.B.C.P.get\").WithLocation(10, 30),\n // (11,19): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor\n // f = C.get_Q;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"get_Q\").WithArguments(\"A.B.C.Q.get\").WithLocation(11, 19),\n // (12,34): error CS0571: 'C.P.set': cannot explicitly call operator or accessor\n // Action a = c.set_P;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_P\").WithArguments(\"A.B.C.P.set\").WithLocation(12, 34),\n // (13,17): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor\n // a = set_Q;\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"set_Q\").WithArguments(\"A.B.C.Q.set\").WithLocation(13, 17));\n }\n\n /// \n /// No errors should be reported if method with\n /// accessor name is defined in different class.\n /// \n [Fact]\n public void CS0571ERR_CantCallSpecialMethod03()\n {\n var source =\n@\"class A\n{\n public object get_P() { return null; }\n}\nclass B : A\n{\n public object P { get; set; }\n void M()\n {\n object o = this.P;\n o = this.get_P();\n }\n}\nclass C\n{\n void M(B b)\n {\n object o = b.P;\n o = b.get_P();\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact()]\n public void CS0571ERR_CantCallSpecialMethod04()\n {\n var compilation = CreateCompilation(\n@\"public class MyClass\n{\n public static MyClass operator ++(MyClass c)\n {\n return null;\n }\n public static void M()\n {\n op_Increment(null); // CS0571\n }\n}\n\").VerifyDiagnostics(\n // (9,9): error CS0571: 'MyClass.operator ++(MyClass)': cannot explicitly call operator or accessor\n // op_Increment(null); // CS0571\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Increment\").WithArguments(\"MyClass.operator ++(MyClass)\"));\n }\n\n [Fact]\n public void CS0571ERR_CantCallSpecialMethod05()\n {\n var source =\n@\"\nusing System;\npublic class C\n{\n public static void M()\n {\n IntPtr.op_Addition(default(IntPtr), 0);\n IntPtr.op_Subtraction(default(IntPtr), 0);\n IntPtr.op_Equality(default(IntPtr), default(IntPtr));\n IntPtr.op_Inequality(default(IntPtr), default(IntPtr));\n IntPtr.op_Explicit(0);\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (7,16): error CS0571: 'IntPtr.operator +(IntPtr, int)': cannot explicitly call operator or accessor\n // IntPtr.op_Addition(default(IntPtr), 0);\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Addition\").WithArguments(\"System.IntPtr.operator +(System.IntPtr, int)\").WithLocation(7, 16),\n // (8,16): error CS0571: 'IntPtr.operator -(IntPtr, int)': cannot explicitly call operator or accessor\n // IntPtr.op_Subtraction(default(IntPtr), 0);\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Subtraction\").WithArguments(\"System.IntPtr.operator -(System.IntPtr, int)\").WithLocation(8, 16),\n // (9,16): error CS0571: 'IntPtr.operator ==(IntPtr, IntPtr)': cannot explicitly call operator or accessor\n // IntPtr.op_Equality(default(IntPtr), default(IntPtr));\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Equality\").WithArguments(\"System.IntPtr.operator ==(System.IntPtr, System.IntPtr)\").WithLocation(9, 16),\n // (10,16): error CS0571: 'IntPtr.operator !=(IntPtr, IntPtr)': cannot explicitly call operator or accessor\n // IntPtr.op_Inequality(default(IntPtr), default(IntPtr));\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Inequality\").WithArguments(\"System.IntPtr.operator !=(System.IntPtr, System.IntPtr)\").WithLocation(10, 16),\n // (11,16): error CS0571: 'IntPtr.explicit operator IntPtr(int)': cannot explicitly call operator or accessor\n // IntPtr.op_Explicit(0);\n Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, \"op_Explicit\").WithArguments(\"System.IntPtr.explicit operator System.IntPtr(int)\").WithLocation(11, 16));\n }\n\n [Fact]\n public void CS0572ERR_BadTypeReference()\n {\n var text = @\"\nusing System;\nclass C\n{\n public class Inner\n {\n public static int v = 9;\n }\n}\n\nclass D : C\n{\n public static void Main()\n {\n C cValue = new C();\n Console.WriteLine(cValue.Inner.v); // CS0572\n // try the following line instead\n // Console.WriteLine(C.Inner.v);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadTypeReference, Line = 16, Column = 32 } });\n }\n\n [Fact]\n public void CS0574ERR_BadDestructorName()\n {\n var test = @\"\nnamespace x\n{\n public class iii\n {\n ~iiii(){}\n public static void Main()\n {\n }\n }\n}\n\";\n\n CreateCompilation(test).VerifyDiagnostics(\n // (6,10): error CS0574: Name of destructor must match name of type\n // ~iiii(){}\n Diagnostic(ErrorCode.ERR_BadDestructorName, \"iiii\").WithLocation(6, 10));\n }\n\n [WorkItem(541951, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951\")]\n [Fact]\n public void CS0611ERR_ArrayElementCantBeRefAny()\n {\n var text = @\"\npublic class Test\n{\n public System.TypedReference[] x;\n public System.RuntimeArgumentHandle[][] y;\n}\n\";\n var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45);\n comp.VerifyDiagnostics(\n // (4,12): error CS0611: Array elements cannot be of type 'System.TypedReference'\n // public System.TypedReference[] x;\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"System.TypedReference\").WithArguments(\"System.TypedReference\").WithLocation(4, 12),\n // (5,12): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle'\n // public System.RuntimeArgumentHandle[][] y;\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"System.RuntimeArgumentHandle\").WithArguments(\"System.RuntimeArgumentHandle\").WithLocation(5, 12));\n }\n\n [WorkItem(541951, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951\")]\n [Fact]\n public void CS0611ERR_ArrayElementCantBeRefAny_1()\n {\n var text =\n@\"using System;\nclass C\n{\n static void M()\n {\n var x = new[] { new ArgIterator() };\n var y = new[] { new TypedReference() };\n var z = new[] { new RuntimeArgumentHandle() };\n }\n}\";\n var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45);\n comp.VerifyDiagnostics(\n // (6,17): error CS0611: Array elements cannot be of type 'System.ArgIterator'\n // var x = new[] { new ArgIterator() };\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"new[] { new ArgIterator() }\").WithArguments(\"System.ArgIterator\").WithLocation(6, 17),\n // (7,17): error CS0611: Array elements cannot be of type 'System.TypedReference'\n // var y = new[] { new TypedReference() };\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"new[] { new TypedReference() }\").WithArguments(\"System.TypedReference\").WithLocation(7, 17),\n // (8,17): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle'\n // var z = new[] { new RuntimeArgumentHandle() };\n Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, \"new[] { new RuntimeArgumentHandle() }\").WithArguments(\"System.RuntimeArgumentHandle\").WithLocation(8, 17));\n }\n\n [Fact, WorkItem(546062, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062\")]\n public void CS0619ERR_DeprecatedSymbolStr()\n {\n var text = @\"\nusing System;\nnamespace a\n{\n [Obsolete]\n class C1 { }\n\n [Obsolete(\"\"Obsolescence message\"\", true)]\n interface I1 { }\n\n public class CI1 : I1 { }\n\n public class MainClass\n {\n public static void Main()\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,24): error CS0619: 'a.I1' is obsolete: 'Obsolescence message'\n // public class CI1 : I1 { }\n Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, \"I1\").WithArguments(\"a.I1\", \"Obsolescence message\")\n );\n }\n\n [Fact]\n public void CS0622ERR_ArrayInitToNonArrayType()\n {\n var text = @\"\npublic class Test\n{\n public static void Main ()\n {\n Test t = { new Test() }; // CS0622\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitToNonArrayType, Line = 6, Column = 18 } });\n }\n\n [Fact]\n public void CS0623ERR_ArrayInitInBadPlace()\n {\n var text = @\"\nclass X\n{\n public void goo(int a)\n {\n int[] x = { { 4 } }; //CS0623\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitInBadPlace, Line = 6, Column = 21 } });\n }\n\n [Fact]\n public void CS0631ERR_IllegalRefParam()\n {\n var compilation = CreateCompilation(\n@\"interface I\n{\n object this[ref object index] { get; set; }\n}\nclass C\n{\n internal object this[object x, out object y] { get { y = null; return null; } }\n}\nstruct S\n{\n internal object this[out int x, out int y] { set { x = 0; y = 0; } }\n}\");\n compilation.VerifyDiagnostics(\n // (3,17): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"ref\").WithLocation(3, 17),\n // (7,36): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"out\").WithLocation(7, 36),\n // (11,26): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"out\").WithLocation(11, 26),\n // (11,37): error CS0631: ref and out are not valid in this context\n Diagnostic(ErrorCode.ERR_IllegalRefParam, \"out\").WithLocation(11, 37));\n }\n\n [WorkItem(529305, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529305\")]\n [Fact()]\n public void CS0664ERR_LiteralDoubleCast()\n {\n var text = @\"\nclass Example\n{\n static void Main()\n {\n // CS0664, because 1.0 is interpreted as a double:\n decimal d1 = 1.0;\n float f1 = 2.0;\n }\n}\";\n var compilation = CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (7,22): error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type\n // decimal d1 = 1.0;\n Diagnostic(ErrorCode.ERR_LiteralDoubleCast, \"1.0\").WithArguments(\"M\", \"decimal\").WithLocation(7, 22),\n // (8,20): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type\n // float f1 = 2.0;\n Diagnostic(ErrorCode.ERR_LiteralDoubleCast, \"2.0\").WithArguments(\"F\", \"float\").WithLocation(8, 20),\n // (7,17): warning CS0219: The variable 'd1' is assigned but its value is never used\n // decimal d1 = 1.0;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"d1\").WithArguments(\"d1\").WithLocation(7, 17),\n // (8,15): warning CS0219: The variable 'f1' is assigned but its value is never used\n // float f1 = 2.0;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"f1\").WithArguments(\"f1\").WithLocation(8, 15));\n }\n\n [Fact]\n public void CS0670ERR_FieldCantHaveVoidType()\n {\n CreateCompilation(@\"\nclass C \n{\n void x = default(void); \n}\").VerifyDiagnostics(\n // (4,22): error CS1547: Keyword 'void' cannot be used in this context\n Diagnostic(ErrorCode.ERR_NoVoidHere, \"void\"),\n // (4,5): error CS0670: Field cannot have void type\n Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, \"void\"));\n }\n\n [Fact]\n public void CS0670ERR_FieldCantHaveVoidType_Var()\n {\n CreateCompilationWithMscorlib45(@\"\nvar x = default(void); \n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,17): error CS1547: Keyword 'void' cannot be used in this context\n Diagnostic(ErrorCode.ERR_NoVoidHere, \"void\"),\n // (2,1): error CS0670: Field cannot have void type\n Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, \"var\"));\n }\n\n [WorkItem(538016, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538016\")]\n [Fact]\n public void CS0687ERR_AliasQualAsExpression()\n {\n var text = @\"\nusing M = Test;\nusing System;\n\npublic class Test\n{\n public static int x = 77;\n\n public static void Main() \n {\n Console.WriteLine(M::x); // CS0687\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, \"M\").WithArguments(\"M\")\n );\n }\n\n [Fact]\n public void CS0704ERR_LookupInTypeVariable()\n {\n var text =\n@\"using System;\nclass A\n{\n internal class B : Attribute { }\n internal class C { }\n}\nclass D where T : A\n{\n class E : T.B { }\n interface I where U : T.B { }\n [T.B]\n static object M()\n {\n T.C b1 = new T.C();\n T.B b2 = null;\n b1 = default(T.B);\n object o = typeof(T.C);\n o = o as T.B;\n return b1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,15): error CS0704: Cannot do member lookup in 'T' because it is a type parameter class E : T.B { }\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (10,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // interface I where U : T.B { }\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (11,6): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // [T.B]\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (14,9): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // T.C b1 = new T.C();\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.C\").WithArguments(\"T\"),\n // (14,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // T.C b1 = new T.C();\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.C\").WithArguments(\"T\"),\n // (15,9): error CS0307: The type parameter 'T' cannot be used with type arguments\n // T.B b2 = null;\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"T\").WithArguments(\"T\", \"type parameter\"),\n // (16,22): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // b1 = default(T.B);\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\"),\n // (17,27): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // object o = typeof(T.C);\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.C\").WithArguments(\"T\"),\n // (18,18): error CS0704: Cannot do member lookup in 'T' because it is a type parameter\n // o = o as T.B;\n Diagnostic(ErrorCode.ERR_LookupInTypeVariable, \"T.B\").WithArguments(\"T\")\n );\n }\n\n [Fact]\n public void CS0712ERR_InstantiatingStaticClass()\n {\n var text = @\"\npublic static class SC\n{\n}\n\npublic class CMain\n{\n public static void Main()\n {\n SC sc = new SC(); // CS0712\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_InstantiatingStaticClass, Line = 10, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_VarDeclIsStaticClass, Line = 10, Column = 9 }});\n }\n\n [Fact]\n public void CS0716ERR_ConvertToStaticClass()\n {\n var text = @\"\npublic static class SC\n{\n static void F() { }\n}\n\npublic class Test\n{\n public static void Main()\n {\n object o = new object();\n System.Console.WriteLine((SC)o); // CS0716\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ConvertToStaticClass, Line = 12, Column = 34 } });\n }\n\n [Fact]\n [WorkItem(36203, \"https://github.com/dotnet/roslyn/issues/36203\")]\n public void CS0718_StaticClassError_HasHigherPriorityThanMethodOverloadError()\n {\n var code = @\"\nstatic class StaticClass { }\n\nclass Code\n{\n void GenericMethod(int i) => throw null;\n void GenericMethod(string s) => throw null;\n\n void IncorrectMethodCall()\n {\n GenericMethod(1);\n }\n}\";\n CreateCompilation(code).VerifyDiagnostics(\n // (11,9): error CS0718: 'StaticClass': static types cannot be used as type arguments\n Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, \"GenericMethod\").WithArguments(\"StaticClass\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS0723ERR_VarDeclIsStaticClass_Locals()\n {\n CreateCompilation(\n@\"static class SC\n{\n static void M()\n {\n SC sc = null; // CS0723\n N(sc);\n var sc2 = new SC();\n }\n static void N(object o)\n {\n }\n}\").VerifyDiagnostics(\n // (5,9): error CS0723: Cannot declare a variable of static type 'SC'\n Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, \"SC\").WithArguments(\"SC\"),\n // (7,19): error CS0712: Cannot create an instance of the static class 'SC'\n Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, \"new SC()\").WithArguments(\"SC\"),\n // (7,9): error CS0723: Cannot declare a variable of static type 'SC'\n Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, \"var\").WithArguments(\"SC\"));\n }\n\n [Fact]\n public void CS0723ERR_VarDeclIsStaticClass_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nstatic class SC {} \n\nvar sc2 = new SC();\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (4,5): error CS0723: Cannot declare a variable of static type 'SC'\n Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, \"sc2\").WithArguments(\"SC\"),\n // (4,11): error CS0712: Cannot create an instance of the static class 'SC'\n Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, \"new SC()\").WithArguments(\"SC\"));\n }\n\n [Fact]\n public void CS0724ERR_BadEmptyThrowInFinally()\n {\n var text = @\"\nusing System;\n\nclass X\n{\n static void Test()\n {\n try\n {\n throw new Exception();\n }\n catch\n {\n try\n {\n }\n finally\n {\n throw; // CS0724\n }\n }\n }\n\n static void Main()\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\").WithLocation(19, 17));\n }\n\n [Fact, WorkItem(1040213, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040213\")]\n public void CS0724ERR_BadEmptyThrowInFinally_Nesting()\n {\n var text = @\"\nusing System;\n\nclass X\n{\n static void Test(bool b)\n {\n try\n {\n throw new Exception();\n }\n catch\n {\n try\n {\n }\n finally\n {\n if (b) throw; // CS0724\n\n try\n {\n throw; // CS0724\n }\n catch\n {\n throw; // OK\n }\n finally\n {\n throw; // CS0724\n }\n }\n }\n }\n\n static void Main()\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"),\n // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause\n Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, \"throw\"));\n }\n\n [Fact]\n public void CS0747ERR_InvalidInitializerElementInitializer()\n {\n var text = @\"\nusing System.Collections.Generic;\n\npublic class C\n{\n public static int Main()\n {\n var t = new List { Capacity = 2, 1 }; // CS0747\n return 1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, \"1\"));\n }\n\n [Fact]\n public void CS0762ERR_PartialMethodToDelegate()\n {\n var text = @\"\npublic delegate void TestDel();\n\n public partial class C\n {\n partial void Part();\n\n public static int Main()\n {\n C c = new C();\n TestDel td = new TestDel(c.Part); // CS0762\n return 1;\n }\n\n }\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodToDelegate, Line = 11, Column = 38 } });\n }\n\n [Fact]\n public void CS0765ERR_PartialMethodInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq.Expressions;\n\npublic delegate void dele();\n\npublic class ConClass\n{\n [Conditional(\"\"CONDITION\"\")]\n public static void TestMethod() { }\n}\n\npublic partial class PartClass : IEnumerable\n{\n List list = new List();\n\n partial void Add(int x);\n\n public IEnumerator GetEnumerator()\n {\n for (int i = 0; i < list.Count; i++)\n yield return list[i];\n }\n\n static void Main()\n {\n Expression> testExpr1 = () => new PartClass { 1, 2 }; // CS0765\n Expression testExpr2 = () => ConClass.TestMethod(); // CS0765\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (30,71): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees\n // Expression> testExpr1 = () => new PartClass { 1, 2 }; // CS0765\n Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, \"1\"),\n // (30,74): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees\n // Expression> testExpr1 = () => new PartClass { 1, 2 }; // CS0765\n Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, \"2\"),\n // (31,44): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees\n // Expression testExpr2 = () => ConClass.TestMethod(); // CS0765\n Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, \"ConClass.TestMethod()\"));\n }\n\n [Fact]\n public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Local()\n {\n CreateCompilation(@\"\nclass Test\n{\n public static void Main()\n {\n var m = Main;\n var d = s => -1; // CS8917\n var e = (string s) => 0;\n var p = null;//CS0815\n var del = delegate(string a) { return -1; };\n var v = M(); // CS0815\n }\n static void M() {}\n}\").VerifyDiagnostics(\n // (7,17): error CS8917: The delegate type could not be inferred.\n // var d = s => -1; // CS8917\n Diagnostic(ErrorCode.ERR_CannotInferDelegateType, \"s => -1\").WithLocation(7, 17),\n // (9,13): error CS0815: Cannot assign to an implicitly-typed variable\n // var p = null;//CS0815\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"p = null\").WithArguments(\"\").WithLocation(9, 13),\n // (11,13): error CS0815: Cannot assign void to an implicitly-typed variable\n // var v = M(); // CS0815\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"v = M()\").WithArguments(\"void\").WithLocation(11, 13));\n }\n\n [Fact]\n public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Field()\n {\n CreateCompilationWithMscorlib45(@\"\nstatic void M() {}\n\nvar m = M; \nvar d = s => -1; \nvar e = (string s) => 0;\nvar p = null; \nvar del = delegate(string a) { return -1; };\nvar v = M(); \n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (5,9): error CS8917: The delegate type could not be inferred.\n // var d = s => -1; \n Diagnostic(ErrorCode.ERR_CannotInferDelegateType, \"s => -1\").WithLocation(5, 9),\n // (7,5): error CS0815: Cannot assign to an implicitly-typed variable\n // var p = null; \n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, \"p = null\").WithArguments(\"\").WithLocation(7, 5),\n // (9,1): error CS0670: Field cannot have void type\n // var v = M(); \n Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, \"var\").WithLocation(9, 1));\n }\n\n [Fact]\n public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer()\n {\n var text = @\"\nclass A\n{\n public static int Main()\n {\n var a; // CS0818\n return -1;\n }\n}\";\n // In the native compiler we skip post-initial-binding error analysis if there was\n // an error during the initial binding, so we report only that the \"var\" declaration \n // is bad. We do not report warnings like \"variable b is assigned but never used\". \n // In Roslyn we do flow analysis even if the initial binding pass produced an error,\n // so we have extra errors here.\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, Line = 6, Column = 13 },\n new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVar, Line = 6, Column = 13, IsWarning = true }});\n }\n\n [Fact]\n public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvar a; // CS0818\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (1,5): error CS0818: Implicitly-typed variables must be initialized\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, \"a\"));\n }\n\n [Fact]\n public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Locals()\n {\n var text = @\"\nclass A\n{\n public static int Main()\n {\n var a = 3, b = 2; // CS0819\n return -1;\n }\n}\n\";\n // In the native compiler we skip post-initial-binding error analysis if there was\n // an error during the initial binding, so we report only that the \"var\" declaration \n // is bad. We do not report warnings like \"variable b is assigned but never used\". \n // In Roslyn we do flow analysis even if the initial binding pass produced an error,\n // so we have extra errors here.\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, Line = 6, Column = 9 },\n new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 13, IsWarning = true },\n new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 20, IsWarning = true }});\n }\n\n [Fact]\n public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvar goo = 4, bar = 4.5;\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,1): error CS0819: Implicitly-typed fields cannot have multiple declarators\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, \"var\"));\n }\n\n [Fact]\n public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer()\n {\n var text = @\"\nclass G\n{\n public static int Main()\n {\n var a = { 1, 2, 3 }; //CS0820\n return -1;\n }\n}\";\n // In the native compilers this code produces two errors, both \n // \"you can't assign an array initializer to an implicitly typed local\" and\n // \"you can only use an array initializer to assign to an array type\". \n // It seems like the first error ought to prevent the second. In Roslyn\n // we only produce the first error.\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, Line = 6, Column = 13 }});\n }\n\n [Fact]\n public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvar y = { 1, 2, 3 };\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (1,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, \"y = { 1, 2, 3 }\"));\n }\n\n [Fact]\n public void CS0821ERR_ImplicitlyTypedLocalCannotBeFixed()\n {\n var text = @\"\nclass A\n{\n static int x;\n\n public static int Main()\n {\n unsafe\n {\n fixed (var p = &x) { }\n }\n return -1;\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (10,24): error CS0821: Implicitly-typed local variables cannot be fixed\n // fixed (var p = &x) { }\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, \"p = &x\"));\n }\n\n [Fact]\n public void CS0822ERR_ImplicitlyTypedLocalCannotBeConst()\n {\n var text = @\"\nclass A\n{\n public static void Main()\n {\n const var x = 0; // CS0822.cs\n const var y = (int?)null + x;\n }\n}\";\n // In the dev10 compiler, the second line reports both that \"const var\" is illegal \n // and that the initializer must be a valid constant. This seems a bit odd, so\n // in Roslyn we just report the first error. Let the user sort out whether they\n // meant it to be a constant or a variable, and then we can tell them if its a\n // bad constant.\n\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,15): error CS0822: Implicitly-typed variables cannot be constant\n // const var x = 0; // CS0822.cs\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, \"var x = 0\").WithLocation(6, 15),\n // (7,15): error CS0822: Implicitly-typed variables cannot be constant\n // const var y = (int?)null + x;\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, \"var y = (int?)null + x\").WithLocation(7, 15),\n // (7,23): warning CS0458: The result of the expression is always 'null' of type 'int?'\n // const var y = (int?)null + x;\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"(int?)null + x\").WithArguments(\"int?\").WithLocation(7, 23)\n );\n }\n\n [Fact]\n public void CS0822ERR_ImplicitlyTypedVariableCannotBeConst_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nconst var x = 0; // CS0822.cs\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,7): error CS0822: Implicitly-typed variables cannot be constant\n Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, \"var\"));\n }\n\n [Fact]\n public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields()\n {\n CreateCompilationWithMscorlib45(@\"\nvoid goo(var arg) { }\nvar goo(int arg) { return 2; }\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (1,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code\n Diagnostic(ErrorCode.ERR_TypeVarNotFound, \"var\"),\n // (2,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code\n Diagnostic(ErrorCode.ERR_TypeVarNotFound, \"var\"));\n }\n\n [Fact]\n public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields2()\n {\n CreateCompilationWithMscorlib45(@\"\nT goo() { return default(T); }\ngoo();\n\", parseOptions: TestOptions.Script).VerifyDiagnostics(\n // (2,5): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code\n Diagnostic(ErrorCode.ERR_TypeVarNotFound, \"var\"));\n }\n\n [Fact()]\n public void CS0826ERR_ImplicitlyTypedArrayNoBestType()\n {\n var text = @\"\npublic class C\n{\n delegate void D();\n public static void M1() {}\n public static void M2(int x) {}\n public static int M3() { return 1; }\n public static int M4(int x) { return x; }\n\n public static int Main()\n {\n var z = new[] { 1, \"\"str\"\" }; // CS0826\n\n char c = 'c';\n short s1 = 0;\n short s2 = -0;\n short s3 = 1;\n short s4 = -1;\n \n var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826\n\n var a = new [] {}; // CS0826\n\n byte b = 3;\n var arr = new [] {b, c}; // CS0826\n\n var a1 = new [] {null}; // CS0826\n var a2 = new [] {null, null, null}; // CS0826\n\n D[] l1 = new [] {x=>x+1}; // CS0826\n D[] l2 = new [] {x=>x+1, x=>{return x + 1;}, (int x)=>x+1, (int x)=>{return x + 1;}, (x, y)=>x + y, ()=>{return 1;}}; // CS0826\n\n D[] d1 = new [] {delegate {}}; // CS0826\n D[] d2 = new [] {delegate {}, delegate (){}, delegate {return 1;}, delegate {return;}, delegate(int x){}, delegate(int x){return x;}, delegate(int x, int y){return x + y;}}; // CS0826\n\n var m = new [] {M1, M2, M3, M4}; // CS0826\n\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 12, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 20, Column = 22 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 22, Column = 17 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 25, Column = 19 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 27, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 28, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 30, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 31, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 33, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 34, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 36, Column = 17 }});\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { p1 = null }; // CS0828\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_2()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new { p1 = Main }; // CS0828\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_3()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new { p1 = Main() }; // CS0828\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_4()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new { p1 = ()=>3 }; // CS0828\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } });\n }\n\n [Fact]\n public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_5()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n var c = new \n { \n p1 = delegate { return 1; } // CS0828\n }; \n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 8, Column = 13 } });\n }\n\n [Fact]\n public void CS0831ERR_ExpressionTreeContainsBaseAccess()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class A\n{\n public virtual int BaseMethod() { return 1; }\n}\npublic class C : A\n{\n public override int BaseMethod() { return 2; }\n public int Test(C c)\n {\n Expression> e = () => base.BaseMethod(); // CS0831\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (14,41): error CS0831: An expression tree may not contain a base access\n // Expression> e = () => base.BaseMethod(); // CS0831\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, \"base\")\n );\n }\n\n [Fact]\n public void CS0832ERR_ExpressionTreeContainsAssignment()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class C\n{\n public static int Main()\n {\n Expression> e1 = x => x += 5; // CS0843\n Expression> e2 = x => x = 5; // CS0843\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (9,46): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e1 = x => x += 5; // CS0843\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"x += 5\"),\n // (10,46): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e2 = x => x = 5; // CS0843\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"x = 5\")\n );\n }\n\n [Fact]\n public void CS0833ERR_AnonymousTypeDuplicatePropertyName()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { p1 = 1, p1 = 2 }; // CS0833\n return 1;\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } });\n }\n\n [Fact]\n public void CS0833ERR_AnonymousTypeDuplicatePropertyName_2()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { C.Prop, Prop = 2 }; // CS0833\n return 1;\n }\n static string Prop { get; set; }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } });\n }\n\n [Fact]\n public void CS0833ERR_AnonymousTypeDuplicatePropertyName_3()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n var c = new { C.Prop, Prop = 2 }; // CS0833 + CS0828\n return 1;\n }\n static string Prop() { return null; }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 }});\n }\n\n [Fact]\n public void CS0834ERR_StatementLambdaToExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class C\n{\n public static void Main()\n {\n Expression> e = x => { return x; }; // CS0834\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (9,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree\n // Expression> e = x => { return x; }; // CS0834\n Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, \"x => { return x; }\")\n );\n }\n\n [Fact]\n public void CS0835ERR_ExpressionTreeMustHaveDelegate()\n {\n var text = @\"\nusing System.Linq.Expressions;\n\npublic class Myclass\n{\n public static int Main()\n {\n Expression e = x => x + 1; // CS0835\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { LinqAssemblyRef },\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExpressionTreeMustHaveDelegate, Line = 8, Column = 29 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable()\n {\n var text = @\"\nusing System;\n[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]\npublic class MyClass : Attribute\n{\n public MyClass(object obj)\n {\n }\n}\n\n[MyClass(new { })] // CS0836\npublic class ClassGoo\n{\n}\n\npublic class Test\n{\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 11, Column = 10 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable2()\n {\n var text = @\"\npublic class Test\n{\n const object x = new { };\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 4, Column = 22 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable3()\n {\n var text = @\"\npublic class Test\n{\n static object y = new { };\n private object x = new { };\n public static int Main()\n {\n return 0;\n }\n}\n\";\n // NOTE: Actually we assert that #836 is NOT generated\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable4()\n {\n var text = @\"\npublic class Test\n{\n public static int Main(object x = new { })\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueMustBeConstant, Line = 4, Column = 39 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable5()\n {\n var text = @\"\nusing System;\n[AttributeUsage(AttributeTargets.All)]\npublic class MyClass : Attribute\n{\n public MyClass(object obj)\n {\n }\n}\n\npublic class Test\n{\n [MyClass(new { })] // CS0836\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } });\n }\n\n [Fact]\n public void CS0836ERR_AnonymousTypeNotAvailable6()\n {\n var text = @\"\nusing System;\n[AttributeUsage(AttributeTargets.All)]\npublic class MyClass : Attribute\n{\n public MyClass(object obj)\n {\n }\n}\n\npublic class Test\n{\n [MyClass(new { })] // CS0836\n static object y = new { };\n\n public static int Main()\n {\n return 0;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } });\n }\n\n [Fact]\n public void CS0837ERR_LambdaInIsAs()\n {\n var text = @\"\nnamespace TestNamespace\n{\n public delegate void Del();\n\n class Test\n {\n static int Main()\n {\n bool b1 = (() => { }) is Del; // CS0837\n bool b2 = delegate() { } is Del;// CS0837\n Del d1 = () => { } as Del; // CS0837\n Del d2 = delegate() { } as Del; // CS0837\n return 1;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b1 = (() => { }) is Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"(() => { }) is Del\").WithLocation(10, 23),\n // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } is Del\").WithLocation(11, 23),\n // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"is\").WithArguments(\"is\").WithLocation(11, 38),\n // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"() => { } as Del\").WithLocation(12, 22),\n // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(12, 32),\n // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } as Del\").WithLocation(13, 22),\n // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(13, 37)\n );\n CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(5)).VerifyDiagnostics(\n // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b1 = (() => { }) is Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"(() => { }) is Del\").WithLocation(10, 23),\n // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } is Del\").WithLocation(11, 23),\n // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate.\n // bool b2 = delegate() { } is Del;// CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"is\").WithArguments(\"is\").WithLocation(11, 38),\n // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"() => { } as Del\").WithLocation(12, 22),\n // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d1 = () => { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(12, 32),\n // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"delegate() { } as Del\").WithLocation(13, 22),\n // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate.\n // Del d2 = delegate() { } as Del; // CS0837\n Diagnostic(ErrorCode.WRN_PrecedenceInversion, \"as\").WithArguments(\"as\").WithLocation(13, 37)\n );\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration01()\n {\n CreateCompilation(\n@\"class C\n{\n static void M()\n {\n j = 5; // CS0841\n int j; // To fix, move this line up.\n }\n}\n\")\n // The native compiler just produces the \"var used before decl\" error; the Roslyn\n // compiler runs the flow checking pass even if the initial binding failed. We \n // might consider turning off flow checking if the initial binding failed, and\n // removing the warning here.\n\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"j\").WithArguments(\"j\"),\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"j\").WithArguments(\"j\"));\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration02()\n {\n CreateCompilation(\n@\"class C\n{\n static void M()\n {\n int a = b, b = 0, c = a;\n for (int x = y, y = 0; ; )\n {\n }\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"b\").WithArguments(\"b\"),\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"y\").WithArguments(\"y\"));\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration03()\n {\n // It is a bit unfortunate that we produce \"can't use variable before decl\" here\n // when the variable is being used after the decl. Perhaps we should generate\n // a better error?\n\n CreateCompilation(\n@\"class C\n{\n static int N(out int q) { q = 1; return 2;}\n static void M()\n {\n var x = N(out x);\n }\n}\n\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"x\").WithArguments(\"x\"));\n }\n\n [Fact]\n public void CS0841ERR_VariableUsedBeforeDeclaration04()\n {\n var systemRef = Net451.System;\n CreateCompilationWithMscorlib40AndSystemCore(\n@\"using System.Collections.Generic;\nclass Base\n{\n int i;\n}\nclass Derived : Base\n{\n int j;\n}\nclass C\n{\n public static void Main()\n {\n HashSet set1 = new HashSet();\n\n foreach (Base b in set1)\n {\n Derived d = b as Derived;\n Base b = null;\n }\n }\n}\n\", new List { systemRef })\n .VerifyDiagnostics(\n // (18,25): error CS0841: Cannot use local variable 'b' before it is declared\n // Derived d = b as Derived;\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, \"b\").WithArguments(\"b\"),\n // (19,18): error CS0136: A local or parameter named 'b' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter\n // Base b = null;\n Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, \"b\").WithArguments(\"b\"),\n // (4,9): warning CS0169: The field 'Base.i' is never used\n // int i;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"i\").WithArguments(\"Base.i\"),\n // (8,9): warning CS0169: The field 'Derived.j' is never used\n // int j;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"j\").WithArguments(\"Derived.j\"));\n }\n\n /// \n /// No errors using statics before declaration.\n /// \n [Fact]\n public void StaticUsedBeforeDeclaration()\n {\n var text =\n@\"class C\n{\n static int F = G + 2;\n static int G = F + 1;\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);\n }\n\n [Fact]\n public void CS0843ERR_UnassignedThisAutoProperty()\n {\n var text = @\"\nstruct S\n{\n public int AIProp { get; set; }\n public S(int i) { } //CS0843\n}\n\nclass Test\n{\n static int Main()\n {\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnassignedThisAutoProperty, Line = 5, Column = 12 } });\n }\n\n [Fact]\n public void CS0844ERR_VariableUsedBeforeDeclarationAndHidesField()\n {\n var text = @\"\npublic class MyClass\n{\n int num;\n public void TestMethod()\n {\n num = 5; // CS0844\n int num = 6;\n System.Console.WriteLine(num);\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (7,9): error CS0844: Cannot use local variable 'num' before it is declared. The declaration of the local variable hides the field 'MyClass.num'.\n // num = 5; // CS0844\n Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, \"num\").WithArguments(\"num\", \"MyClass.num\"),\n // (4,9): warning CS0169: The field 'MyClass.num' is never used\n // int num;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"num\").WithArguments(\"MyClass.num\")\n );\n }\n\n [Fact]\n public void CS0845ERR_ExpressionTreeContainsBadCoalesce()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n Expression> e = () => null ?? \"\"x\"\"; // CS0845\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (11,48): error CS0845: An expression tree lambda may not contain a coalescing operator with a null literal left-hand side\n // Expression> e = () => null ?? \"x\"; // CS0845\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, \"null\")\n );\n }\n\n [WorkItem(3717, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS0846ERR_ArrayInitializerExpected()\n {\n var text = @\"public class Myclass\n{\n public static void Main()\n {\n int[,] a = new int[,] { 1 }; // error\n } \n} \n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitializerExpected, Line = 5, Column = 33 } });\n }\n\n [Fact]\n public void CS0847ERR_ArrayInitializerIncorrectLength()\n {\n var text = @\"\npublic class Program\n{\n public static void Main(string[] args)\n {\n int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected\n int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected\n ar0[0] = ar1[0];\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,31): error CS0847: An array initializer of length '0' is expected\n // int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected\n Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, \"{0}\").WithArguments(\"0\").WithLocation(6, 31),\n // (7,31): error CS0847: An array initializer of length '3' is expected\n // int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected\n Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, \"{}\").WithArguments(\"3\").WithLocation(7, 31));\n }\n\n [Fact]\n public void CS0853ERR_ExpressionTreeContainsNamedArgument01()\n {\n var text = @\"\nusing System.Linq.Expressions;\nnamespace ConsoleApplication3\n{\n class Program\n {\n delegate string dg(int x);\n static void Main(string[] args)\n {\n Expression myET = x => Index(minSessions:5);\n }\n public static string Index(int minSessions = 0)\n {\n return minSessions.ToString();\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,40): error CS0853: An expression tree may not contain a named argument specification\n // Expression myET = x => Index(minSessions:5);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, \"Index(minSessions:5)\").WithLocation(10, 40)\n );\n }\n\n [WorkItem(545063, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545063\")]\n [Fact]\n public void CS0853ERR_ExpressionTreeContainsNamedArgument02()\n {\n var text = @\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n \nclass A\n{\n static void Main()\n {\n Expression> f = () => new List { 1 } [index: 0];\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,41): error CS0853: An expression tree may not contain a named argument specification\n // Expression> f = () => new List { 1 } [index: 0];\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, \"new List { 1 } [index: 0]\").WithLocation(10, 41)\n );\n }\n\n [Fact]\n public void CS0854ERR_ExpressionTreeContainsOptionalArgument01()\n {\n var text = @\"\nusing System.Linq.Expressions;\nnamespace ConsoleApplication3\n{\n class Program\n {\n delegate string dg(int x);\n static void Main(string[] args)\n {\n Expression myET = x => Index();\n }\n public static string Index(int minSessions = 0)\n {\n return minSessions.ToString();\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,40): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n // Expression myET = x => Index();\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"Index()\").WithLocation(10, 40)\n );\n }\n\n [Fact]\n public void CS0854ERR_ExpressionTreeContainsOptionalArgument02()\n {\n var text =\n@\"using System;\nusing System.Linq.Expressions;\nclass A\n{\n internal object this[int x, int y = 2]\n {\n get { return null; }\n }\n}\nclass B\n{\n internal object this[int x, int y = 2]\n {\n set { }\n }\n}\nclass C\n{\n static void M(A a, B b)\n {\n Expression> e1;\n e1 = () => a[0];\n e1 = () => a[1, 2];\n Expression e2;\n e2 = () => b[3] = null;\n e2 = () => b[4, 5] = null;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (22,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"a[0]\").WithLocation(22, 20),\n // (25,20): error CS0832: An expression tree may not contain an assignment operator\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"b[3] = null\").WithLocation(25, 20),\n // (25,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"b[3]\").WithLocation(25, 20),\n // (26,20): error CS0832: An expression tree may not contain an assignment operator\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"b[4, 5] = null\").WithLocation(26, 20));\n }\n\n [Fact]\n public void CS0854ERR_ExpressionTreeContainsOptionalArgument03()\n {\n var text =\n@\"using System;\nusing System.Collections;\nusing System.Linq.Expressions;\n\npublic class Collection : IEnumerable\n{\n public void Add(int i, int j = 0) { }\n\n public IEnumerator GetEnumerator()\n {\n throw new NotImplementedException();\n }\n}\n\npublic class C {\n public void M() {\n Expression> expr =\n () => new Collection { 1 }; // 1\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,36): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments\n // () => new Collection { 1 }; // 1\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, \"1\").WithLocation(18, 36));\n }\n\n [Fact]\n public void CS0855ERR_ExpressionTreeContainsIndexedProperty()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\nPublic Interface I\n Property P(index As Object) As Integer\n Property Q(Optional index As Object = Nothing) As Integer\nEnd Interface\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1);\n var source2 =\n@\"using System;\nusing System.Linq.Expressions;\nclass C\n{\n static void M(I i)\n {\n Expression> e1;\n e1 = () => i.P[1];\n e1 = () => i.get_P(2); // no error\n e1 = () => i.Q;\n e1 = () => i.Q[index:3];\n Expression e2;\n e2 = () => i.P[4] = 0;\n e2 = () => i.set_P(5, 6); // no error\n }\n}\";\n var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (8,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.P[1]\").WithLocation(8, 20),\n // (10,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.Q\").WithLocation(10, 20),\n // (11,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.Q[index:3]\").WithLocation(11, 20),\n // (13,20): error CS0832: An expression tree may not contain an assignment operator\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"i.P[4] = 0\").WithLocation(13, 20),\n // (13,20): error CS0855: An expression tree may not contain an indexed property\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, \"i.P[4]\").WithLocation(13, 20));\n }\n\n [Fact]\n [CompilerTrait(CompilerFeature.IOperation)]\n [WorkItem(23004, \"https://github.com/dotnet/roslyn/issues/23004\")]\n public void CS0856ERR_IndexedPropertyRequiresParams01()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\nPublic Interface I\n Property P(x As Object, Optional y As Object = Nothing) As Object\n Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(x As Object, Optional y As Object = Nothing) As Object\n Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object\n Property S(ParamArray args As Integer()) As Object\nEnd Interface\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1);\n var source2 =\n@\"class C\n{\n static void M(I i)\n {\n object o;\n o = i.P; // CS0856 (Dev11)\n o = i.Q;\n i.R = o; // CS0856\n i.R[1] = o; // CS1501\n o = i.S; // CS0856 (Dev11)\n i.S = o; // CS0856 (Dev11)\n }\n}\";\n var compilation2 = CreateCompilation(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (8,9): error CS0856: Indexed property 'I.R' has non-optional arguments which must be provided\n Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, \"i.R\").WithArguments(\"I.R\").WithLocation(8, 9),\n // (9,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'I.R[int, int, int]'\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"i.R[1]\").WithArguments(\"y\", \"I.R[int, int, int]\").WithLocation(9, 9));\n\n var tree = compilation2.SyntaxTrees.Single();\n var node = tree.GetRoot().DescendantNodes().OfType().First();\n\n Assert.Equal(\"i.R[1]\", node.ToString());\n\n compilation2.VerifyOperationTree(node, expectedOperationTree:\n@\"\nIInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'i.R[1]')\n Children(2):\n IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: I, IsInvalid) (Syntax: 'i')\n ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')\n\");\n }\n\n [Fact]\n public void CS0856ERR_IndexedPropertyRequiresParams02()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\nPublic Class A\n Protected ReadOnly Property P(Optional o As Object = Nothing) As Object\n Get\n Return Nothing\n End Get\n End Property\n Public ReadOnly Property P(i As Integer) As Object\n Get\n Return Nothing\n End Get\n End Property\nEnd Class\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1);\n var source2 =\n@\"class C\n{\n static object F(A a)\n {\n return a.P;\n }\n}\";\n var compilation2 = CreateCompilation(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (5,16): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided\n Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, \"a.P\").WithArguments(\"A.P\").WithLocation(5, 16));\n }\n\n [Fact]\n public void CS0857ERR_IndexedPropertyMustHaveAllOptionalParams()\n {\n var source1 =\n@\"Imports System\nImports System.Runtime.InteropServices\n \n \n\n\n\nPublic Interface IA\n Property P(x As Object, Optional y As Object = Nothing) As Object\n Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object\n Property Q(x As Object, Optional y As Object = Nothing) As Object\n Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object\n Property S(ParamArray args As Integer()) As Object\nEnd Interface\nPublic Class A\n Implements IA\n Property P(x As Object, Optional y As Object = Nothing) As Object Implements IA.P\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.P\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.Q\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property Q(x As Object, Optional y As Object = Nothing) As Object Implements IA.Q\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Implements IA.R\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\n Property S(ParamArray args As Integer()) As Object Implements IA.S\n Get\n Return Nothing\n End Get\n Set(value As Object)\n End Set\n End Property\nEnd Class\";\n var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes);\n var source2 =\n@\"class B\n{\n static void M()\n {\n IA a;\n a = new IA() { P = null }; // CS0857 (Dev11)\n a = new IA() { Q = null };\n a = new IA() { R = null }; // CS0857\n a = new IA() { S = null }; // CS0857 (Dev11)\n }\n}\";\n var compilation2 = CreateCompilation(source2, new[] { reference1 });\n compilation2.VerifyDiagnostics(\n // (8,24): error CS0857: Indexed property 'IA.R' must have all arguments optional\n Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, \"R\").WithArguments(\"IA.R\").WithLocation(8, 24));\n }\n\n [Fact]\n public void CS1059ERR_IncrementLvalueExpected01()\n {\n var text =\n@\"enum E { A, B }\nclass C\n{\n static void M()\n {\n ++E.A; // CS1059\n E.A++; // CS1059\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 6, Column = 11 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 7, Column = 9 });\n }\n\n [Fact]\n public void CS1059ERR_IncrementLvalueExpected02()\n {\n var text =\n@\"class C\n{\n const int field = 0;\n static void M()\n {\n const int local = 0;\n ++local;\n local++;\n --field;\n field--;\n ++(local + 3);\n (local + 3)++;\n --2;\n 2--;\n\n dynamic d = null;\n (d + 1)++;\n --(d + 1);\n d++++;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local\"),\n // (8,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local\"),\n // (9,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"field\"),\n // (10,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"field\"),\n // (11,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local + 3\"),\n // (12,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"local + 3\"),\n // (13,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"2\"),\n // (14,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"2\"),\n // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"d + 1\"),\n // (18,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"d + 1\"),\n // (19,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"d++\"));\n }\n\n [Fact]\n public void CS1059ERR_IncrementLvalueExpected03()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n ++this; // CS1059\n this--; // CS1059\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n // ++this; // CS1059\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"this\").WithArguments(\"this\"),\n // (7,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer\n // this--; // CS1059\n Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension01()\n {\n var text = @\"\npublic class TestClass1\n{\n public void WriteSomething(string s)\n {\n System.Console.WriteLine(s);\n }\n}\n\npublic class TestClass2\n{\n public void DisplaySomething(string s)\n {\n System.Console.WriteLine(s);\n }\n}\n\npublic class TestTheClasses\n{\n public static void Main()\n {\n TestClass1 tc1 = new TestClass1();\n TestClass2 tc2 = new TestClass2();\n if (tc1 == null | tc2 == null) {}\n tc1.DisplaySomething(\"\"Hello\"\"); // CS1061\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 25, Column = 13 } });\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension02()\n {\n var source =\n@\"enum E { }\nclass C\n{\n static void M(E e)\n {\n object o = e.value__;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (6,22): error CS1061: 'E' does not contain a definition for 'value__' and no extension method 'value__' accepting a first argument of type 'E' could be found (are you missing a using directive or an assembly reference?)\n // object o = e.value__;\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"value__\").WithArguments(\"E\", \"value__\").WithLocation(6, 22));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension03()\n {\n CreateCompilation(\n@\"class A\n{\n}\nclass B\n{\n void M()\n {\n this.F();\n this.P = this.Q;\n }\n static void M(A a)\n {\n a.F();\n a.P = a.Q;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"F\").WithArguments(\"A\", \"F\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"P\").WithArguments(\"A\", \"P\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Q\").WithArguments(\"A\", \"Q\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"F\").WithArguments(\"B\", \"F\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"P\").WithArguments(\"B\", \"P\"),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Q\").WithArguments(\"B\", \"Q\"));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension04()\n {\n CreateCompilation(\n@\"using System.Collections.Generic;\nclass C\n{\n static void M(List list)\n {\n object o = list.Item;\n list.Item = o;\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Item\").WithArguments(\"System.Collections.Generic.List\", \"Item\").WithLocation(6, 25),\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Item\").WithArguments(\"System.Collections.Generic.List\", \"Item\").WithLocation(7, 14));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension05()\n {\n CreateCompilationWithMscorlib40AndSystemCore(\n@\"using System.Linq;\n\nclass Test\n{\n static void Main()\n {\n var q = 1.Select(z => z);\n }\n}\n\")\n .VerifyDiagnostics(\n // (7,17): error CS1061: 'int' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)\n // var q = 1.Select(z => z);\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"Select\").WithArguments(\"int\", \"Select\").WithLocation(7, 19));\n }\n\n [Fact]\n public void CS1061ERR_NoSuchMemberOrExtension06()\n {\n var source =\n@\"interface I { }\nstatic class C\n{\n static void M(object o)\n {\n o.M1(o, o);\n o.M2(o, o);\n }\n static void M1(this I o, object arg) { }\n static void M2(this I o, params object[] args) { }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(\n // (6,9): error CS1501: No overload for method 'M1' takes 2 arguments\n Diagnostic(ErrorCode.ERR_BadArgCount, \"M1\").WithArguments(\"M1\", \"2\").WithLocation(6, 11),\n // (7,9): error CS1061: 'object' does not contain a definition for 'M2' and no extension method 'M2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)\n Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, \"M2\").WithArguments(\"object\", \"M2\").WithLocation(7, 11));\n }\n\n [Fact]\n public void CS1113ERR_ValueTypeExtDelegate01()\n {\n var source =\n@\"class C\n{\n public void M() { }\n}\ninterface I\n{\n void M();\n}\nenum E\n{\n}\nstruct S\n{\n public void M() { }\n}\nstatic class SC\n{\n static void Test(C c, I i, E e, S s, double d)\n {\n System.Action cm = c.M; // OK -- instance method\n System.Action cm1 = c.M1; // OK -- extension method on ref type\n System.Action im = i.M; // OK -- instance method\n System.Action im2 = i.M2; // OK -- extension method on ref type\n System.Action em3 = e.M3; // BAD -- extension method on value type\n System.Action sm = s.M; // OK -- instance method\n System.Action sm4 = s.M4; // BAD -- extension method on value type\n System.Action dm5 = d.M5; // BAD -- extension method on value type\n }\n\n static void M1(this C c) { }\n static void M2(this I i) { }\n static void M3(this E e) { }\n static void M4(this S s) { }\n static void M5(this double d) { }\n}\";\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (24,29): error CS1113: Extension methods 'SC.M3(E)' defined on value type 'E' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"e.M3\").WithArguments(\"SC.M3(E)\", \"E\").WithLocation(24, 29),\n // (26,29): error CS1113: Extension methods 'SC.M4(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M4\").WithArguments(\"SC.M4(S)\", \"S\").WithLocation(26, 29),\n // (27,29): error CS1113: Extension methods 'SC.M5(double)' defined on value type 'double' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"d.M5\").WithArguments(\"SC.M5(double)\", \"double\").WithLocation(27, 29));\n }\n\n [Fact]\n public void CS1113ERR_ValueTypeExtDelegate02()\n {\n var source =\n@\"delegate void D();\ninterface I { }\nstruct S { }\nclass C\n{\n static void M(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)\n where T2 : class\n where T3 : struct\n where T4 : I\n where T5 : C\n {\n D d;\n d = i.M1;\n d = i.M2;\n d = s.M1;\n d = s.M2;\n d = t1.M1;\n d = t1.M2;\n d = t2.M1;\n d = t2.M2;\n d = t3.M1;\n d = t3.M2;\n d = t4.M1;\n d = t4.M2;\n d = t5.M1;\n d = t5.M2;\n }\n}\nstatic class E\n{\n internal static void M1(this T t) { }\n internal static void M2(this T t) { }\n}\";\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (13,13): error CS1113: Extension methods 'E.M1(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M1\").WithArguments(\"E.M1(int)\", \"int\").WithLocation(13, 13),\n // (14,13): error CS1113: Extension methods 'E.M2(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M2\").WithArguments(\"E.M2(int)\", \"int\").WithLocation(14, 13),\n // (15,13): error CS1113: Extension methods 'E.M1(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M1\").WithArguments(\"E.M1(S)\", \"S\").WithLocation(15, 13),\n // (16,13): error CS1113: Extension methods 'E.M2(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M2\").WithArguments(\"E.M2(S)\", \"S\").WithLocation(16, 13),\n // (17,13): error CS1113: Extension methods 'E.M1(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M1\").WithArguments(\"E.M1(T1)\", \"T1\").WithLocation(17, 13),\n // (18,13): error CS1113: Extension methods 'E.M2(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M2\").WithArguments(\"E.M2(T1)\", \"T1\").WithLocation(18, 13),\n // (21,13): error CS1113: Extension methods 'E.M1(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M1\").WithArguments(\"E.M1(T3)\", \"T3\").WithLocation(21, 13),\n // (22,13): error CS1113: Extension methods 'E.M2(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M2\").WithArguments(\"E.M2(T3)\", \"T3\").WithLocation(22, 13),\n // (23,13): error CS1113: Extension methods 'E.M1(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M1\").WithArguments(\"E.M1(T4)\", \"T4\").WithLocation(23, 13),\n // (24,13): error CS1113: Extension methods 'E.M2(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M2\").WithArguments(\"E.M2(T4)\", \"T4\").WithLocation(24, 13));\n }\n\n [WorkItem(528758, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528758\")]\n [Fact(Skip = \"528758\")]\n public void CS1113ERR_ValueTypeExtDelegate03()\n {\n var source =\n@\"delegate void D();\ninterface I { }\nstruct S { }\nclass C\n{\n static void M(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)\n where T2 : class\n where T3 : struct\n where T4 : I\n where T5 : C\n {\n F(i.M1);\n F(i.M2);\n F(s.M1);\n F(s.M2);\n F(t1.M1);\n F(t1.M2);\n F(t2.M1);\n F(t2.M2);\n F(t3.M1);\n F(t3.M2);\n F(t4.M1);\n F(t4.M2);\n F(t5.M1);\n F(t5.M2);\n }\n static void F(D d) { }\n}\nstatic class E\n{\n internal static void M1(this T t) { }\n internal static void M2(this T t) { }\n}\";\n CreateCompilation(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics(\n // (12,11): error CS1113: Extension methods 'E.M1(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M1\").WithArguments(\"E.M1(int)\", \"int\").WithLocation(12, 11),\n // (13,11): error CS1113: Extension methods 'E.M2(int)' defined on value type 'int' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"i.M2\").WithArguments(\"E.M2(int)\", \"int\").WithLocation(13, 11),\n // (14,11): error CS1113: Extension methods 'E.M1(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M1\").WithArguments(\"E.M1(S)\", \"S\").WithLocation(14, 11),\n // (15,11): error CS1113: Extension methods 'E.M2(S)' defined on value type 'S' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"s.M2\").WithArguments(\"E.M2(S)\", \"S\").WithLocation(15, 11),\n // (16,11): error CS1113: Extension methods 'E.M1(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M1\").WithArguments(\"E.M1(T1)\", \"T1\").WithLocation(16, 11),\n // (17,11): error CS1113: Extension methods 'E.M2(T1)' defined on value type 'T1' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t1.M2\").WithArguments(\"E.M2(T1)\", \"T1\").WithLocation(17, 11),\n // (20,11): error CS1113: Extension methods 'E.M1(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M1\").WithArguments(\"E.M1(T3)\", \"T3\").WithLocation(20, 11),\n // (21,11): error CS1113: Extension methods 'E.M2(T3)' defined on value type 'T3' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t3.M2\").WithArguments(\"E.M2(T3)\", \"T3\").WithLocation(21, 11),\n // (22,11): error CS1113: Extension methods 'E.M1(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M1\").WithArguments(\"E.M1(T4)\", \"T4\").WithLocation(22, 11),\n // (23,11): error CS1113: Extension methods 'E.M2(T4)' defined on value type 'T4' cannot be used to create delegates\n Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, \"t4.M2\").WithArguments(\"E.M2(T4)\", \"T4\").WithLocation(23, 11));\n }\n\n [Fact]\n public void CS1501ERR_BadArgCount()\n {\n var text = @\"\nusing System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n ExampleClass ec = new ExampleClass();\n ec.ExampleMethod(10, 20);\n }\n }\n\n class ExampleClass\n {\n public void ExampleMethod()\n {\n Console.WriteLine(\"\"Zero parameters\"\");\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgCount, Line = 11, Column = 16 } });\n }\n\n [Fact]\n public void CS1502ERR_BadArgTypes()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public a(char i)\n {\n }\n\n public static void Main()\n {\n a aa = new a(2222); // CS1502 & CS1503\n if (aa == null) {}\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 12, Column = 24 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 12, Column = 26 }});\n }\n\n [Fact]\n public void CS1502ERR_BadArgTypes_ConstructorInitializer()\n {\n var text = @\"\nnamespace x\n{\n public class a\n {\n public a() : this(\"\"string\"\") //CS1502, CS1503\n {\n }\n\n public a(char i)\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n //// (6,22): error CS1502: The best overloaded method match for 'x.a.a(char)' has some invalid arguments\n //Diagnostic(ErrorCode.ERR_BadArgTypes, \"this\").WithArguments(\"x.a.a(char)\"), //specifically omitted by roslyn\n // (6,27): error CS1503: Argument 1: cannot convert from 'string' to 'char'\n Diagnostic(ErrorCode.ERR_BadArgType, \"\\\"string\\\"\").WithArguments(\"1\", \"string\", \"char\"));\n }\n\n [Fact]\n public void CS1503ERR_BadArgType01()\n {\n var source =\n@\"namespace X\n{\n public class C\n {\n public C(int i, char c)\n {\n }\n static void M()\n {\n new C(1, 2); // CS1502 & CS1503\n }\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (10,22): error CS1503: Argument 2: cannot convert from 'int' to 'char'\n // new C(1, 2); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"2\").WithArguments(\"2\", \"int\", \"char\").WithLocation(10, 22));\n }\n\n [Fact]\n public void CS1503ERR_BadArgType02()\n {\n var source =\n@\"enum E1 { A, B, C }\nenum E2 { X, Y, Z }\nclass C\n{\n static void F(int i) { }\n static void G(E1 e) { }\n static void M()\n {\n F(E1.A); // CS1502 & CS1503\n F((E2)E1.B); // CS1502 & CS1503\n F((int)E1.C);\n G(E2.X); // CS1502 & CS1503\n G((E1)E2.Y);\n G((int)E2.Z); // CS1502 & CS1503\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,11): error CS1503: Argument 1: cannot convert from 'E1' to 'int'\n // F(E1.A); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"E1.A\").WithArguments(\"1\", \"E1\", \"int\").WithLocation(9, 11),\n // (10,11): error CS1503: Argument 1: cannot convert from 'E2' to 'int'\n // F((E2)E1.B); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"(E2)E1.B\").WithArguments(\"1\", \"E2\", \"int\").WithLocation(10, 11),\n // (12,11): error CS1503: Argument 1: cannot convert from 'E2' to 'E1'\n // G(E2.X); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"E2.X\").WithArguments(\"1\", \"E2\", \"E1\").WithLocation(12, 11),\n // (14,11): error CS1503: Argument 1: cannot convert from 'int' to 'E1'\n // G((int)E2.Z); // CS1502 & CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"(int)E2.Z\").WithArguments(\"1\", \"int\", \"E1\").WithLocation(14, 11));\n }\n\n [WorkItem(538939, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538939\")]\n [Fact]\n public void CS1503ERR_BadArgType03()\n {\n var source =\n@\"class C\n{\n static void F(out int i)\n {\n i = 0;\n }\n static void M(long arg)\n {\n F(out arg); // CS1503\n }\n}\n\";\n CreateCompilation(source).VerifyDiagnostics(\n // (9,15): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'\n // F(out arg); // CS1503\n Diagnostic(ErrorCode.ERR_BadArgType, \"arg\").WithArguments(\"1\", \"out long\", \"out int\").WithLocation(9, 15));\n }\n\n [Fact]\n public void CS1503ERR_BadArgType_MixedMethodsAndTypes()\n {\n var text = @\"\nclass A\n{\n public static void Goo(int x) { }\n}\nclass B : A\n{\n public class Goo { }\n}\nclass C : B\n{\n public static void Goo(string x) { }\n\n static void Main()\n {\n ((Goo))(1);\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 8, Column = 16, IsWarning = true },\n new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 22, IsWarning = true },\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 16, Column = 5 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 16, Column = 13 }\n });\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_01()\n {\n var text =\n@\"class C\n{\n void M(ref int i)\n {\n M(ref 2); // CS1510, can't pass a number as a ref parameter\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_RefLvalueExpected, Line = 5, Column = 15 });\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_02()\n {\n var text =\n@\"class C\n{\n void M()\n {\n var a = new System.Action(ref x => x = 1);\n var b = new System.Action(ref (x,y) => x = 1);\n var c = new System.Action(ref delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,44): error CS1510: A ref or out argument must be an assignable variable\n // var a = new System.Action(ref x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(5, 44),\n // (6,49): error CS1510: A ref or out argument must be an assignable variable\n // var b = new System.Action(ref (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(6, 49),\n // (7,44): error CS1510: A ref or out argument must be an assignable variable\n // var c = new System.Action(ref delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(7, 44));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_03()\n {\n var text =\n@\"class C\n{\n void M()\n {\n var a = new System.Action(out x => x = 1);\n var b = new System.Action(out (x,y) => x = 1);\n var c = new System.Action(out delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,44): error CS1510: A ref or out argument must be an assignable variable\n // var a = new System.Action(out x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(5, 44),\n // (6,49): error CS1510: A ref or out argument must be an assignable variable\n // var b = new System.Action(out (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(6, 49),\n // (7,44): error CS1510: A ref or out argument must be an assignable variable\n // var c = new System.Action(out delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(7, 44));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_04()\n {\n var text =\n@\"class C\n{\n void Goo(ref System.Action t) {}\n void Goo(ref System.Action t) {}\n void M()\n {\n Goo(ref x => x = 1);\n Goo(ref (x,y) => x = 1);\n Goo(ref delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(ref x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(7, 22),\n // (8,27): error CS1510: A ref or out argument must be an assignable variable\n // Goo(ref (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(8, 27),\n // (9,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(ref delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(9, 22));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_05()\n {\n var text =\n@\"class C\n{\n void Goo(out System.Action t) {t = null;}\n void Goo(out System.Action t) {t = null;}\n void M()\n {\n Goo(out x => x = 1);\n Goo(out (x,y) => x = 1);\n Goo(out delegate (int x) {x = 1;});\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(out x => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x = 1\").WithLocation(7, 22),\n // (8,27): error CS1510: A ref or out argument must be an assignable variable\n // Goo(out (x,y) => x = 1);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"(x,y) => x = 1\").WithLocation(8, 27),\n // (9,22): error CS1510: A ref or out argument must be an assignable variable\n // Goo(out delegate (int x) {x = 1;});\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"delegate (int x) {x = 1;}\").WithLocation(9, 22));\n }\n\n [Fact]\n public void CS1510ERR_RefLvalueExpected_Strict()\n {\n var text =\n@\"class C\n{\n void D(int i) {}\n void M()\n {\n System.Action del = D;\n\n var a = new System.Action(ref D);\n var b = new System.Action(out D);\n var c = new System.Action(ref del);\n var d = new System.Action(out del);\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (8,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group'\n // var a = new System.Action(ref D);\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"D\").WithArguments(\"D\", \"method group\").WithLocation(8, 44),\n // (9,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group'\n // var b = new System.Action(out D);\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"D\").WithArguments(\"D\", \"method group\").WithLocation(9, 44),\n // (10,44): error CS0149: Method name expected\n // var c = new System.Action(ref del);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"del\").WithLocation(10, 44),\n // (11,44): error CS0149: Method name expected\n // var d = new System.Action(out del);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"del\").WithLocation(11, 44));\n }\n\n [Fact]\n public void CS1511ERR_BaseInStaticMeth()\n {\n var text = @\"\npublic class A\n{\n public int j = 0;\n}\n\nclass C : A\n{\n public void Method()\n {\n base.j = 3; // base allowed here\n }\n\n public static int StaticMethod()\n {\n base.j = 3; // CS1511\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInStaticMeth, Line = 16, Column = 7 } });\n }\n\n [Fact]\n public void CS1511ERR_BaseInStaticMeth_Combined()\n {\n var text = @\"\nusing System;\n\nclass CLS\n{\n static CLS() { var x = base.ToString(); }\n static object FLD = base.ToString();\n static object PROP { get { return base.ToString(); } }\n static object METHOD() { return base.ToString(); }\n}\n\nclass A : Attribute\n{\n public object P;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,25): error CS1511: Keyword 'base' is not available in a static method\n // static object FLD = base.ToString();\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (6,28): error CS1511: Keyword 'base' is not available in a static method\n // static CLS() { var x = base.ToString(); }\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (8,39): error CS1511: Keyword 'base' is not available in a static method\n // static object PROP { get { return base.ToString(); } }\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (9,37): error CS1511: Keyword 'base' is not available in a static method\n // static object METHOD() { return base.ToString(); }\n Diagnostic(ErrorCode.ERR_BaseInStaticMeth, \"base\"),\n // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null\n // public object P;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"P\").WithArguments(\"A.P\", \"null\")\n );\n }\n\n [Fact]\n public void CS1512ERR_BaseInBadContext()\n {\n var text = @\"\nusing System;\n\nclass Base { }\n\nclass CMyClass : Base\n{\n private String xx = base.ToString(); // CS1512\n \n public static void Main()\n {\n CMyClass z = new CMyClass();\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 8, Column = 25 } });\n }\n\n [Fact]\n public void CS1512ERR_BaseInBadContext_AttributeArgument()\n {\n var text = @\"\nusing System;\n\n[assembly: A(P = base.ToString())]\n\npublic class A : Attribute\n{\n public object P;\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 4, Column = 18 } });\n }\n\n [Fact]\n public void CS1520ERR_MemberNeedsType_02()\n {\n CreateCompilation(\n@\"class Program\n{\n Main() {}\n Helper() {}\n \\u0050rogram(int x) {}\n}\")\n .VerifyDiagnostics(\n // (3,5): error CS1520: Method must have a return type\n // Main() {}\n Diagnostic(ErrorCode.ERR_MemberNeedsType, \"Main\"),\n // (4,5): error CS1520: Method must have a return type\n // Helper() {}\n Diagnostic(ErrorCode.ERR_MemberNeedsType, \"Helper\").WithLocation(4, 5)\n );\n }\n\n [Fact]\n public void CS1525ERR_InvalidExprTerm()\n {\n CreateCompilation(\n@\"public class MyClass {\n\n public static int Main() {\n bool b = string is string;\n return 1;\n }\n\n}\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"string\").WithArguments(\"string\"));\n }\n\n [WorkItem(543167, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543167\")]\n [Fact]\n public void CS1525ERR_InvalidExprTerm_1()\n {\n CreateCompilation(\n@\"class D\n{\n public static void Main()\n { \n var s = 1?;\n }\n}\n\")\n .VerifyDiagnostics(\n // (5,19): error CS1525: Invalid expression term ';'\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \";\").WithArguments(\";\"),\n // (5,19): error CS1003: Syntax error, ':' expected\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_SyntaxError, \";\").WithArguments(\":\", \";\"),\n // (5,19): error CS1525: Invalid expression term ';'\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \";\").WithArguments(\";\"),\n // (5,17): error CS0029: Cannot implicitly convert type 'int' to 'bool'\n // var s = 1?;\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"1\").WithArguments(\"int\", \"bool\")\n );\n }\n\n [Fact]\n public void CS1525ERR_InvalidExprTerm_ConditionalOperator()\n {\n CreateCompilation(\n@\"class Program\n{\n static void Main(string[] args)\n {\n int x = 1;\n int y = 1;\n System.Console.WriteLine(((x == y)) ?); // Invalid\n System.Console.WriteLine(((x == y)) ? (x++)); // Invalid\n System.Console.WriteLine(((x == y)) ? (x++) : (x++) : ((((y++))))); // Invalid\n System.Console.WriteLine(((x == y)) ? : :); \t// Invalid\n }\n}\n\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, \")\").WithArguments(\")\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \")\").WithArguments(\":\", \")\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \")\").WithArguments(\")\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \")\").WithArguments(\":\", \")\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \")\").WithArguments(\")\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \":\").WithArguments(\",\", \":\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \"(\").WithArguments(\",\", \"(\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \":\").WithArguments(\":\"),\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \":\").WithArguments(\":\"),\n Diagnostic(ErrorCode.ERR_SyntaxError, \":\").WithArguments(\",\", \":\"));\n }\n\n [WorkItem(528657, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528657\")]\n [Fact]\n public void CS0106ERR_BadMemberFlag()\n {\n CreateCompilation(\n@\"new class MyClass\n{\n}\")\n .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadMemberFlag, \"MyClass\").WithArguments(\"new\"));\n }\n\n [Fact]\n public void CS1540ERR_BadProtectedAccess01()\n {\n var text = @\"\nnamespace CS1540\n{\n class Program1\n {\n static void Main()\n {\n Employee.PreparePayroll();\n }\n }\n\n class Person\n {\n protected virtual void CalculatePay() \n {\n }\n }\n\n class Manager : Person\n {\n protected override void CalculatePay() \n {\n }\n }\n\n class Employee : Person\n {\n public static void PreparePayroll()\n {\n Employee emp1 = new Employee();\n Person emp2 = new Manager();\n Person emp3 = new Employee();\n emp1.CalculatePay(); \n emp2.CalculatePay();\n emp3.CalculatePay();\n }\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 34, Column = 18 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 35, Column = 18 }});\n }\n\n [Fact]\n public void CS1540ERR_BadProtectedAccess02()\n {\n var text =\n@\"class A\n{\n protected object F;\n protected void M()\n {\n }\n protected object P { get; set; }\n public object Q { get; protected set; }\n public object R { protected get; set; }\n public object S { private get; set; }\n}\nclass B : A\n{\n void M(object o)\n {\n // base.\n base.M();\n base.P = base.F;\n base.Q = null;\n M(base.R);\n M(base.S);\n // a.\n A a = new A();\n a.M();\n a.P = a.F;\n a.Q = null;\n M(a.R);\n M(a.S);\n // G().\n G().M();\n G().P = G().F;\n G().Q = null;\n M(G().R);\n M(G().S);\n // no qualifier\n M();\n P = F;\n Q = null;\n M(R);\n M(S);\n // this.\n this.M();\n this.P = this.F;\n this.Q = null;\n M(this.R);\n M(this.S);\n // ((A)this).\n ((A)this).M();\n ((A)this).P = ((A)this).F;\n ((A)this).Q = null;\n M(((A)this).R);\n M(((A)this).S);\n }\n static A G()\n {\n return null;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (21,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(base.S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"base.S\").WithArguments(\"A.S\"),\n // (24,11): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.M();\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"M\").WithArguments(\"A.M()\", \"A\", \"B\"),\n // (25,11): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.P = a.F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"P\").WithArguments(\"A.P\", \"A\", \"B\"),\n // (25,17): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.P = a.F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"F\").WithArguments(\"A.F\", \"A\", \"B\"),\n // (26,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // a.Q = null;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"a.Q\").WithArguments(\"A.Q\", \"A\", \"B\"),\n // (27,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // M(a.R);\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"a.R\").WithArguments(\"A.R\", \"A\", \"B\"),\n // (28,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(a.S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"a.S\").WithArguments(\"A.S\"),\n // (30,13): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().M();\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"M\").WithArguments(\"A.M()\", \"A\", \"B\"),\n // (31,13): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().P = G().F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"P\").WithArguments(\"A.P\", \"A\", \"B\"),\n // (31,21): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().P = G().F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"F\").WithArguments(\"A.F\", \"A\", \"B\"),\n // (32,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // G().Q = null;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"G().Q\").WithArguments(\"A.Q\", \"A\", \"B\"),\n // (33,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // M(G().R);\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"G().R\").WithArguments(\"A.R\", \"A\", \"B\"),\n // (34,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(G().S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"G().S\").WithArguments(\"A.S\"),\n // (40,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"S\").WithArguments(\"A.S\"),\n // (46,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(this.S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"this.S\").WithArguments(\"A.S\"),\n // (48,19): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).M();\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"M\").WithArguments(\"A.M()\", \"A\", \"B\"),\n // (49,19): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).P = ((A)this).F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"P\").WithArguments(\"A.P\", \"A\", \"B\"),\n // (49,33): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).P = ((A)this).F;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"F\").WithArguments(\"A.F\", \"A\", \"B\"),\n // (50,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // ((A)this).Q = null;\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"((A)this).Q\").WithArguments(\"A.Q\", \"A\", \"B\"),\n // (51,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)\n // M(((A)this).R);\n Diagnostic(ErrorCode.ERR_BadProtectedAccess, \"((A)this).R\").WithArguments(\"A.R\", \"A\", \"B\"),\n // (52,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible\n // M(((A)this).S);\n Diagnostic(ErrorCode.ERR_InaccessibleGetter, \"((A)this).S\").WithArguments(\"A.S\"),\n // (3,22): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null\n // protected object F;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"F\").WithArguments(\"A.F\", \"null\")\n );\n }\n\n [WorkItem(540271, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540271\")]\n [Fact]\n public void CS0122ERR_BadAccessProtectedCtor()\n {\n // It is illegal to access any \"protected\" instance method with a \"this\" that is not of the \n // current class's type. Oddly enough, that includes constructors. It is legal to call\n // a protected ctor via \": base()\" because then the \"this\" is of the derived type. But\n // in a derived class you cannot call \"new MyBase()\" if the ctor is protected.\n //\n // The native compiler produces the error CS1540 whether the offending method is a regular\n // method or a ctor:\n //\n // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; \n // the qualifier must be of type 'Derived' (or derived from it)\n //\n // Though technically correct, this is a very confusing error message for this scenario;\n // one does not typically think of the constructor as being a method that is \n // called with an implicit \"this\" of a particular receiver type, even though of course\n // that is exactly what it is.\n //\n // The better error message here is to simply say that the best possible ctor cannot\n // be accessed because it is not accessible. That's what Roslyn does.\n //\n // CONSIDER: We might consider making up a new error message for this situation.\n\n // \n // CS0122: 'Base.Base' is inaccessible due to its protection level\n\n var text = @\"namespace CS0122\n{\n public class Base\n {\n protected Base() {}\n }\n\n public class Derived : Base\n {\n void M()\n {\n Base b = new Base(); \n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, \"Base\").WithArguments(\"CS0122.Base.Base()\"));\n }\n\n // CS1545ERR_BindToBogusProp2 --> Symbols\\Source\\EventTests.cs\n // CS1546ERR_BindToBogusProp1 --> Symbols\\Source\\PropertyTests.cs\n\n [WorkItem(528658, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528658\")]\n [Fact()]\n public void CS1560ERR_FileNameTooLong()\n {\n var text = @\"\n#line 1 \"\"ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\"\"\n\npublic class C {\n public void Main ()\n {\n }\n}\n\";\n //EDMAURER no need to enforce a limit here.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);//,\n //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FileNameTooLong, Line = 1, Column = 25 } });\n }\n\n [Fact]\n public void CS1579ERR_ForEachMissingMember()\n {\n var text = @\"\nusing System;\npublic class MyCollection\n{\n int[] items;\n public MyCollection()\n {\n items = new int[5] { 12, 44, 33, 2, 50 };\n }\n\n MyEnumerator GetEnumerator()\n {\n return new MyEnumerator(this);\n }\n\n public class MyEnumerator\n {\n int nIndex;\n MyCollection collection;\n public MyEnumerator(MyCollection coll)\n {\n collection = coll;\n nIndex = -1;\n }\n\n public bool MoveNext()\n {\n nIndex++;\n return (nIndex < collection.items.GetLength(0));\n }\n\n public int Current\n {\n get\n {\n return (collection.items[nIndex]);\n }\n }\n }\n\n public static void Main()\n {\n MyCollection col = new MyCollection();\n Console.WriteLine(\"\"Values in the collection are:\"\");\n foreach (int i in col) // CS1579\n {\n Console.WriteLine(i);\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (45,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method.\n // foreach (int i in col) // CS1579\n Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, \"col\").WithArguments(\"MyCollection\", \"collection\", \"MyCollection.GetEnumerator()\"),\n // (45,27): error CS1579: foreach statement cannot operate on variables of type 'MyCollection' because 'MyCollection' does not contain a public definition for 'GetEnumerator'\n // foreach (int i in col) // CS1579\n Diagnostic(ErrorCode.ERR_ForEachMissingMember, \"col\").WithArguments(\"MyCollection\", \"GetEnumerator\"));\n }\n\n [Fact]\n public void CS1579ERR_ForEachMissingMember02()\n {\n var text = @\"\npublic class Test\n{\n public static void Main(string[] args)\n {\n foreach (int x in F(1)) { }\n }\n static void F(int x) { }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ForEachMissingMember, \"F(1)\").WithArguments(\"void\", \"GetEnumerator\"));\n }\n\n [Fact]\n public void CS1593ERR_BadDelArgCount()\n {\n var text = @\"\nusing System;\ndelegate string func(int i); // declare delegate\n\nclass a\n{\n public static void Main()\n {\n func dt = new func(z);\n x(dt);\n }\n\n public static string z(int j)\n {\n Console.WriteLine(j);\n return j.ToString();\n }\n\n public static void x(func hello)\n {\n hello(8, 9); // CS1593\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgCount, Line = 21, Column = 9 } });\n }\n\n [Fact]\n public void CS1593ERR_BadDelArgCount_02()\n {\n var text = @\"\ndelegate void MyDelegate1(int x, float y);\nclass Program\n{\n public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); }\n static void Main(string[] args)\n {\n Program mc = new Program();\n MyDelegate1 md1 = null;\n md1 += mc.DelegatedMethod;\n md1(1);\n md1 -= mc.DelegatedMethod;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'MyDelegate1'\n // md1(1);\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"md1\").WithArguments(\"y\", \"MyDelegate1\").WithLocation(11, 9));\n }\n\n [Fact]\n public void CS1593ERR_BadDelArgCount_03()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n static void Main()\n {\n new Action(Console.WriteLine)(1, 1);\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadDelArgCount, \"new Action(Console.WriteLine)\").WithArguments(\"System.Action\", \"2\"));\n }\n\n [Fact()]\n public void CS1594ERR_BadDelArgTypes()\n {\n var text = @\"\nusing System;\ndelegate string func(int i); // declare delegate\n\nclass a\n{\n public static void Main()\n {\n func dt = new func(z);\n x(dt);\n }\n\n public static string z(int j)\n {\n Console.WriteLine(j);\n return j.ToString();\n }\n\n public static void x(func hello)\n {\n hello(\"\"8\"\"); // CS1594\n }\n}\n\";\n //EDMAURER Giving errors for the individual argument problems is better than generic \"delegate 'blah' has some invalid arguments\"\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 21, Column = 15 } });\n //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgTypes, Line = 21, Column = 9 } });\n }\n\n // TODO: change this to CS0051 in Roslyn?\n [Fact]\n public void CS1604ERR_AssgReadonlyLocal()\n {\n var text = @\"\nclass C\n{\n void M()\n {\n this = null;\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS1604: Cannot assign to 'this' because it is read-only\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS1605ERR_RefReadonlyLocal()\n {\n var text = @\"\nclass C\n{\n void Test()\n {\n Ref(ref this); //CS1605\n Out(out this); //CS1605\n }\n\n static void Ref(ref C c)\n {\n }\n\n static void Out(out C c)\n {\n c = null;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only\n Diagnostic(ErrorCode.ERR_RefReadonlyLocal, \"this\").WithArguments(\"this\"),\n // (7,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only\n Diagnostic(ErrorCode.ERR_RefReadonlyLocal, \"this\").WithArguments(\"this\"));\n }\n\n [Fact]\n public void CS1612ERR_ReturnNotLValue01()\n {\n var text = @\"\npublic struct MyStruct\n{\n public int Width;\n}\n\npublic class ListView\n{\n MyStruct ms;\n public MyStruct Size\n {\n get { return ms; }\n set { ms = value; }\n }\n}\n\npublic class MyClass\n{\n public MyClass()\n {\n ListView lvi;\n lvi = new ListView();\n lvi.Size.Width = 5; // CS1612\n }\n\n public static void Main()\n {\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnNotLValue, Line = 23, Column = 9 } });\n }\n\n /// \n /// Breaking change from Dev10. CS1612 is now reported for all value\n /// types, not just struct types. Specifically, CS1612 is now reported\n /// for type parameters constrained to \"struct\". (See also CS0131.)\n /// \n [WorkItem(528821, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528821\")]\n [Fact]\n public void CS1612ERR_ReturnNotLValue02()\n {\n var source =\n@\"interface I\n{\n object P { get; set; }\n}\nstruct S : I\n{\n public object P { get; set; }\n}\nclass C\n where T : struct, I\n where U : class, I\n where V : I\n{\n S F1 { get; set; }\n T F2 { get; set; }\n U F3 { get; set; }\n V F4 { get; set; }\n void M()\n {\n F1.P = null;\n F2.P = null;\n F3.P = null;\n F4.P = null;\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (20,9): error CS1612: Cannot modify the return value of 'C.F1' because it is not a variable\n Diagnostic(ErrorCode.ERR_ReturnNotLValue, \"F1\").WithArguments(\"C.F1\").WithLocation(20, 9),\n // (20,9): error CS1612: Cannot modify the return value of 'C.F2' because it is not a variable\n Diagnostic(ErrorCode.ERR_ReturnNotLValue, \"F2\").WithArguments(\"C.F2\").WithLocation(21, 9));\n }\n\n [Fact]\n public void CS1615ERR_BadArgExtraRef()\n {\n var text = @\"\nclass C\n{\n public void f(int i) {}\n public static void Main()\n {\n int i = 1;\n f(ref i); // CS1615\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 7 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgExtraRef, Line = 8, Column = 13 } });\n }\n\n [Fact()]\n public void CS1618ERR_DelegateOnConditional()\n {\n var text = @\"\nusing System.Diagnostics;\n\ndelegate void del();\n\nclass MakeAnError\n{\n public static void Main()\n {\n del d = new del(ConditionalMethod); // CS1618\n }\n [Conditional(\"\"DEBUG\"\")]\n public static void ConditionalMethod()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (10,25): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute\n // del d = new del(ConditionalMethod); // CS1618\n Diagnostic(ErrorCode.ERR_DelegateOnConditional, \"ConditionalMethod\").WithArguments(\"MakeAnError.ConditionalMethod()\").WithLocation(10, 25));\n }\n\n [Fact()]\n public void CS1618ERR_DelegateOnConditional_02()\n {\n var text = @\"\nusing System;\nusing System.Diagnostics;\n\ndelegate void del();\n\nclass MakeAnError\n{\n class Goo: Attribute\n {\n public Goo(object o) {}\n }\n\n [Conditional(\"\"DEBUG\"\")]\n [Goo(new del(ConditionalMethod))] // CS1618\n public static void ConditionalMethod()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,18): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute\n // [Goo(new del(ConditionalMethod))] // CS1618\n Diagnostic(ErrorCode.ERR_DelegateOnConditional, \"ConditionalMethod\").WithArguments(\"MakeAnError.ConditionalMethod()\").WithLocation(15, 18));\n }\n\n [Fact]\n public void CS1620ERR_BadArgRef()\n {\n var text = @\"\nclass C\n{\n void f(ref int i) { }\n public static void Main()\n {\n int x = 1;\n f(out x); // CS1620 - f takes a ref parameter, not an out parameter\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 9 }, //specifically omitted by roslyn\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgRef, Line = 8, Column = 15 } });\n }\n\n [Fact]\n public void CS1621ERR_YieldInAnonMeth()\n {\n var text = @\"\nusing System.Collections;\n\ndelegate object MyDelegate();\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n MyDelegate d = delegate\n {\n yield return this; // CS1621\n return this;\n };\n d();\n }\n\n public static void Main()\n {\n }\n}\n\";\n var comp = CreateCompilation(text);\n var expected = new DiagnosticDescription[] {\n // (12,13): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression\n // yield return this; // CS1621\n Diagnostic(ErrorCode.ERR_YieldInAnonMeth, \"yield\"),\n // (8,24): error CS0161: 'C.GetEnumerator()': not all code paths return a value\n // public IEnumerator GetEnumerator()\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"GetEnumerator\").WithArguments(\"C.GetEnumerator()\")\n };\n comp.VerifyDiagnostics(expected);\n comp.VerifyEmitDiagnostics(expected);\n }\n\n [Fact]\n public void CS1622ERR_ReturnInIterator()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n return (IEnumerator) this; // CS1622\n yield return this; // OK\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (8,7): error CS1622: Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.\n // return (IEnumerator) this; // CS1622\n Diagnostic(ErrorCode.ERR_ReturnInIterator, \"return\"),\n // (9,7): warning CS0162: Unreachable code detected\n // yield return this; // OK\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"yield\")\n );\n }\n\n [Fact]\n public void CS1623ERR_BadIteratorArgType()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n yield return 0;\n }\n\n public IEnumerator GetEnumerator(ref int i) // CS1623\n {\n yield return i;\n }\n\n public IEnumerator GetEnumerator(out float f) // CS1623\n {\n f = 0.0F;\n yield return f;\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (11,46): error CS1623: Iterators cannot have ref, in or out parameters\n // public IEnumerator GetEnumerator(ref int i) // CS1623\n Diagnostic(ErrorCode.ERR_BadIteratorArgType, \"i\"),\n // (16,48): error CS1623: Iterators cannot have ref, in or out parameters\n // public IEnumerator GetEnumerator(out float f) // CS1623\n Diagnostic(ErrorCode.ERR_BadIteratorArgType, \"f\")\n );\n }\n\n [Fact]\n public void CS1624ERR_BadIteratorReturn()\n {\n var text = @\"\nclass C\n{\n public int Iterator\n {\n get // CS1624\n {\n yield return 1;\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIteratorReturn, Line = 6, Column = 9 } });\n }\n\n [Fact]\n public void CS1625ERR_BadYieldInFinally()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n try\n {\n }\n finally\n {\n yield return this; // CS1625\n }\n }\n}\n\npublic class CMain\n{\n public static void Main() { }\n}\n\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (13,9): error CS1625: Cannot yield in the body of a finally clause\n // yield return this; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\")\n );\n }\n\n [Fact]\n public void CS1626ERR_BadYieldInTryOfCatch()\n {\n var text = @\"\nusing System.Collections;\n\nclass C : IEnumerable\n{\n public IEnumerator GetEnumerator()\n {\n try\n {\n yield return this; // CS1626\n }\n catch\n {\n \n }\n }\n}\n\npublic class CMain\n{\n public static void Main() { }\n}\n\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (10,10): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return this; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\")\n );\n }\n\n [Fact]\n public void CS1628ERR_AnonDelegateCantUse()\n {\n var text = @\"\ndelegate int MyDelegate();\n\nclass C\n{\n public static void F(ref int i)\n {\n MyDelegate d = delegate { return i; }; // CS1628\n }\n\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonDelegateCantUse, Line = 8, Column = 42 } });\n }\n\n [Fact]\n public void CS1629ERR_IllegalInnerUnsafe()\n {\n var text = @\"\nusing System.Collections.Generic;\nclass C \n{\n IEnumerator IteratorMeth() {\n int i;\n unsafe // CS1629\n {\n int *p = &i;\n yield return *p;\n }\n }\n\n unsafe IEnumerator IteratorMeth2() { // CS1629\n yield break;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (7,7): error CS1629: Unsafe code may not appear in iterators\n // unsafe // CS1629\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"unsafe\"),\n // (9,10): error CS1629: Unsafe code may not appear in iterators\n // int *p = &i;\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"int *\"),\n // (9,19): error CS1629: Unsafe code may not appear in iterators\n // int *p = &i;\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"&i\"),\n // (10,24): error CS1629: Unsafe code may not appear in iterators\n // yield return *p;\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"p\"),\n // (14,29): error CS1629: Unsafe code may not appear in iterators\n // unsafe IEnumerator IteratorMeth2() { // CS1629\n Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, \"IteratorMeth2\")\n );\n }\n\n [Fact]\n public void CS1631ERR_BadYieldInCatch()\n {\n var text = @\"\nusing System;\nusing System.Collections;\n\npublic class C : IEnumerable\n{\n public IEnumerator GetEnumerator() \n {\n try\n {\n }\n catch(Exception e)\n {\n yield return this; // CS1631\n }\n } \n\n public static void Main() \n {\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (14,9): error CS1631: Cannot yield a value in the body of a catch clause\n // yield return this; // CS1631\n Diagnostic(ErrorCode.ERR_BadYieldInCatch, \"yield\"),\n // (12,23): warning CS0168: The variable 'e' is declared but never used\n // catch(Exception e)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\")\n );\n }\n\n [Fact]\n public void CS1632ERR_BadDelegateLeave()\n {\n var text = @\"\ndelegate void MyDelegate();\nclass MyClass\n{\n public void Test()\n { \n for (int i = 0 ; i < 5 ; i++)\n {\n MyDelegate d = delegate {\n break; // CS1632\n }; \n }\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n// (10,13): error CS1632: Control cannot leave the body of an anonymous method or lambda expression\n// break; // CS1632\nDiagnostic(ErrorCode.ERR_BadDelegateLeave, \"break\")\n );\n }\n\n [Fact]\n public void CS1636ERR_VarargsIterator()\n {\n var text = @\"using System.Collections;\n\npublic class Test\n{\n IEnumerable Goo(__arglist)\n {\n yield return 1;\n }\n\n static int Main(string[] args)\n {\n return 1;\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n// (5,17): error CS1636: __arglist is not allowed in the parameter list of iterators\n// IEnumerable Goo(__arglist)\nDiagnostic(ErrorCode.ERR_VarargsIterator, \"Goo\"));\n }\n\n [Fact]\n public void CS1637ERR_UnsafeIteratorArgType()\n {\n var text = @\"\nusing System.Collections;\n\npublic unsafe class C\n{\n public IEnumerator Iterator1(int* p) // CS1637\n {\n yield return null;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,39): error CS1637: Iterators cannot have unsafe parameters or yield types\n Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, \"p\"));\n }\n\n [Fact()]\n public void CS1639ERR_BadCoClassSig()\n {\n // BREAKING CHANGE: Dev10 allows this test to compile, even though the output assembly is not verifiable and generates a runtime exception:\n // BREAKING CHANGE: We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error.\n\n var text = @\"\nusing System.Runtime.InteropServices;\n\n[ComImport, Guid(\"\"00020810-0000-0000-C000-000000000046\"\")]\n[CoClass(typeof(GenericClass<>))]\npublic interface InterfaceType {}\n\npublic class GenericClass: InterfaceType {}\n\npublic class Program\n{\n public static void Main() { var i = new InterfaceType(); }\n}\n \";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadCoClassSig, Line = 12, Column = 41 } }\n );\n }\n\n [Fact()]\n public void CS1640ERR_MultipleIEnumOfT()\n {\n var text = @\"\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic class C : IEnumerable, IEnumerable, IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n yield break;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n yield break;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return (IEnumerator)((IEnumerable)this).GetEnumerator();\n }\n}\n\npublic class Test\n{\n public static int Main()\n {\n foreach (int i in new C()) { } // CS1640\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MultipleIEnumOfT, Line = 27, Column = 27 } });\n }\n\n [WorkItem(7389, \"DevDiv_Projects/Roslyn\")]\n [Fact]\n public void CS1640ERR_MultipleIEnumOfT02()\n {\n var text = @\"\nusing System.Collections.Generic;\npublic class Test\n{\n public static void Main(string[] args)\n {\n }\n}\npublic class C where T : IEnumerable, IEnumerable\n{\n public static void TestForeach(T t)\n {\n foreach (int i in t) { }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"t\").WithArguments(\"T\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\"),\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"t\").WithArguments(\"T\", \"System.Collections.Generic.IEnumerable\"));\n }\n\n [Fact]\n public void CS1643ERR_AnonymousReturnExpected()\n {\n var text = @\"\ndelegate int MyDelegate();\n\nclass C\n{\n static void Main()\n {\n MyDelegate d = delegate\n { // CS1643\n int i = 0;\n if (i == 0)\n return 1;\n };\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,24): error CS1643: Not all code paths return a value in anonymous method of type 'MyDelegate'\n // MyDelegate d = delegate\n Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, \"delegate\").WithArguments(\"anonymous method\", \"MyDelegate\").WithLocation(8, 24)\n );\n }\n\n [Fact]\n public void CS1643ERR_AnonymousReturnExpected_Foreach()\n {\n var text = @\"\nusing System;\npublic class Test\n{\n public static void Main(string[] args)\n {\n string[] arr = null;\n Func f = () => { foreach (var x in arr) return x; };\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (8,61): error CS0029: Cannot implicitly convert type 'string' to 'int'\n // Func f = () => { foreach (var x in arr) return x; };\n Diagnostic(ErrorCode.ERR_NoImplicitConv, \"x\").WithArguments(\"string\", \"int\").WithLocation(8, 61),\n // (8,61): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type\n // Func f = () => { foreach (var x in arr) return x; };\n Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, \"x\").WithArguments(\"lambda expression\").WithLocation(8, 61),\n // (8,26): error CS1643: Not all code paths return a value in lambda expression of type 'Func'\n // Func f = () => { foreach (var x in arr) return x; };\n Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, \"=>\").WithArguments(\"lambda expression\", \"System.Func\").WithLocation(8, 26)\n );\n }\n\n [Fact]\n public void CS1648ERR_AssgReadonly2()\n {\n var text = @\"\npublic struct Inner\n {\n public int i;\n }\n\nclass Outer\n{ \n public readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void Main()\n {\n Outer outer = new Outer();\n outer.inner.i = 1; // CS1648\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonly2, Line = 17, Column = 7 } });\n }\n\n [Fact]\n public void CS1649ERR_RefReadonly2()\n {\n var text = @\"\npublic struct Inner\n{\n public int i;\n}\n\nclass Outer\n{\n public readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void f(ref int iref)\n {\n }\n\n static void Main()\n {\n Outer outer = new Outer();\n f(ref outer.inner.i); // CS1649\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (21,15): error CS1649: Members of readonly field 'Outer.inner' cannot be used as a ref or out value (except in a constructor)\n // f(ref outer.inner.i); // CS1649\n Diagnostic(ErrorCode.ERR_RefReadonly2, \"outer.inner.i\").WithArguments(\"Outer.inner\").WithLocation(21, 15)\n);\n }\n\n [Fact]\n public void CS1650ERR_AssgReadonlyStatic2()\n {\n string text =\n@\"public struct Inner\n{\n public int i;\n}\n\nclass Outer\n{\n public static readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void Main()\n {\n Outer.inner.i = 1; // CS1650\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,9): error CS1650: Fields of static readonly field 'Outer.inner' cannot be assigned to (except in a static constructor or a variable initializer)\n Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, \"Outer.inner.i\").WithArguments(\"Outer.inner\"));\n }\n\n [Fact]\n public void CS1651ERR_RefReadonlyStatic2()\n {\n var text = @\"\npublic struct Inner\n{\n public int i;\n}\n\nclass Outer\n{\n public static readonly Inner inner = new Inner();\n}\n\nclass D\n{\n static void f(ref int iref)\n {\n }\n\n static void Main()\n {\n f(ref Outer.inner.i); // CS1651\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (20,15): error CS1651: Fields of static readonly field 'Outer.inner' cannot be passed ref or out (except in a static constructor)\n Diagnostic(ErrorCode.ERR_RefReadonlyStatic2, \"Outer.inner.i\").WithArguments(\"Outer.inner\"));\n }\n\n [Fact]\n public void CS1654ERR_AssgReadonlyLocal2Cause()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nnamespace CS1654\n{\n struct Book\n {\n public string Title;\n public string Author;\n public double Price;\n public Book(string t, string a, double p)\n {\n Title = t;\n Author = a;\n Price = p;\n\n }\n }\n\n class Program\n {\n List list;\n static void Main(string[] args)\n {\n Program prog = new Program();\n prog.list = new List();\n foreach (Book b in prog.list)\n {\n b.Price += 9.95; // CS1654\n }\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (29,17): error CS1654: Cannot modify members of 'b' because it is a 'foreach iteration variable'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocal2Cause, \"b.Price\").WithArguments(\"b\", \"foreach iteration variable\"));\n }\n\n [Fact]\n public void CS1655ERR_RefReadonlyLocal2Cause()\n {\n var text = @\"\nstruct S \n{\n public int i;\n}\n\nclass CMain\n{\n static void f(ref int iref)\n {\n }\n \n public static void Main()\n {\n S[] sa = new S[10];\n foreach(S s in sa)\n {\n CMain.f(ref s.i); // CS1655\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,21): error CS1655: Cannot pass fields of 's' as a ref or out argument because it is a 'foreach iteration variable'\n // CMain.f(ref s.i); // CS1655\n Diagnostic(ErrorCode.ERR_RefReadonlyLocal2Cause, \"s.i\").WithArguments(\"s\", \"foreach iteration variable\")\n );\n }\n\n [Fact]\n public void CS1656ERR_AssgReadonlyLocalCause01()\n {\n var text = @\"\nusing System;\n\nclass C : IDisposable\n{\n public void Dispose() { }\n}\n\nclass CMain\n{\n unsafe public static void Main()\n {\n using (C c = new C())\n {\n c = new C(); // CS1656\n }\n\n int[] ary = new int[] { 1, 2, 3, 4 };\n fixed (int* p = ary)\n {\n p = null; // CS1656\n }\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (13,13): error CS1656: Cannot assign to 'c' because it is a 'using variable'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"c\").WithArguments(\"c\", \"using variable\").WithLocation(15, 13),\n // (19,13): error CS1656: Cannot assign to 'p' because it is a 'fixed variable'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"p\").WithArguments(\"p\", \"fixed variable\").WithLocation(21, 13));\n }\n\n [Fact]\n public void CS1656ERR_AssgReadonlyLocalCause02()\n {\n var text =\n@\"class C\n{\n static void M()\n {\n M = null;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,9): error CS1656: Cannot assign to 'M' because it is a 'method group'\n Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"M\").WithArguments(\"M\", \"method group\").WithLocation(5, 9));\n }\n\n [Fact]\n public void CS1656ERR_AssgReadonlyLocalCause_NestedForeach()\n {\n var text = @\"\npublic class Test\n{\n static public void Main(string[] args)\n {\n string S = \"\"ABC\"\";\n string T = \"\"XYZ\"\";\n foreach (char x in S)\n {\n foreach (char y in T)\n {\n x = 'M';\n }\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, \"x\").WithArguments(\"x\", \"foreach iteration variable\"));\n }\n\n [Fact]\n public void CS1657ERR_RefReadonlyLocalCause()\n {\n var text = @\"\nclass C\n{\n static void F(ref string s)\n {\n }\n\n static void Main(string[] args)\n {\n foreach (var a in args)\n {\n F(ref a); //CS1657\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (12,19): error CS1657: Cannot use 'a' as a ref or out value because it is a 'foreach iteration variable'\n // F(ref a); //CS1657\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"a\").WithArguments(\"a\", \"foreach iteration variable\").WithLocation(12, 19)\n );\n }\n\n [Fact]\n public void CS1660ERR_AnonMethToNonDel()\n {\n var text = @\"\ndelegate int MyDelegate();\nclass C {\n static void Main()\n {\n int i = delegate { return 1; }; // CS1660\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethToNonDel, Line = 6, Column = 14 } });\n }\n\n [Fact]\n public void CS1661ERR_CantConvAnonMethParams()\n {\n var text = @\"\ndelegate void MyDelegate(int i);\n\nclass C\n{\n public static void Main()\n {\n MyDelegate d = delegate(string s) { }; // CS1661\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 8, Column = 24 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 8, Column = 40 }\n });\n }\n\n [Fact]\n public void CS1662ERR_CantConvAnonMethReturns()\n {\n var text = @\"\ndelegate int MyDelegate(int i);\n\nclass C\n{\n delegate double D();\n public static void Main()\n {\n MyDelegate d = delegate(int i) { return 1.0; }; // CS1662\n D dd = () => { return \"\"Who knows the real sword of Gryffindor?\"\"; };\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,49): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)\n // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662\n Diagnostic(ErrorCode.ERR_NoImplicitConvCast, \"1.0\").WithArguments(\"double\", \"int\").WithLocation(9, 49),\n // (9,49): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type\n // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662\n Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, \"1.0\").WithArguments(\"anonymous method\").WithLocation(9, 49),\n // (10,31): error CS0029: Cannot implicitly convert type 'string' to 'double'\n // D dd = () => { return \"Who knows the real sword of Gryffindor?\"; };\n Diagnostic(ErrorCode.ERR_NoImplicitConv, @\"\"\"Who knows the real sword of Gryffindor?\"\"\").WithArguments(\"string\", \"double\").WithLocation(10, 31),\n // (10,31): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type\n // D dd = () => { return \"Who knows the real sword of Gryffindor?\"; };\n Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @\"\"\"Who knows the real sword of Gryffindor?\"\"\").WithArguments(\"lambda expression\").WithLocation(10, 31)\n );\n }\n\n [Fact]\n public void CS1666ERR_FixedBufferNotFixedErr()\n {\n var text = @\"\nunsafe struct S\n{\n public fixed int buffer[1];\n}\n\nunsafe class Test\n{\n public static void Main()\n {\n var inst = new Test();\n System.Console.Write(inst.example1());\n System.Console.Write(inst.field.buffer[0]);\n System.Console.Write(inst.example2());\n System.Console.Write(inst.field.buffer[0]);\n }\n\n S field = new S();\n\n private int example1()\n {\n return (field.buffer[0] = 7); // OK\n }\n\n private int example2()\n {\n fixed (int* p = field.buffer)\n {\n return (p[0] = 8); // OK\n }\n }\n}\n\";\n\n CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(\n // (13,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater.\n // System.Console.Write(inst.field.buffer[0]);\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, \"inst.field.buffer\").WithArguments(\"indexing movable fixed buffers\", \"7.3\").WithLocation(13, 30),\n // (15,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater.\n // System.Console.Write(inst.field.buffer[0]);\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, \"inst.field.buffer\").WithArguments(\"indexing movable fixed buffers\", \"7.3\").WithLocation(15, 30),\n // (22,17): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater.\n // return (field.buffer[0] = 7); // OK\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, \"field.buffer\").WithArguments(\"indexing movable fixed buffers\", \"7.3\").WithLocation(22, 17)\n );\n }\n\n [Fact]\n public void CS1666ERR_FixedBufferNotUnsafeErr()\n {\n var text = @\"\nunsafe struct S\n{\n public fixed int buffer[1];\n}\n\nclass Test\n{\n public static void Main()\n {\n var inst = new Test();\n System.Console.Write(inst.example1());\n System.Console.Write(inst.field.buffer[0]);\n }\n\n S field = new S();\n\n private int example1()\n {\n return (field.buffer[0] = 7); // OK\n }\n}\n\";\n\n CreateCompilation(text, options: TestOptions.UnsafeReleaseExe).VerifyDiagnostics(\n // (13,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context\n // System.Console.Write(inst.field.buffer[0]);\n Diagnostic(ErrorCode.ERR_UnsafeNeeded, \"inst.field.buffer\").WithLocation(13, 30),\n // (20,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context\n // return (field.buffer[0] = 7); // OK\n Diagnostic(ErrorCode.ERR_UnsafeNeeded, \"field.buffer\").WithLocation(20, 17)\n );\n }\n\n [Fact]\n public void CS1666ERR_FixedBufferNotFixed()\n {\n var text = @\"\nunsafe struct S\n{\n public fixed int buffer[1];\n}\n\nunsafe class Test\n{\n public static void Main()\n {\n var inst = new Test();\n System.Console.Write(inst.example1());\n System.Console.Write(inst.field.buffer[0]);\n System.Console.Write(inst.example2());\n System.Console.Write(inst.field.buffer[0]);\n }\n\n S field = new S();\n\n private int example1()\n {\n return (field.buffer[0] = 7); // OK\n }\n\n private int example2()\n {\n fixed (int* p = field.buffer)\n {\n return (p[0] = 8); // OK\n }\n }\n}\n\";\n\n var c = CompileAndVerify(text, expectedOutput: \"7788\", verify: Verification.Fails, options: TestOptions.UnsafeReleaseExe);\n\n c.VerifyIL(\"Test.example1()\", @\"\n{\n // Code size 22 (0x16)\n .maxstack 3\n .locals init (int V_0)\n IL_0000: ldarg.0\n IL_0001: ldflda \"\"S Test.field\"\"\n IL_0006: ldflda \"\"int* S.buffer\"\"\n IL_000b: ldflda \"\"int S.e__FixedBuffer.FixedElementField\"\"\n IL_0010: ldc.i4.7\n IL_0011: dup\n IL_0012: stloc.0\n IL_0013: stind.i4\n IL_0014: ldloc.0\n IL_0015: ret\n}\n\");\n\n c.VerifyIL(\"Test.example2()\", @\"\n{\n // Code size 25 (0x19)\n .maxstack 3\n .locals init (pinned int& V_0,\n int V_1)\n IL_0000: ldarg.0\n IL_0001: ldflda \"\"S Test.field\"\"\n IL_0006: ldflda \"\"int* S.buffer\"\"\n IL_000b: ldflda \"\"int S.e__FixedBuffer.FixedElementField\"\"\n IL_0010: stloc.0\n IL_0011: ldloc.0\n IL_0012: conv.u\n IL_0013: ldc.i4.8\n IL_0014: dup\n IL_0015: stloc.1\n IL_0016: stind.i4\n IL_0017: ldloc.1\n IL_0018: ret\n}\n\");\n }\n\n [Fact]\n public void CS1669ERR_IllegalVarArgs01()\n {\n var source =\n@\"class C \n{\n delegate void D(__arglist); // CS1669\n static void Main() {}\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,21): error CS1669: __arglist is not valid in this context\n // delegate void D(__arglist); // CS1669\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\")\n );\n }\n\n [Fact]\n public void CS1669ERR_IllegalVarArgs02()\n {\n var source =\n@\"class C\n{\n object this[object index, __arglist]\n {\n get { return null; }\n }\n public static C operator +(C c1, __arglist) { return c1; }\n public static implicit operator int(__arglist) { return 0; }\n\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (3,31): error CS1669: __arglist is not valid in this context\n // object this[object index, __arglist]\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\"),\n\n // (7,38): error CS1669: __arglist is not valid in this context\n // public static C operator +(C c1, __arglist) { return c1; }\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\"),\n\n // (8,41): error CS1669: __arglist is not valid in this context\n // public static implicit operator int(__arglist) { return 0; }\n Diagnostic(ErrorCode.ERR_IllegalVarArgs, \"__arglist\")\n );\n }\n\n [WorkItem(863433, \"DevDiv/Personal\")]\n [Fact]\n public void CS1670ERR_IllegalParams()\n {\n // TODO: extra 1670 (not check for now)\n var test = @\"\ndelegate int MyDelegate(params int[] paramsList);\nclass Test\n{\n public static int Main()\n {\n MyDelegate d = delegate(params int[] paramsList) // CS1670\n {\n return paramsList[0];\n }; \n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IllegalParams, Line = 7, Column = 33 } });\n }\n\n [Fact]\n public void CS1673ERR_ThisStructNotInAnonMeth01()\n {\n var text = @\"\ndelegate int MyDelegate();\n\npublic struct S\n{\n int member;\n\n public int F(int i)\n {\n member = i;\n MyDelegate d = delegate()\n {\n i = this.member; // CS1673\n return i;\n\n };\n return d();\n }\n}\n\nclass CMain\n{\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } });\n }\n\n [Fact]\n public void CS1673ERR_ThisStructNotInAnonMeth02()\n {\n var text = @\"\ndelegate int MyDelegate();\n\npublic struct S\n{\n int member;\n\n public int F(int i)\n {\n member = i;\n MyDelegate d = delegate()\n {\n i = member; // CS1673\n return i;\n\n };\n return d();\n }\n}\n\nclass CMain\n{\n public static void Main()\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } });\n }\n\n [Fact]\n public void CS1674ERR_NoConvToIDisp()\n {\n var text = @\"\nclass C\n{\n public static void Main()\n {\n using (int a = 0) // CS1674\n using (a); //CS1674\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,22): warning CS0642: Possible mistaken empty statement\n Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, \";\"),\n // (6,16): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'.\n Diagnostic(ErrorCode.ERR_NoConvToIDisp, \"int a = 0\").WithArguments(\"int\"),\n // (7,20): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'.\n Diagnostic(ErrorCode.ERR_NoConvToIDisp, \"a\").WithArguments(\"int\"));\n }\n\n [Fact]\n public void CS1676ERR_BadParamRef()\n {\n var text = @\"\ndelegate void E(ref int i);\nclass Errors \n{\n static void Main()\n {\n E e = delegate(out int i) { }; // CS1676\n }\n}\n\";\n var compilation = CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (7,13): error CS1661: Cannot convert anonymous method to delegate type 'E' because the parameter types do not match the delegate parameter types\n // E e = delegate(out int i) { }; // CS1676\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate(out int i) { }\").WithArguments(\"anonymous method\", \"E\"),\n // (7,22): error CS1676: Parameter 1 must be declared with the 'ref' keyword\n // E e = delegate(out int i) { }; // CS1676\n Diagnostic(ErrorCode.ERR_BadParamRef, \"i\").WithArguments(\"1\", \"ref\"),\n // (7,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method\n // E e = delegate(out int i) { }; // CS1676\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"delegate(out int i) { }\").WithArguments(\"i\")\n );\n }\n\n [Fact]\n public void CS1677ERR_BadParamExtraRef()\n {\n var text = @\"\ndelegate void D(int i);\nclass Errors\n{\n static void Main()\n {\n D d = delegate(out int i) { }; // CS1677\n D d = delegate(ref int j) { }; // CS1677\n }\n}\n\";\n var compilation = CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (7,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types\n // D d = delegate(out int i) { }; // CS1677\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate(out int i) { }\").WithArguments(\"anonymous method\", \"D\"),\n // (7,24): error CS1677: Parameter 1 should not be declared with the 'out' keyword\n // D d = delegate(out int i) { }; // CS1677\n Diagnostic(ErrorCode.ERR_BadParamExtraRef, \"i\").WithArguments(\"1\", \"out\"),\n // (8,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types\n // D d = delegate(ref int j) { }; // CS1677\n Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, \"delegate(ref int j) { }\").WithArguments(\"anonymous method\", \"D\"),\n // (8,24): error CS1677: Parameter 1 should not be declared with the 'ref' keyword\n // D d = delegate(ref int j) { }; // CS1677\n Diagnostic(ErrorCode.ERR_BadParamExtraRef, \"j\").WithArguments(\"1\", \"ref\"),\n // (8,11): error CS0128: A local variable named 'd' is already defined in this scope\n // D d = delegate(ref int j) { }; // CS1677\n Diagnostic(ErrorCode.ERR_LocalDuplicate, \"d\").WithArguments(\"d\"),\n // (7,15): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method\n // D d = delegate(out int i) { }; // CS1677\n Diagnostic(ErrorCode.ERR_ParamUnassigned, \"delegate(out int i) { }\").WithArguments(\"i\")\n );\n }\n\n [Fact]\n public void CS1678ERR_BadParamType()\n {\n var text = @\"\ndelegate void D(int i);\nclass Errors\n{\n static void Main()\n {\n D d = delegate(string s) { }; // CS1678\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] {\n new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 7, Column = 15 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 7, Column = 31 }\n });\n }\n\n [Fact]\n public void CS1681ERR_GlobalExternAlias()\n {\n var text = @\"\nextern alias global;\n\nclass myClass\n{\n static int Main()\n {\n //global::otherClass oc = new global::otherClass();\n return 0;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (2,14): error CS1681: You cannot redefine the global extern alias\n // extern alias global;\n Diagnostic(ErrorCode.ERR_GlobalExternAlias, \"global\"),\n // (2,14): error CS0430: The extern alias 'global' was not specified in a /reference option\n // extern alias global;\n Diagnostic(ErrorCode.ERR_BadExternAlias, \"global\").WithArguments(\"global\"),\n // (2,1): info CS8020: Unused extern alias.\n // extern alias global;\n Diagnostic(ErrorCode.HDN_UnusedExternAlias, \"extern alias global;\")\n );\n }\n\n [Fact]\n public void CS1686ERR_LocalCantBeFixedAndHoisted()\n {\n var text = @\"\nclass MyClass\n{\n public unsafe delegate int* MyDelegate();\n\n public unsafe int* Test()\n {\n int j = 0;\n MyDelegate d = delegate { return &j; }; // CS1686\n return &j; // CS1686\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,42): error CS1686: Local 'j' or its members cannot have their address taken and be used inside an anonymous method or lambda expression\n // MyDelegate d = delegate { return &j; }; // CS1686\n Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, \"&j\").WithArguments(\"j\"));\n }\n\n [Fact]\n public void CS1686ERR_LocalCantBeFixedAndHoisted02()\n {\n var text = @\"using System;\n\nunsafe struct S\n{\n public fixed int buffer[1];\n public int i;\n}\n\nunsafe class Test\n{\n private void example1()\n {\n S data = new S();\n data.i = data.i + 1;\n Func lambda = () => data;\n fixed (int* p = data.buffer) // fail due to receiver being a local\n {\n }\n int *q = data.buffer; // fail due to lambda capture\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (16,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression\n // fixed (int* p = data.buffer) // fail due to receiver being a local\n Diagnostic(ErrorCode.ERR_FixedNotNeeded, \"data.buffer\"),\n // (19,18): error CS1686: Local 'data' or its members cannot have their address taken and be used inside an anonymous method or lambda expression\n // int *q = data.buffer; // fail due to lambda capture\n Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, \"data.buffer\").WithArguments(\"data\")\n );\n }\n\n [WorkItem(580537, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580537\")]\n [Fact]\n public void CS1686ERR_LocalCantBeFixedAndHoisted03()\n {\n var text = @\"unsafe\npublic struct Test\n{\n private delegate int D();\n public fixed int i[1];\n public void example()\n {\n Test t = this;\n t.i[0] = 5;\n D d = delegate {\n var x = t;\n return 0;\n };\n }\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,9): error CS1686: Local 't' or its members cannot have their address taken and be used inside an anonymous method or lambda expression\n // t.i[0] = 5;\n Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, \"t.i\").WithArguments(\"t\")\n );\n }\n\n [Fact]\n public void CS1688ERR_CantConvAnonMethNoParams()\n {\n var text = @\"\nusing System;\ndelegate void OutParam(out int i);\nclass ErrorCS1676\n{\n static void Main()\n {\n OutParam o;\n o = delegate // CS1688\n {\n Console.WriteLine(\"\");\n };\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,31): error CS1010: Newline in constant\n // Console.WriteLine(\");\n Diagnostic(ErrorCode.ERR_NewlineInConst, \"\").WithLocation(11, 31),\n // (11,34): error CS1026: ) expected\n // Console.WriteLine(\");\n Diagnostic(ErrorCode.ERR_CloseParenExpected, \"\").WithLocation(11, 34),\n // (11,34): error CS1002: ; expected\n // Console.WriteLine(\");\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(11, 34),\n // (9,13): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'OutParam' because it has one or more out parameters\n // o = delegate // CS1688\n Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, @\"delegate // CS1688\n {\n Console.WriteLine(\"\");\n }\").WithArguments(\"OutParam\").WithLocation(9, 13)\n );\n }\n\n [Fact]\n public void CS1708ERR_FixedNeedsLvalue()\n {\n var text = @\"\nunsafe public struct S\n{\n public fixed char name[10];\n}\n\npublic unsafe class C\n{\n public S UnsafeMethod()\n {\n S myS = new S();\n return myS;\n }\n\n static void Main()\n {\n C myC = new C();\n myC.UnsafeMethod().name[3] = 'a'; // CS1708\n C._s1.name[3] = 'a'; // CS1648\n myC._s2.name[3] = 'a'; // CS1648\n }\n\n static readonly S _s1;\n public readonly S _s2;\n}\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (18,9): error CS1708: Fixed size buffers can only be accessed through locals or fields\n // myC.UnsafeMethod().name[3] = 'a'; // CS1708\n Diagnostic(ErrorCode.ERR_FixedNeedsLvalue, \"myC.UnsafeMethod().name\").WithLocation(18, 9),\n // (19,9): error CS1650: Fields of static readonly field 'C._s1' cannot be assigned to (except in a static constructor or a variable initializer)\n // C._s1.name[3] = 'a'; // CS1648\n Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, \"C._s1.name[3]\").WithArguments(\"C._s1\").WithLocation(19, 9),\n // (20,9): error CS1648: Members of readonly field 'C._s2' cannot be modified (except in a constructor, an init-only member or a variable initializer)\n // myC._s2.name[3] = 'a'; // CS1648\n Diagnostic(ErrorCode.ERR_AssgReadonly2, \"myC._s2.name[3]\").WithArguments(\"C._s2\").WithLocation(20, 9)\n );\n }\n\n [Fact, WorkItem(543995, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543995\"), WorkItem(544258, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258\")]\n public void CS1728ERR_DelegateOnNullable()\n {\n var text = @\"\nusing System;\nclass Test\n{\n static void Main()\n {\n int? x = null;\n\n Func f1 = x.ToString; // no error\n Func f2 = x.GetHashCode; // no error\n Func f3 = x.Equals; // no error\n Func f4 = x.GetType; // no error\n\n Func x1 = x.GetValueOrDefault; // 1728\n Func x2 = x.GetValueOrDefault; // 1728\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (14,24): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault()' because it is a member of 'System.Nullable'\n // Func x1 = x.GetValueOrDefault; // 1728\n Diagnostic(ErrorCode.ERR_DelegateOnNullable, \"x.GetValueOrDefault\").WithArguments(\"int?.GetValueOrDefault()\"),\n // (15,29): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault(int)' because it is a member of 'System.Nullable'\n // Func x2 = x.GetValueOrDefault; // 1728\n Diagnostic(ErrorCode.ERR_DelegateOnNullable, \"x.GetValueOrDefault\").WithArguments(\"int?.GetValueOrDefault(int)\")\n );\n }\n\n [Fact, WorkItem(999399, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399\")]\n public void CS1729ERR_BadCtorArgCount()\n {\n var text = @\"\nclass Test\n{\n static int Main()\n {\n double d = new double(4.5); // was CS0143 (Dev10)\n Test test1 = new Test(2); // CS1729\n Test test2 = new Test();\n Parent exampleParent1 = new Parent(10); // CS1729\n Parent exampleParent2 = new Parent(10, 1);\n if (test1 == test2 & exampleParent1 == exampleParent2) {}\n return 1;\n }\n}\n\npublic class Parent\n{\n public Parent(int i, int j) { }\n}\n\npublic class Child : Parent { } // CS1729\n\npublic class Child2 : Parent\n{\n public Child2(int k)\n : base(k, 0)\n {\n }\n}\";\n var compilation = CreateCompilation(text);\n\n DiagnosticDescription[] expected = {\n // (21,14): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Parent.Parent(int, int)'\n // public class Child : Parent { } // CS1729\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"Child\").WithArguments(\"i\", \"Parent.Parent(int, int)\").WithLocation(21, 14),\n // (6,24): error CS1729: 'double' does not contain a constructor that takes 1 arguments\n // double d = new double(4.5); // was CS0143 (Dev10)\n Diagnostic(ErrorCode.ERR_BadCtorArgCount, \"double\").WithArguments(\"double\", \"1\").WithLocation(6, 24),\n // (7,26): error CS1729: 'Test' does not contain a constructor that takes 1 arguments\n // Test test1 = new Test(2); // CS1729\n Diagnostic(ErrorCode.ERR_BadCtorArgCount, \"Test\").WithArguments(\"Test\", \"1\").WithLocation(7, 26),\n // (9,37): error CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'Parent.Parent(int, int)'\n // Parent exampleParent1 = new Parent(10); // CS1729\n Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, \"Parent\").WithArguments(\"j\", \"Parent.Parent(int, int)\").WithLocation(9, 37)\n };\n\n compilation.VerifyDiagnostics(expected);\n\n compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single(), filterSpanWithinTree: null, includeEarlierStages: true).Verify(expected);\n }\n\n [WorkItem(539631, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539631\")]\n [Fact]\n public void CS1729ERR_BadCtorArgCount02()\n {\n var text = @\"\nclass MyClass\n{\n int intI = 1;\n MyClass()\n {\n intI = 2;\n }\n\n //this constructor initializer\n MyClass(int intJ) : this(3, 4) // CS1729\n {\n intI = intI * intJ;\n }\n}\n\nclass MyBase\n{\n public int intI = 1;\n protected MyBase()\n {\n intI = 2;\n }\n protected MyBase(int intJ)\n {\n intI = intJ;\n }\n}\n\nclass MyDerived : MyBase\n{\n MyDerived() : base(3, 4) // CS1729\n {\n intI = intI * 2;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 11, Column = 25 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 32, Column = 19 });\n }\n\n [Fact]\n public void CS1737ERR_DefaultValueBeforeRequiredValue()\n {\n var text = @\"\nclass C\n{\n public void Goo(string s = null, int x)\n {\n }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueBeforeRequiredValue, Line = 4, Column = 43 } } //sic: error on close paren\n );\n }\n\n [WorkItem(539007, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539007\")]\n [Fact]\n public void DevDiv4792_OptionalBeforeParams()\n {\n var text = @\"\nclass C\n{\n public void Goo(string s = null, params int[] ints)\n {\n }\n}\n\";\n //no errors\n var comp = CreateCompilation(text);\n Assert.False(comp.GetDiagnostics().Any());\n }\n\n [WorkItem(527351, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527351\")]\n [Fact]\n public void CS1738ERR_NamedArgumentSpecificationBeforeFixedArgument()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(age: 5,\"\"\"\");\n return 0;\n }\n public static void Test(int age, string Name)\n { }\n}\";\n var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6);\n comp.VerifyDiagnostics(\n // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.\n // Test(age: 5,\"\");\n Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, @\"\"\"\"\"\").WithArguments(\"7.2\").WithLocation(6, 21)\n );\n }\n\n [Fact]\n public void CS1739ERR_BadNamedArgument()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(5,Nam:null);\n return 0;\n }\n public static void Test(int age , string Name)\n { }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } });\n }\n\n [Fact, WorkItem(866112, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866112\")]\n public void CS1739ERR_BadNamedArgument_1()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(1, 2, Name:3);\n }\n\n public static void Test(params int [] array)\n { }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } });\n }\n\n [Fact]\n public void CS1740ERR_DuplicateNamedArgument()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(age: 5, Name: \"\"5\"\", Name: \"\"\"\");\n return 0;\n }\n public static void Test(int age, string Name)\n {\n }\n}\";\n var compilation = CSharpTestBase.CreateCompilation(text);\n compilation.VerifyDiagnostics(\n // (6,33): error CS1740: Named argument 'Name' cannot be specified multiple times\n // Test(age: 5, Name: \"5\", Name: \"\");\n Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, \"Name\").WithArguments(\"Name\").WithLocation(6, 33));\n }\n\n [Fact]\n public void CS1742ERR_NamedArgumentForArray()\n {\n var text = @\"\npublic class B\n{\n static int Main()\n {\n int[] arr = { };\n int s = arr[arr: 1];\n s = s + 1;\n return 1;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1742, Line = 7, Column = 17 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n Test(5, age: 3);\n return 0;\n }\n public static void Test(int age , string Name)\n { }\n}\";\n // CS1744: Named argument 'q' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 21 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional2()\n {\n // Unfortunately we allow \"void M(params int[] x)\" to be called in the expanded\n // form as \"M(x : 123);\". However, we still do not allow \"M(123, x:456);\".\n\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(5, x: 3);\n }\n public static void Test(params int[] x) { }\n}\";\n // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional3()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(5, x : 6);\n }\n public static void Test(int x, int y = 10, params int[] z) { }\n}\";\n // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } });\n }\n\n [Fact]\n public void CS1744ERR_NamedArgumentUsedInPositional4()\n {\n var text = @\"\npublic class C\n{\n public static void Main()\n {\n Test(5, 6, 7, 8, 9, 10, z : 6);\n }\n public static void Test(int x, int y = 10, params int[] z) { }\n}\";\n // CS1744: Named argument 'z' specifies a parameter for which a positional argument has already been given.\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 33 } });\n }\n\n [Fact]\n public void CS1746ERR_BadNamedArgumentForDelegateInvoke()\n {\n var text = @\"\npublic class C\n{\n delegate int MyDg(int age);\n public static int Main()\n {\n MyDg dg = new MyDg(Test);\n int S = dg(Ne: 3);\n return 0;\n }\n public static int Test(int age)\n { return 1; }\n}\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = 1746, Line = 8, Column = 24 } });\n }\n\n // [Fact()]\n // public void CS1752ERR_FixedNeedsLvalue()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FixedNeedsLvalue, Line = 20, Column = 9 } }\n // );\n // }\n\n // CS1912 --> ObjectAndCollectionInitializerTests.cs\n // CS1913 --> ObjectAndCollectionInitializerTests.cs\n // CS1914 --> ObjectAndCollectionInitializerTests.cs\n // CS1917 --> ObjectAndCollectionInitializerTests.cs\n // CS1918 --> ObjectAndCollectionInitializerTests.cs\n // CS1920 --> ObjectAndCollectionInitializerTests.cs\n // CS1921 --> ObjectAndCollectionInitializerTests.cs\n // CS1922 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1919ERR_UnsafeTypeInObjectCreation()\n {\n var text = @\"\nunsafe public class C\n{\n public static int Main()\n {\n var col1 = new int*(); // CS1919\n var col2 = new char*(); // CS1919\n return 1;\n }\n}\n\";\n CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (6,20): error CS1919: Unsafe type 'int*' cannot be used in object creation\n Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, \"new int*()\").WithArguments(\"int*\"),\n // (7,20): error CS1919: Unsafe type 'char*' cannot be used in object creation\n Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, \"new char*()\").WithArguments(\"char*\"));\n }\n\n [Fact]\n public void CS1928ERR_BadExtensionArgTypes()\n {\n var text =\n@\"class C\n{\n static void M(float f)\n {\n f.F();\n }\n}\nstatic class S\n{\n internal static void F(this double d) { }\n}\";\n var compilation = CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore });\n // Previously ERR_BadExtensionArgTypes.\n compilation.VerifyDiagnostics(\n // (5,9): error CS1929: 'float' does not contain a definition for 'F' and the best extension method overload 'S.F(double)' requires a receiver of type 'double'\n // f.F();\n Diagnostic(ErrorCode.ERR_BadInstanceArgType, \"f\").WithArguments(\"float\", \"F\", \"S.F(double)\", \"double\").WithLocation(5, 9));\n }\n\n [Fact]\n public void CS1929ERR_BadInstanceArgType()\n {\n var source = @\"class A { }\nclass B : A\n{\n static void M(A a)\n {\n a.E();\n }\n}\nstatic class S\n{\n internal static void E(this B b) { }\n}\";\n var compilation = CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore });\n compilation.VerifyDiagnostics(\n // (6,9): error CS1929: 'A' does not contain a definition for 'E' and the best extension method overload 'S.E(B)' requires a receiver of type 'B'\n // a.E();\n Diagnostic(ErrorCode.ERR_BadInstanceArgType, \"a\").WithArguments(\"A\", \"E\", \"S.E(B)\", \"B\").WithLocation(6, 9)\n );\n }\n\n [Fact]\n public void CS1930ERR_QueryDuplicateRangeVariable()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Program\n{\n static void Main()\n {\n int[] nums = { 0, 1, 2, 3, 4, 5 };\n var query = from num in nums\n let num = 3 // CS1930\n select num; \n }\n}\n\").VerifyDiagnostics(\n // (10,25): error CS1930: The range variable 'num' has already been declared\n Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, \"num\").WithArguments(\"num\"));\n }\n\n [Fact]\n public void CS1931ERR_QueryRangeVariableOverrides01()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\n\nclass Test\n{\n static void Main()\n {\n int x = 1;\n var y = from x in Enumerable.Range(1, 100) // CS1931\n select x + 1;\n }\n}\n\").VerifyDiagnostics(\n // (9,22): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'\n // var y = from x in Enumerable.Range(1, 100) // CS1931\n Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, \"x\").WithArguments(\"x\"),\n // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used\n // int x = 1;\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = null\n select i;\n }\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign to a range variable\n // let k = null\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = null\").WithArguments(\"\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue02()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = ()=>3\n select i;\n }\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign lambda expression to a range variable\n // let k = ()=>3\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = ()=>3\").WithArguments(\"lambda expression\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue03()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = Main\n select i;\n }\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign method group to a range variable\n // let k = Main\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = Main\").WithArguments(\"method group\")\n );\n }\n\n [Fact]\n public void CS1932ERR_QueryRangeVariableAssignedBadValue04()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from i in Enumerable.Range(1, 100)\n let k = M()\n select i;\n }\n static void M() {}\n}\n\").VerifyDiagnostics(\n // (8,21): error CS1932: Cannot assign void to a range variable\n // let k = M()\n Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, \"k = M()\").WithArguments(\"void\")\n );\n }\n\n [WorkItem(528756, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756\")]\n [Fact()]\n public void CS1933ERR_QueryNotAllowed()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nusing System.Collections;\n\nclass P\n{\n const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933\n static int Main()\n {\n return 1;\n }\n}\n\").VerifyDiagnostics(\n // EDMAURER now giving the more generic message CS0133\n // (7,27): error CS1933: Expression cannot contain query expressions\n // from\n //Diagnostic(ErrorCode.ERR_QueryNotAllowed, \"from\").WithArguments());\n\n // (7,27): error CS0133: The expression being assigned to 'P.e' must be constant\n // const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933\n Diagnostic(ErrorCode.ERR_NotConstantExpression, \"from x in new int[] { 1, 2, 3 } select x\").WithArguments(\"P.e\")\n );\n }\n\n [Fact]\n public void CS1934ERR_QueryNoProviderCastable()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nusing System.Collections;\nstatic class Test\n{\n public static void Main()\n {\n var list = new ArrayList();\n var q = from x in list // CS1934\n select x + 1;\n }\n}\n\").VerifyDiagnostics(\n // (9,27): error CS1934: Could not find an implementation of the query pattern for source type 'System.Collections.ArrayList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'x'.\n // list\n Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, \"list\").WithArguments(\"System.Collections.ArrayList\", \"Select\", \"x\"));\n }\n\n [Fact]\n public void CS1935ERR_QueryNoProviderStandard()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Collections.Generic;\nclass Test\n{\n static int Main()\n {\n int[] nums = { 0, 1, 2, 3, 4, 5 };\n IEnumerable e = from n in nums\n where n > 3\n select n;\n return 0;\n }\n}\n\").VerifyDiagnostics(\n // (8,40): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Where' not found. Are you missing required assembly references or a using directive for 'System.Linq'?\n // nums\n Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, \"nums\").WithArguments(\"int[]\", \"Where\"));\n }\n\n [Fact]\n public void CS1936ERR_QueryNoProvider()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Collections;\nusing System.Linq;\nclass Test\n{\n static int Main()\n {\n object obj = null;\n IEnumerable e = from x in obj // CS1936\n select x;\n return 0;\n }\n}\n\").VerifyDiagnostics(\n // (10,35): error CS1936: Could not find an implementation of the query pattern for source type 'object'. 'Select' not found.\n // obj\n Diagnostic(ErrorCode.ERR_QueryNoProvider, \"obj\").WithArguments(\"object\", \"Select\"));\n }\n\n [Fact]\n public void CS1936ERR_QueryNoProvider01()\n {\n var program = @\"\nclass X\n{\n internal X Cast() { return this; }\n}\nclass Program\n{\n static void Main()\n {\n var xx = new X();\n var q3 = from int x in xx select x;\n }\n}\";\n var comp = CreateCompilation(program);\n comp.VerifyDiagnostics(\n // (11,32): error CS1936: Could not find an implementation of the query pattern for source type 'X'. 'Select' not found.\n // var q3 = from int x in xx select x;\n Diagnostic(ErrorCode.ERR_QueryNoProvider, \"xx\").WithArguments(\"X\", \"Select\")\n );\n }\n\n [Fact]\n public void CS1937ERR_QueryOuterKey()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] sourceA = { 1, 2, 3, 4, 5 };\n int[] sourceB = { 3, 4, 5, 6, 7 };\n\n var query = from a in sourceA\n join b in sourceB on b equals 5 // CS1937\n select a + b;\n }\n}\n\").VerifyDiagnostics(\n // (11,42): error CS1937: The name 'b' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.\n // join b in sourceB on b equals 5 // CS1937\n Diagnostic(ErrorCode.ERR_QueryOuterKey, \"b\").WithArguments(\"b\")\n );\n }\n\n [Fact]\n public void CS1938ERR_QueryInnerKey()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] sourceA = { 1, 2, 3, 4, 5 };\n int[] sourceB = { 3, 4, 5, 6, 7 };\n\n var query = from a in sourceA\n join b in sourceB on 5 equals a // CS1938\n select a + b;\n }\n}\n\").VerifyDiagnostics(\n // (11,51): error CS1938: The name 'a' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.\n // join b in sourceB on 5 equals a // CS1938\n Diagnostic(ErrorCode.ERR_QueryInnerKey, \"a\").WithArguments(\"a\")\n );\n }\n\n [Fact]\n public void CS1939ERR_QueryOutRefRangeVariable()\n {\n var text = @\"\nusing System.Linq;\nclass Test\n{\n public static int F(ref int i) { return i; }\n public static void Main()\n {\n var list = new int[] { 0, 1, 2, 3, 4, 5 };\n var q = from x in list\n let k = x\n select Test.F(ref x); // CS1939\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,35): error CS1939: Cannot pass the range variable 'x' as an out or ref parameter\n // select Test.F(ref x); // CS1939\n Diagnostic(ErrorCode.ERR_QueryOutRefRangeVariable, \"x\").WithArguments(\"x\"));\n }\n\n [Fact]\n public void CS1940ERR_QueryMultipleProviders()\n {\n var text =\n@\"using System; \nclass Test\n{\n public delegate int Dele(int x);\n int num = 0;\n public int Select(Func d)\n {\n return d(this.num);\n }\n public int Select(Dele d) \n {\n return d(this.num) + 1;\n }\n public static void Main()\n {\n var q = from x in new Test()\n select x; // CS1940\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (18,17): error CS1940: Multiple implementations of the query pattern were found for source type 'Test'. Ambiguous call to 'Select'.\n // select\n Diagnostic(ErrorCode.ERR_QueryMultipleProviders, \"select x\").WithArguments(\"Test\", \"Select\")\n );\n }\n\n [Fact]\n public void CS1941ERR_QueryTypeInferenceFailedMulti()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Collections;\nusing System.Linq;\nclass Test\n{\n static int Main()\n {\n var nums = new int[] { 1, 2, 3, 4, 5, 6 };\n var words = new string[] { \"\"lake\"\", \"\"mountain\"\", \"\"sky\"\" };\n IEnumerable e = from n in nums\n join w in words on n equals w // CS1941\n select w;\n return 0;\n }\n}\n\").VerifyDiagnostics(\n // (11,25): error CS1941: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.\n // join\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedMulti, \"join\").WithArguments(\"join\", \"Join\"));\n }\n\n [Fact]\n public void CS1942ERR_QueryTypeInferenceFailed()\n {\n var text = @\"\nusing System;\nclass Q\n{\n public Q Select(Func func) { return this; }\n}\nclass Program\n{\n static void Main(string[] args)\n {\n var x = from i in new Q()\n select i; //CS1942\n }\n}\n\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (12,17): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.\n // select i; //CS1942\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, \"select\").WithArguments(\"select\", \"Select\")\n );\n }\n\n [Fact]\n public void CS1943ERR_QueryTypeInferenceFailedSelectMany()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n class TestClass\n { }\n static void Main()\n {\n int[] nums = { 0, 1, 2, 3, 4, 5 };\n TestClass tc = new TestClass();\n \n var x = from n in nums\n from s in tc // CS1943\n select n + s;\n }\n}\n\").VerifyDiagnostics(\n // (13,27): error CS1943: An expression of type 'Test.TestClass' is not allowed in a subsequent from clause in a query expression with source type 'int[]'. Type inference failed in the call to 'SelectMany'.\n // tc\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, \"tc\").WithArguments(\"Test.TestClass\", \"int[]\", \"SelectMany\"));\n }\n\n [Fact]\n public void CS1943ERR_QueryTypeInferenceFailedSelectMany02()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System;\nclass Test\n{\n class F1\n {\n public F1 SelectMany(Func func1, Func func2) { return this; }\n }\n static void Main()\n {\n F1 f1 = new F1();\n var x =\n from f in f1\n from g in 3\n select f + g;\n }\n}\n\").VerifyDiagnostics(\n // (14,23): error CS1943: An expression of type 'int' is not allowed in a subsequent from clause in a query expression with source type 'Test.F1'. Type inference failed in the call to 'SelectMany'.\n // from g in 3\n Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, \"3\").WithArguments(\"int\", \"Test.F1\", \"SelectMany\").WithLocation(14, 23)\n );\n }\n\n [Fact, WorkItem(546510, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546510\")]\n public void CS1944ERR_ExpressionTreeContainsPointerOp()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nunsafe class Test\n{\n public delegate int* D(int i);\n static void Main()\n {\n Expression tree = x => &x; // CS1944\n Expression> testExpr = x => new int*[] { &x };\n }\n}\n\";\n //Assert.Equal(\"\", text);\n CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (10,35): error CS1944: An expression tree may not contain an unsafe pointer operation\n // Expression tree = x => &x; // CS1944\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, \"&x\"),\n // (11,68): error CS1944: An expression tree may not contain an unsafe pointer operation\n // Expression> testExpr = x => new int*[] { &x };\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, \"&x\")\n );\n }\n\n [Fact]\n public void CS1945ERR_ExpressionTreeContainsAnonymousMethod()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic delegate void D();\nclass Test\n{\n static void Main()\n {\n Expression>> tree = (x => delegate(int i) { return true; }); // CS1945\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,61): error CS1945: An expression tree may not contain an anonymous method expression\n // Expression>> tree = (x => delegate(int i) { return true; }); // CS1945\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, \"delegate(int i) { return true; }\")\n );\n }\n\n [Fact]\n public void CS1946ERR_AnonymousMethodToExpressionTree()\n {\n var text = @\"\nusing System.Linq.Expressions;\n\npublic delegate void D();\n\nclass Test\n{\n static void Main()\n {\n Expression tree = delegate() { }; //CS1946\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,30): error CS1946: An anonymous method expression cannot be converted to an expression tree\n // Expression tree = delegate() { }; //CS1946\n Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, \"delegate() { }\")\n );\n }\n\n [Fact]\n public void CS1947ERR_QueryRangeVariableReadOnly()\n {\n var program = @\"\nusing System.Linq;\nclass Test\n{\n static void Main()\n {\n int[] array = new int[] { 1, 2, 3, 4, 5 };\n var x = from i in array\n let k = i\n select i = 5; // CS1947\n x.ToList();\n }\n}\n\";\n CreateCompilation(program).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, \"i\").WithArguments(\"i\"));\n }\n\n [Fact]\n public void CS1948ERR_QueryRangeVariableSameAsTypeParam()\n {\n CreateCompilationWithMscorlib40AndSystemCore(@\"\nusing System.Linq;\nclass Test\n{\n public void TestMethod(T t)\n {\n var x = from T in Enumerable.Range(1, 100) // CS1948\n select T;\n }\n public static void Main()\n {\n }\n}\n\").VerifyDiagnostics(\n // (8,17): error CS1948: The range variable 'T' cannot have the same name as a method type parameter\n // T\n Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, \"T\").WithArguments(\"T\"));\n }\n\n [Fact]\n public void CS1949ERR_TypeVarNotFoundRangeVariable()\n {\n var text =\n@\"using System.Linq;\nclass Test\n{\n static void Main()\n {\n var x = from var i in Enumerable.Range(1, 100) // CS1949\n select i;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (7,22): error CS1949: The contextual keyword 'var' cannot be used in a range variable declaration\n // var x = from var i in Enumerable.Range(1, 100) // CS1949\n Diagnostic(ErrorCode.ERR_TypeVarNotFoundRangeVariable, \"var\")\n );\n }\n\n // CS1950 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1951ERR_ByRefParameterInExpressionTree()\n {\n var text = @\"\npublic delegate int TestDelegate(ref int i);\nclass Test\n{\n static void Main()\n {\n System.Linq.Expressions.Expression tree1 = (ref int x) => x; // CS1951\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (7,75): error CS1951: An expression tree lambda may not contain a ref, in or out parameter\n // System.Linq.Expressions.Expression tree1 = (ref int x) => x; // CS1951\n Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, \"x\").WithLocation(7, 75)\n );\n }\n\n [Fact]\n public void CS1951ERR_InParameterInExpressionTree()\n {\n var text = @\"\npublic delegate int TestDelegate(in int i);\nclass Test\n{\n static void Main()\n {\n System.Linq.Expressions.Expression tree1 = (in int x) => x; // CS1951\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (7,74): error CS1951: An expression tree lambda may not contain a ref, in or out parameter\n // System.Linq.Expressions.Expression tree1 = (in int x) => x; // CS1951\n Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, \"x\").WithLocation(7, 74)\n );\n }\n\n [Fact]\n public void CS1952ERR_VarArgsInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nclass Test\n{\n public static int M(__arglist)\n {\n return 1;\n }\n\n static int Main()\n {\n Expression> f = x => Test.M(__arglist(x)); // CS1952\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (14,52): error CS1952: An expression tree lambda may not contain a method with variable arguments\n // Expression> f = x => Test.M(__arglist(x)); // CS1952\n Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, \"__arglist(x)\")\n );\n }\n\n [WorkItem(864605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605\")]\n [Fact]\n public void CS1953ERR_MemGroupInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\nclass CS1953\n{\n public static void Main()\n {\n double num = 10;\n Expression> testExpr =\n () => num.GetType is int; // CS0837 \n }\n}\";\n // Used to be CS1953, but now a method group in an is expression is illegal anyway.\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (10,21): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.\n // () => num.GetType is int; // CS1953 \n Diagnostic(ErrorCode.ERR_LambdaInIsAs, \"num.GetType is int\").WithLocation(10, 21));\n }\n\n // CS1954 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1955ERR_NonInvocableMemberCalled()\n {\n var text = @\"\nnamespace CompilerError1955\n{\n class ClassA\n {\n public int x = 100;\n public int X\n {\n get { return x; }\n set { x = value; }\n }\n }\n\n class Test\n {\n static void Main()\n {\n ClassA a = new ClassA();\n System.Console.WriteLine(a.x()); // CS1955\n System.Console.WriteLine(a.X()); // CS1955\n }\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 19, Column = 40 },\n new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 20, Column = 40 }});\n }\n\n // CS1958 --> ObjectAndCollectionInitializerTests.cs\n\n [Fact]\n public void CS1959ERR_InvalidConstantDeclarationType()\n {\n var text = @\"\nclass Program\n {\n static void Test() where T : class\n {\n const T x = null; // CS1959\n }\n }\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,25): error CS1959: 'x' is of type 'T'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type.\n // const T x = null; // CS1959\n Diagnostic(ErrorCode.ERR_InvalidConstantDeclarationType, \"null\").WithArguments(\"x\", \"T\")\n );\n }\n\n /// \n /// Test the different contexts in which CS1961 can be seen.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_Contexts()\n {\n var text = @\"\ninterface IContexts\n{\n #region In\n TIn Property1In { set; }\n TIn Property2In { get; } //CS1961 on \"\"TIn\"\"\n TIn Property3In { get; set; } //CS1961 on \"\"TIn\"\"\n\n int this[TIn arg, char filler, char indexer1In] { get; }\n TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on \"\"TIn\"\"\n int this[TIn arg, bool filler, char indexer3In] { set; }\n TIn this[int arg, bool[] filler, char indexer4In] { set; }\n int this[TIn arg, long filler, char indexer5In] { get; set; }\n TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on \"\"TIn\"\"\n\n int Method1In(TIn p);\n TIn Method2In(); //CS1961 on \"\"TIn\"\"\n int Method3In(out TIn p); //CS1961 on \"\"TIn\"\"\n int Method4In(ref TIn p); //CS1961 on \"\"TIn\"\"\n\n event DOut Event1In;\n #endregion In\n\n #region Out\n TOut Property1Out { set; } //CS1961 on \"\"TOut\"\"\n TOut Property2Out { get; }\n TOut Property3Out { get; set; } //CS1961 on \"\"TOut\"\"\n\n int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on \"\"TOut\"\"\n TOut this[int arg, char[] filler, bool indexer2Out] { get; }\n int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on \"\"TOut\"\"\n TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on \"\"TOut\"\"\n int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on \"\"TOut\"\"\n TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on \"\"TOut\"\"\n\n long Method1Out(TOut p); //CS1961 on \"\"TOut\"\"\n TOut Method2Out();\n long Method3Out(out TOut p); //CS1961 on \"\"TOut\"\" (sic: out params have to be input-safe)\n long Method4Out(ref TOut p); //CS1961 on \"\"TOut\"\"\n\n event DOut Event1Out; //CS1961 on \"\"TOut\"\"\n #endregion Out\n\n #region Inv\n TInv Property1Inv { set; }\n TInv Property2Inv { get; }\n TInv Property3Inv { get; set; }\n\n int this[TInv arg, char filler, long indexer1Inv] { get; }\n TInv this[int arg, char[] filler, long indexer2Inv] { get; }\n int this[TInv arg, bool filler, long indexer3Inv] { set; }\n TInv this[int arg, bool[] filler, long indexer4Inv] { set; }\n int this[TInv arg, long filler, long indexer5Inv] { get; set; }\n TInv this[int arg, long[] filler, long indexer6Inv] { get; set; }\n\n long Method1Inv(TInv p);\n TInv Method2Inv();\n long Method3Inv(out TInv p);\n long Method4Inv(ref TInv p);\n\n event DOut Event1Inv;\n #endregion Inv\n}\n\ndelegate void DOut(); //for event types - should preserve the variance of the type arg\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (6,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts.Property2In'. 'TIn' is contravariant.\n // TIn Property2In { get; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Property2In\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(6, 5),\n // (7,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.Property3In'. 'TIn' is contravariant.\n // TIn Property3In { get; set; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Property3In\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(7, 5),\n // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts.this[int, char[], char]'. 'TIn' is contravariant.\n // TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.this[int, char[], char]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(10, 5),\n // (14,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.this[int, long[], char]'. 'TIn' is contravariant.\n // TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.this[int, long[], char]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(14, 5),\n // (17,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts.Method2In()'. 'TIn' is contravariant.\n // TIn Method2In(); //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Method2In()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(17, 5),\n // (18,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.Method3In(out TIn)'. 'TIn' is contravariant.\n // int Method3In(out TIn p); //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Method3In(out TIn)\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(18, 23),\n // (19,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts.Method4In(ref TIn)'. 'TIn' is contravariant.\n // int Method4In(ref TIn p); //CS1961 on \"TIn\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IContexts.Method4In(ref TIn)\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(19, 23),\n // (25,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.Property1Out'. 'TOut' is covariant.\n // TOut Property1Out { set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Property1Out\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(25, 5),\n // (27,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.Property3Out'. 'TOut' is covariant.\n // TOut Property3Out { get; set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Property3Out\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(27, 5),\n // (29,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[TOut, char, bool]'. 'TOut' is covariant.\n // int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[TOut, char, bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(29, 14),\n // (31,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[TOut, bool, bool]'. 'TOut' is covariant.\n // int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[TOut, bool, bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(31, 14),\n // (32,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[int, bool[], bool]'. 'TOut' is covariant.\n // TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[int, bool[], bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(32, 5),\n // (33,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.this[TOut, long, bool]'. 'TOut' is covariant.\n // int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[TOut, long, bool]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(33, 14),\n // (34,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.this[int, long[], bool]'. 'TOut' is covariant.\n // TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.this[int, long[], bool]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(34, 5),\n // (36,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.Method1Out(TOut)'. 'TOut' is covariant.\n // long Method1Out(TOut p); //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Method1Out(TOut)\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(36, 21),\n // (38,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.Method3Out(out TOut)'. 'TOut' is covariant.\n // long Method3Out(out TOut p); //CS1961 on \"TOut\" (sic: out params have to be input-safe)\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Method3Out(out TOut)\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(38, 25),\n // (39,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts.Method4Out(ref TOut)'. 'TOut' is covariant.\n // long Method4Out(ref TOut p); //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IContexts.Method4Out(ref TOut)\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(39, 25),\n // (41,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts.Event1Out'. 'TOut' is covariant.\n // event DOut Event1Out; //CS1961 on \"TOut\"\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event1Out\").WithArguments(\"IContexts.Event1Out\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(41, 22));\n }\n\n /// \n /// Test all of the contexts that require output safety.\n /// Note: some also require input safety.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_OutputUnsafe()\n {\n var text = @\"\ninterface IOutputUnsafe\n{\n #region Case 1: contravariant type parameter\n TInv Property1Good { get; }\n TInv this[long[] Indexer1Good] { get; }\n TInv Method1Good();\n\n TIn Property1Bad { get; }\n TIn this[char[] Indexer1Bad] { get; }\n TIn Method1Bad();\n #endregion Case 1\n\n #region Case 2: array of output-unsafe\n TInv[] Property2Good { get; }\n TInv[] this[long[,] Indexer2Good] { get; }\n TInv[] Method2Good();\n\n TIn[] Property2Bad { get; }\n TIn[] this[char[,] Indexer2Bad] { get; }\n TIn[] Method2Bad();\n #endregion Case 2\n\n #region Case 3: constructed with output-unsafe type arg in covariant slot\n IOut Property3Good { get; }\n IOut this[long[,,] Indexer3Good] { get; }\n IOut Method3Good();\n\n IOut Property3Bad { get; }\n IOut this[char[,,] Indexer3Bad] { get; }\n IOut Method3Bad();\n #endregion Case 3\n\n #region Case 4: constructed with output-unsafe type arg in invariant slot\n IInv Property4Good { get; }\n IInv this[long[,,,] Indexer4Good] { get; }\n IInv Method4Good();\n\n IInv Property4Bad { get; }\n IInv this[char[,,,] Indexer4Bad] { get; }\n IInv Method4Bad();\n #endregion Case 4\n\n #region Case 5: constructed with input-unsafe (sic) type arg in contravariant slot\n IIn Property5Good { get; }\n IIn this[long[,,,,] Indexer5Good] { get; }\n IIn Method5Good();\n\n IIn Property5Bad { get; }\n IIn this[char[,,,,] Indexer5Bad] { get; }\n IIn Method5Bad();\n #endregion Case 5\n\n #region Case 6: constructed with input-unsafe (sic) type arg in invariant slot\n IInv Property6Good { get; }\n IInv this[long[,,,,,] Indexer6Good] { get; }\n IInv Method6Good();\n\n IInv Property6Bad { get; }\n IInv this[char[,,,,,] Indexer6Bad] { get; }\n IInv Method6Bad();\n #endregion Case 6\n}\n\ninterface IIn { }\ninterface IOut { }\ninterface IInv { }\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (9,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Property1Bad'. 'TIn' is contravariant.\n // TIn Property1Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOutputUnsafe.Property1Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(9, 5),\n // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.this[char[]]'. 'TIn' is contravariant.\n // TIn this[char[] Indexer1Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOutputUnsafe.this[char[]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(10, 5),\n // (11,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Method1Bad()'. 'TIn' is contravariant.\n // TIn Method1Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOutputUnsafe.Method1Bad()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(11, 5),\n // (19,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Property2Bad'. 'TIn' is contravariant.\n // TIn[] Property2Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn[]\").WithArguments(\"IOutputUnsafe.Property2Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(19, 5),\n // (20,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.this[char[*,*]]'. 'TIn' is contravariant.\n // TIn[] this[char[,] Indexer2Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn[]\").WithArguments(\"IOutputUnsafe.this[char[*,*]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(20, 5),\n // (21,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Method2Bad()'. 'TIn' is contravariant.\n // TIn[] Method2Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn[]\").WithArguments(\"IOutputUnsafe.Method2Bad()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(21, 5),\n // (29,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Property3Bad'. 'TIn' is contravariant.\n // IOut Property3Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IOutputUnsafe.Property3Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(29, 5),\n // (30,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.this[char[*,*,*]]'. 'TIn' is contravariant.\n // IOut this[char[,,] Indexer3Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IOutputUnsafe.this[char[*,*,*]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(30, 5),\n // (31,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe.Method3Bad()'. 'TIn' is contravariant.\n // IOut Method3Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IOutputUnsafe.Method3Bad()\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(31, 5),\n // (39,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe.Property4Bad'. 'TIn' is contravariant.\n // IInv Property4Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Property4Bad\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(39, 5),\n // (40,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe.this[char[*,*,*,*]]'. 'TIn' is contravariant.\n // IInv this[char[,,,] Indexer4Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.this[char[*,*,*,*]]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(40, 5),\n // (41,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe.Method4Bad()'. 'TIn' is contravariant.\n // IInv Method4Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Method4Bad()\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(41, 5),\n // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe.Property5Bad'. 'TOut' is covariant.\n // IIn Property5Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IOutputUnsafe.Property5Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(49, 5),\n // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe.this[char[*,*,*,*,*]]'. 'TOut' is covariant.\n // IIn this[char[,,,,] Indexer5Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IOutputUnsafe.this[char[*,*,*,*,*]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(50, 5),\n // (51,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe.Method5Bad()'. 'TOut' is covariant.\n // IIn Method5Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IOutputUnsafe.Method5Bad()\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(51, 5),\n // (59,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe.Property6Bad'. 'TOut' is covariant.\n // IInv Property6Bad { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Property6Bad\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(59, 5),\n // (60,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe.this[char[*,*,*,*,*,*]]'. 'TOut' is covariant.\n // IInv this[char[,,,,,] Indexer6Bad] { get; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.this[char[*,*,*,*,*,*]]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(60, 5),\n // (61,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe.Method6Bad()'. 'TOut' is covariant.\n // IInv Method6Bad();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IOutputUnsafe.Method6Bad()\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(61, 5));\n }\n\n /// \n /// Test all of the contexts that require input safety.\n /// Note: some also require output safety.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_InputUnsafe()\n {\n var text = @\"\ninterface IInputUnsafe\n{\n #region Case 1: contravariant type parameter\n TInv Property1Good { set; }\n TInv this[long[] Indexer1GoodA] { set; }\n long this[long[] Indexer1GoodB, TInv p] { set; }\n long Method1Good(TInv p);\n\n TOut Property1Bad { set; }\n TOut this[char[] Indexer1BadA] { set; }\n long this[char[] Indexer1BadB, TOut p] { set; }\n long Method1Bad(TOut p);\n #endregion Case 1\n\n #region Case 2: array of input-unsafe\n TInv[] Property2Good { set; }\n TInv[] this[long[,] Indexer2GoodA] { set; }\n long this[long[,] Indexer2GoodB, TInv[] p] { set; }\n long Method2Good(TInv[] p);\n\n TOut[] Property2Bad { set; }\n TOut[] this[char[,] Indexer2BadA] { set; }\n long this[char[,] Indexer2BadB, TOut[] p] { set; }\n long Method2Bad(TOut[] p);\n #endregion Case 2\n\n #region Case 3: constructed with input-unsafe type arg in covariant (sic: not flipped) slot\n IOut Property3Good { set; }\n IOut this[long[,,] Indexer3GoodA] { set; }\n long this[long[,,] Indexer3GoodB, IOut p] { set; }\n long Method3Good(IOut p);\n event DOut Event3Good;\n\n IOut Property3Bad { set; }\n IOut this[char[,,] Indexer3BadA] { set; }\n long this[char[,,] Indexer3BadB, IOut p] { set; }\n long Method3Bad(IOut p);\n event DOut Event3Bad;\n #endregion Case 3\n\n #region Case 4: constructed with input-unsafe type arg in invariant slot\n IInv Property4Good { set; }\n IInv this[long[,,,] Indexer4GoodA] { set; }\n long this[long[,,,] Indexer4GoodB, IInv p] { set; }\n long Method4Good(IInv p);\n event DInv Event4Good;\n\n IInv Property4Bad { set; }\n IInv this[char[,,,] Indexer4BadA] { set; }\n long this[char[,,,] Indexer4BadB, IInv p] { set; }\n long Method4Bad(IInv p);\n event DInv Event4Bad;\n #endregion Case 4\n\n #region Case 5: constructed with output-unsafe (sic) type arg in contravariant (sic: not flipped) slot\n IIn Property5Good { set; }\n IIn this[long[,,,,] Indexer5GoodA] { set; }\n long this[long[,,,,] Indexer5GoodB, IIn p] { set; }\n long Method5Good(IIn p);\n event DIn Event5Good;\n\n IIn Property5Bad { set; }\n IIn this[char[,,,,] Indexer5BadA] { set; }\n long this[char[,,,,] Indexer5BadB, IIn p] { set; }\n long Method5Bad(IIn p);\n event DIn Event5Bad;\n #endregion Case 5\n\n #region Case 6: constructed with output-unsafe (sic) type arg in invariant slot\n IInv Property6Good { set; }\n IInv this[long[,,,,,] Indexer6GoodA] { set; }\n long this[long[,,,,,] Indexer6GoodB, IInv p] { set; }\n long Method6Good(IInv p);\n event DInv Event6Good;\n\n IInv Property6Bad { set; }\n IInv this[char[,,,,,] Indexer6BadA] { set; }\n long this[char[,,,,,] Indexer6BadB, IInv p] { set; }\n long Method6Bad(IInv p);\n event DInv Event6Bad;\n #endregion Case 6\n}\n\ninterface IIn { }\ninterface IOut { }\ninterface IInv { }\n\ndelegate void DIn();\ndelegate void DOut();\ndelegate void DInv();\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (11,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[]]'. 'TOut' is covariant.\n // TOut this[char[] Indexer1BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.this[char[]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(11, 5),\n // (12,36): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[], TOut]'. 'TOut' is covariant.\n // long this[char[] Indexer1BadB, TOut p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.this[char[], TOut]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(12, 36),\n // (23,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*]]'. 'TOut' is covariant.\n // TOut[] this[char[,] Indexer2BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.this[char[*,*]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(23, 5),\n // (24,37): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*], TOut[]]'. 'TOut' is covariant.\n // long this[char[,] Indexer2BadB, TOut[] p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.this[char[*,*], TOut[]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(24, 37),\n // (36,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*,*]]'. 'TOut' is covariant.\n // IOut this[char[,,] Indexer3BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.this[char[*,*,*]]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(36, 5),\n // (37,38): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.this[char[*,*,*], IOut]'. 'TOut' is covariant.\n // long this[char[,,] Indexer3BadB, IOut p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.this[char[*,*,*], IOut]\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(37, 38),\n // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*]]'. 'TOut' is covariant.\n // IInv this[char[,,,] Indexer4BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*]]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(50, 5),\n // (51,39): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*], IInv]'. 'TOut' is covariant.\n // long this[char[,,,] Indexer4BadB, IInv p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*], IInv]\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(51, 39),\n // (64,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*]]'. 'TIn' is contravariant.\n // IIn this[char[,,,,] Indexer5BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*]]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(64, 5),\n // (65,40): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*], IIn]'. 'TIn' is contravariant.\n // long this[char[,,,,] Indexer5BadB, IIn p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*], IIn]\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(65, 40),\n // (78,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*,*]]'. 'TIn' is contravariant.\n // IInv this[char[,,,,,] Indexer6BadA] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*,*]]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(78, 5),\n // (79,41): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.this[char[*,*,*,*,*,*], IInv]'. 'TIn' is contravariant.\n // long this[char[,,,,,] Indexer6BadB, IInv p] { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.this[char[*,*,*,*,*,*], IInv]\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(79, 41),\n // (10,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Property1Bad'. 'TOut' is covariant.\n // TOut Property1Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.Property1Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(10, 5),\n // (13,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Method1Bad(TOut)'. 'TOut' is covariant.\n // long Method1Bad(TOut p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IInputUnsafe.Method1Bad(TOut)\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(13, 21),\n // (22,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Property2Bad'. 'TOut' is covariant.\n // TOut[] Property2Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.Property2Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(22, 5),\n // (25,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Method2Bad(TOut[])'. 'TOut' is covariant.\n // long Method2Bad(TOut[] p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut[]\").WithArguments(\"IInputUnsafe.Method2Bad(TOut[])\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(25, 21),\n // (35,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Property3Bad'. 'TOut' is covariant.\n // IOut Property3Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.Property3Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(35, 5),\n // (38,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Method3Bad(IOut)'. 'TOut' is covariant.\n // long Method3Bad(IOut p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IOut\").WithArguments(\"IInputUnsafe.Method3Bad(IOut)\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(38, 21),\n // (39,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe.Event3Bad'. 'TOut' is covariant.\n // event DOut Event3Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event3Bad\").WithArguments(\"IInputUnsafe.Event3Bad\", \"TOut\", \"covariant\", \"contravariantly\").WithLocation(39, 22),\n // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.Property4Bad'. 'TOut' is covariant.\n // IInv Property4Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Property4Bad\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(49, 5),\n // (52,21): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.Method4Bad(IInv)'. 'TOut' is covariant.\n // long Method4Bad(IInv p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Method4Bad(IInv)\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(52, 21),\n // (53,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe.Event4Bad'. 'TOut' is covariant.\n // event DInv Event4Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event4Bad\").WithArguments(\"IInputUnsafe.Event4Bad\", \"TOut\", \"covariant\", \"invariantly\").WithLocation(53, 22),\n // (63,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.Property5Bad'. 'TIn' is contravariant.\n // IIn Property5Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.Property5Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(63, 5),\n // (66,21): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.Method5Bad(IIn)'. 'TIn' is contravariant.\n // long Method5Bad(IIn p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IIn\").WithArguments(\"IInputUnsafe.Method5Bad(IIn)\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(66, 21),\n // (67,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe.Event5Bad'. 'TIn' is contravariant.\n // event DIn Event5Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event5Bad\").WithArguments(\"IInputUnsafe.Event5Bad\", \"TIn\", \"contravariant\", \"covariantly\").WithLocation(67, 20),\n // (77,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.Property6Bad'. 'TIn' is contravariant.\n // IInv Property6Bad { set; }\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Property6Bad\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(77, 5),\n // (80,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.Method6Bad(IInv)'. 'TIn' is contravariant.\n // long Method6Bad(IInv p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInv\").WithArguments(\"IInputUnsafe.Method6Bad(IInv)\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(80, 21),\n // (81,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe.Event6Bad'. 'TIn' is contravariant.\n // event DInv Event6Bad;\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"Event6Bad\").WithArguments(\"IInputUnsafe.Event6Bad\", \"TIn\", \"contravariant\", \"invariantly\").WithLocation(81, 21));\n }\n\n /// \n /// Test output-safety checks on base interfaces.\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_BaseInterfaces()\n {\n var text = @\"\ninterface IBaseInterfaces : IIn, IOut, IInv { }\n\ninterface IIn { }\ninterface IOut { }\ninterface IInv { }\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (2,39): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IIn'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"IIn\", \"TOut\", \"covariant\", \"contravariantly\"),\n // (2,30): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOut'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"IOut\", \"TIn\", \"contravariant\", \"covariantly\"));\n }\n\n /// \n /// Test all type parameter/type argument combinations.\n /// | Type Arg Covariant | Type Arg Contravariant | Type Arg Invariant\n /// -------------------------+----------------------+------------------------+--------------------\n /// Type Param Covariant | Covariant | Contravariant | Invariant\n /// Type Param Contravariant | Contravariant | Covariant | Invariant\n /// Type Param Invariant | Error | Error | Invariant\n /// \n [Fact]\n public void CS1961ERR_UnexpectedVariance_Generics()\n {\n var text = @\"\ninterface IOutputUnsafeTable\n{\n ICovariant OutputUnsafe1();\n ICovariant OutputUnsafe2();\n ICovariant OutputUnsafe3();\n\n IContravariant OutputUnsafe4();\n IContravariant OutputUnsafe5();\n IContravariant OutputUnsafe6();\n\n IInvariant OutputUnsafe7();\n IInvariant OutputUnsafe8();\n IInvariant OutputUnsafe9();\n}\n\ninterface IInputUnsafeTable\n{\n void InputUnsafe1(ICovariant p);\n void InputUnsafe2(ICovariant p);\n void InputUnsafe3(ICovariant p);\n\n void InputUnsafe4(IContravariant p);\n void InputUnsafe5(IContravariant p);\n void InputUnsafe6(IContravariant p);\n\n void InputUnsafe7(IInvariant p);\n void InputUnsafe8(IInvariant p);\n void InputUnsafe9(IInvariant p);\n}\n\ninterface IBothUnsafeTable\n{\n void InputUnsafe1(ref ICovariant p);\n void InputUnsafe2(ref ICovariant p);\n void InputUnsafe3(ref ICovariant p);\n\n void InputUnsafe4(ref IContravariant p);\n void InputUnsafe5(ref IContravariant p);\n void InputUnsafe6(ref IContravariant p);\n\n void InputUnsafe7(ref IInvariant p);\n void InputUnsafe8(ref IInvariant p);\n void InputUnsafe9(ref IInvariant p);\n}\n\ninterface ICovariant { }\ninterface IContravariant { }\ninterface IInvariant { }\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (5,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IOutputUnsafeTable.OutputUnsafe2()'. 'TOutputUnsafe' is contravariant.\n // ICovariant OutputUnsafe2();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe2()\", \"TOutputUnsafe\", \"contravariant\", \"covariantly\").WithLocation(5, 5),\n // (8,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IOutputUnsafeTable.OutputUnsafe4()'. 'TInputUnsafe' is covariant.\n // IContravariant OutputUnsafe4();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe4()\", \"TInputUnsafe\", \"covariant\", \"contravariantly\").WithLocation(8, 5),\n // (12,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IOutputUnsafeTable.OutputUnsafe7()'. 'TInputUnsafe' is covariant.\n // IInvariant OutputUnsafe7();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe7()\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(12, 5),\n // (13,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IOutputUnsafeTable.OutputUnsafe8()'. 'TOutputUnsafe' is contravariant.\n // IInvariant OutputUnsafe8();\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IOutputUnsafeTable.OutputUnsafe8()\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(13, 5),\n // (19,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IInputUnsafeTable.InputUnsafe1(ICovariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe1(ICovariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe1(ICovariant)\", \"TInputUnsafe\", \"covariant\", \"contravariantly\").WithLocation(19, 23),\n // (24,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IInputUnsafeTable.InputUnsafe5(IContravariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe5(IContravariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe5(IContravariant)\", \"TOutputUnsafe\", \"contravariant\", \"covariantly\").WithLocation(24, 23),\n // (27,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IInputUnsafeTable.InputUnsafe7(IInvariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe7(IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe7(IInvariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(27, 23),\n // (28,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IInputUnsafeTable.InputUnsafe8(IInvariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe8(IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IInputUnsafeTable.InputUnsafe8(IInvariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(28, 23),\n\n // Dev10 doesn't say \"must be invariantly valid\" for ref params - it lists whichever check fails first. This approach seems nicer.\n\n // (34,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe1(ref ICovariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe1(ref ICovariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe1(ref ICovariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(34, 27),\n // (35,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe2(ref ICovariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe2(ref ICovariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"ICovariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe2(ref ICovariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(35, 27),\n // (38,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe4(ref IContravariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe4(ref IContravariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe4(ref IContravariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(38, 27),\n // (39,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe5(ref IContravariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe5(ref IContravariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IContravariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe5(ref IContravariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(39, 27),\n // (42,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe7(ref IInvariant)'. 'TInputUnsafe' is covariant.\n // void InputUnsafe7(ref IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe7(ref IInvariant)\", \"TInputUnsafe\", \"covariant\", \"invariantly\").WithLocation(42, 27),\n // (43,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable.InputUnsafe8(ref IInvariant)'. 'TOutputUnsafe' is contravariant.\n // void InputUnsafe8(ref IInvariant p);\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"IInvariant\").WithArguments(\"IBothUnsafeTable.InputUnsafe8(ref IInvariant)\", \"TOutputUnsafe\", \"contravariant\", \"invariantly\").WithLocation(43, 27));\n }\n\n [Fact]\n public void CS1961ERR_UnexpectedVariance_DelegateInvoke()\n {\n var text = @\"\ndelegate TIn D1(); //CS1961\ndelegate TOut D2();\ndelegate T D3();\n\ndelegate void D4(TIn p);\ndelegate void D5(TOut p); //CS1961\ndelegate void D6(T p);\n\ndelegate void D7(ref TIn p); //CS1961\ndelegate void D8(ref TOut p); //CS1961\ndelegate void D9(ref T p);\n\ndelegate void D10(out TIn p); //CS1961\ndelegate void D11(out TOut p); //CS1961\ndelegate void D12(out T p);\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (2,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'D1.Invoke()'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"D1.Invoke()\", \"TIn\", \"contravariant\", \"covariantly\"),\n // (7,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'D5.Invoke(TOut)'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"D5.Invoke(TOut)\", \"TOut\", \"covariant\", \"contravariantly\"),\n // (10,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D7.Invoke(ref TIn)'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"D7.Invoke(ref TIn)\", \"TIn\", \"contravariant\", \"invariantly\"),\n // (11,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D8.Invoke(ref TOut)'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"D8.Invoke(ref TOut)\", \"TOut\", \"covariant\", \"invariantly\"),\n // (14,22): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D10.Invoke(out TIn)'. 'TIn' is contravariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TIn\").WithArguments(\"D10.Invoke(out TIn)\", \"TIn\", \"contravariant\", \"invariantly\"),\n // (15,23): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D11.Invoke(out TOut)'. 'TOut' is covariant.\n Diagnostic(ErrorCode.ERR_UnexpectedVariance, \"TOut\").WithArguments(\"D11.Invoke(out TOut)\", \"TOut\", \"covariant\", \"invariantly\"));\n }\n\n [Fact]\n public void CS1962ERR_BadDynamicTypeof()\n {\n var text = @\"\npublic class C\n{\n public static int Main()\n {\n dynamic S = typeof(dynamic);\n return 0;\n }\n public static int Test(int age)\n { \n return 1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,25): error CS1962: The typeof operator cannot be used on the dynamic type\n Diagnostic(ErrorCode.ERR_BadDynamicTypeof, \"typeof(dynamic)\"));\n }\n\n [Fact]\n [WorkItem(54804, \"https://github.com/dotnet/roslyn/issues/54804\")]\n public void BadNestedTypeof()\n {\n var source = @\"\n#nullable enable\n\nusing System;\nusing System.Collections.Generic;\n\nvar x = typeof(List); // 1\nx = typeof(nint); // 2\nx = typeof(List); // 3\nx = typeof(List); // 4\nx = typeof((int a, int b)); // 5\nx = typeof((int a, string? b)); // 6\nx = typeof(ValueTuple); // ok\n\";\n CreateCompilation(source).VerifyDiagnostics();\n\n CreateCompilation(source, options: TestOptions.DebugExe.WithWarningLevel(5)).VerifyDiagnostics();\n }\n\n // CS1963ERR_ExpressionTreeContainsDynamicOperation --> SyntaxBinderTests\n\n [Fact]\n public void CS1964ERR_BadDynamicConversion()\n {\n var text = @\"\nclass A\n{\n public static implicit operator dynamic(A a)\n {\n return a;\n }\n\n public static implicit operator A(dynamic a)\n {\n return a;\n}\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (9,37): error CS1964: 'A.implicit operator A(dynamic)': user-defined conversions to or from the dynamic type are not allowed\n Diagnostic(ErrorCode.ERR_BadDynamicConversion, \"A\").WithArguments(\"A.implicit operator A(dynamic)\"),\n // (4,37): error CS1964: 'A.implicit operator dynamic(A)': user-defined conversions to or from the dynamic type are not allowed\n Diagnostic(ErrorCode.ERR_BadDynamicConversion, \"dynamic\").WithArguments(\"A.implicit operator dynamic(A)\"));\n }\n\n // CS1969ERR_DynamicRequiredTypesMissing -> CodeGen_DynamicTests.Missing_*\n // CS1970ERR_ExplicitDynamicAttr --> AttributeTests_Dynamic.ExplicitDynamicAttribute\n\n [Fact]\n public void CS1971ERR_NoDynamicPhantomOnBase()\n {\n const string text = @\"\npublic class B\n{\n public virtual void M(object o) {}\n}\npublic class D : B\n{\n public override void M(object o) {}\n\n void N(dynamic d)\n {\n base.M(d);\n }\n}\n\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (12,9): error CS1971: The call to method 'M' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.\n // base.M(d);\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBase, \"base.M(d)\").WithArguments(\"M\"));\n }\n\n [Fact]\n public void CS1972ERR_NoDynamicPhantomOnBaseIndexer()\n {\n const string text = @\"\npublic class B\n{\n public string this[int index]\n {\n get { return \"\"You passed \"\" + index; }\n }\n}\npublic class D : B\n{\n public void M(object o)\n {\n int[] arr = { 1, 2, 3 };\n int s = base[(dynamic)o];\n }\n}\n\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (14,17): error CS1972: The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.\n // int s = base[(dynamic)o];\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, \"base[(dynamic)o]\"));\n }\n\n [Fact]\n public void CS1973ERR_BadArgTypeDynamicExtension()\n {\n const string text = @\"\nclass Program\n{\n static void Main()\n {\n dynamic d = 1;\n B b = new B();\n b.Goo(d);\n }\n}\npublic class B { }\nstatic public class Extension\n{\n public static void Goo(this B b, int x) { }\n}\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n// (8,9): error CS1973: 'B' has no applicable method named 'Goo' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.\n// b.Goo(d);\nDiagnostic(ErrorCode.ERR_BadArgTypeDynamicExtension, \"b.Goo(d)\").WithArguments(\"B\", \"Goo\"));\n }\n\n [Fact]\n public void CS1975ERR_NoDynamicPhantomOnBaseCtor_Base()\n {\n var text = @\"\nclass A\n{\n public A(int x)\n {\n\n }\n}\nclass B : A\n{\n public B(dynamic d)\n : base(d)\n { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, \"base\"));\n }\n\n [Fact]\n public void CS1975ERR_NoDynamicPhantomOnBaseCtor_This()\n {\n var text = @\"\nclass B\n{\n public B(dynamic d)\n : this(d, 1)\n { }\n\n public B(int a, int b)\n { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.\n Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, \"this\"));\n }\n\n [Fact]\n public void CS1976ERR_BadDynamicMethodArgMemgrp()\n {\n const string text = @\"\nclass Program\n{\n static void M(dynamic d)\n {\n d.Goo(M);\n }\n}\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (6,15): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?\n // d.Goo(M);\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, \"M\"));\n }\n\n [Fact]\n public void CS1977ERR_BadDynamicMethodArgLambda()\n {\n const string text = @\"\nclass Program\n{\n static void M(dynamic d)\n {\n d.Goo(()=>{});\n d.Goo(delegate () {});\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n // (6,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n // d.Goo(()=>{});\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"()=>{}\"),\n // (7,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n // d.Goo(delegate () {});\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"delegate () {}\"));\n }\n\n [Fact, WorkItem(578352, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578352\")]\n public void CS1977ERR_BadDynamicMethodArgLambda_CreateObject()\n {\n string source = @\"\nusing System;\n \nclass C\n{\n static void Main()\n {\n dynamic y = null;\n new C(delegate { }, y);\n }\n \n public C(Action a, Action y)\n {\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef });\n comp.VerifyDiagnostics(\n // (9,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"delegate { }\"));\n }\n\n [Fact]\n public void CS1660ERR_BadDynamicMethodArgLambda_CollectionInitializer()\n {\n string source = @\"\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nunsafe class C : IEnumerable\n{\n public static void M(__arglist) \n {\n int a; \n int* p = &a;\n dynamic d = null;\n\n var c = new C\n {\n { d, delegate() { } },\n { d, 1, p },\n { d, __arglist },\n { d, GetEnumerator },\n { d, SomeStaticMethod },\n };\n }\n\n public static void SomeStaticMethod() {}\n\n public void Add(dynamic d, int x, int* ptr)\n {\n }\n\n public void Add(dynamic d, RuntimeArgumentHandle x)\n {\n }\n\n public void Add(dynamic d, Action f)\n {\n }\n\n public void Add(dynamic d, Func> f)\n {\n }\n\n public IEnumerator GetEnumerator()\n {\n return null;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n}\";\n var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }, options: TestOptions.UnsafeReleaseDll);\n comp.VerifyDiagnostics(\n // (16,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.\n // { d, delegate() { } },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, \"delegate() { }\").WithLocation(16, 18),\n // (17,21): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n // { d, 1, p },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"p\").WithArguments(\"int*\").WithLocation(17, 21),\n // (18,18): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation.\n // { d, __arglist },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"__arglist\").WithArguments(\"System.RuntimeArgumentHandle\").WithLocation(18, 18),\n // (19,13): error CS1950: The best overloaded Add method 'C.Add(dynamic, RuntimeArgumentHandle)' for the collection initializer has some invalid arguments\n // { d, GetEnumerator },\n Diagnostic(ErrorCode.ERR_BadArgTypesForCollectionAdd, \"{ d, GetEnumerator }\").WithArguments(\"C.Add(dynamic, System.RuntimeArgumentHandle)\").WithLocation(19, 13),\n // (19,18): error CS1503: Argument 2: cannot convert from 'method group' to 'RuntimeArgumentHandle'\n // { d, GetEnumerator },\n Diagnostic(ErrorCode.ERR_BadArgType, \"GetEnumerator\").WithArguments(\"2\", \"method group\", \"System.RuntimeArgumentHandle\").WithLocation(19, 18),\n // (20,18): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?\n // { d, SomeStaticMethod },\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, \"SomeStaticMethod\").WithLocation(20, 18));\n }\n\n [Fact]\n public void CS1978ERR_BadDynamicMethodArg()\n {\n // The dev 10 compiler gives arguably wrong error here; it says that \"TypedReference may not be\n // used as a type argument\". Though that is true, and though what is happening here behind the scenes \n // is that TypedReference is being used as a type argument to a dynamic call site helper method,\n // that's giving an error about an implementation detail. A better error is to say that\n // TypedReference is not a legal type in a dynamic operation.\n //\n // Dev10 compiler didn't report an error for by-ref pointer argument. See Dev10 bug 819498.\n // The error should be reported for any pointer argument regardless of its refness.\n const string text = @\"\nclass Program\n{\n unsafe static void M(dynamic d, int* i, System.TypedReference tr)\n {\n d.Goo(i);\n d.Goo(tr);\n d.Goo(ref tr);\n d.Goo(out tr);\n d.Goo(out i);\n d.Goo(ref i);\n }\n}\n\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll);\n comp.VerifyDiagnostics(\n // (6,15): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"i\").WithArguments(\"int*\"),\n // (7,15): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"tr\").WithArguments(\"System.TypedReference\"),\n // (8,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"tr\").WithArguments(\"System.TypedReference\"),\n // (9,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"tr\").WithArguments(\"System.TypedReference\"),\n // (10,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"i\").WithArguments(\"int*\"),\n // (11,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation.\n Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, \"i\").WithArguments(\"int*\"));\n }\n\n // CS1979ERR_BadDynamicQuery --> DynamicTests.cs, DynamicQuery_* \n\n // Test CS1980ERR_DynamicAttributeMissing moved to AttributeTests_Dynamic.cs\n\n // CS1763 is covered for different code path by SymbolErrorTests.CS1763ERR_NotNullRefDefaultParameter()\n [WorkItem(528854, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528854\")]\n [Fact]\n public void CS1763ERR_NotNullRefDefaultParameter02()\n {\n string text = @\"\nclass Program\n{\n public void Goo(T t = default(U)) where U : T\n {\n }\n static void Main(string[] args)\n {\n \n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (4,29): error CS1763: 't' is of type 'T'. A default parameter value of a reference type other than string can only be initialized with null\n // public void Goo(T t = default(U)) where U : T\n Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, \"t\").WithArguments(\"t\", \"T\"));\n }\n\n #endregion\n\n #region \"Targeted Warning Tests - please arrange tests in the order of error code\"\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent()\n {\n var text = @\"\ndelegate void MyDelegate();\nclass MyClass\n{\n public event MyDelegate evt; // CS0067\n public static void Main()\n {\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,29): warning CS0067: The event 'MyClass.evt' is never used\n // public event MyDelegate evt; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"evt\").WithArguments(\"MyClass.evt\"));\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_Accessibility()\n {\n var text = @\"\nusing System;\nclass MyClass\n{\n public event Action E1; // CS0067\n internal event Action E2; // CS0067\n protected internal event Action E3; // CS0067\n protected event Action E4; // CS0067\n private event Action E5; // CS0067\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,25): warning CS0067: The event 'MyClass.E1' is never used\n // public event Action E1; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E1\").WithArguments(\"MyClass.E1\"),\n // (6,27): warning CS0067: The event 'MyClass.E2' is never used\n // internal event Action E2; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E2\").WithArguments(\"MyClass.E2\"),\n // (7,37): warning CS0067: The event 'MyClass.E3' is never used\n // protected internal event Action E3; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E3\").WithArguments(\"MyClass.E3\"),\n // (8,28): warning CS0067: The event 'MyClass.E4' is never used\n // protected event Action E4; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E4\").WithArguments(\"MyClass.E4\"),\n // (9,26): warning CS0067: The event 'MyClass.E5' is never used\n // private event Action E5; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E5\").WithArguments(\"MyClass.E5\"));\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_StructLayout()\n {\n var text = @\"\nusing System;\nusing System.Runtime.InteropServices;\n\n[StructLayout(LayoutKind.Sequential)]\nstruct S\n{\n event Action E1;\n}\n\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_Kind()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n event Action E1; // CS0067\n event Action E2 { add { } remove { } }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,18): warning CS0067: The event 'C.E1' is never used\n // event Action E1; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"E1\").WithArguments(\"C.E1\"));\n }\n\n [Fact, WorkItem(542396, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396\"), WorkItem(546817, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817\")]\n public void CS0067WRN_UnreferencedEvent_Accessed()\n {\n var text = @\"\nusing System;\n\nclass C\n{\n event Action None; // CS0067\n event Action Read;\n event Action Write;\n event Action Add; // CS0067\n\n void M(Action a)\n {\n M(Read);\n Write = a;\n Add += a;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,18): warning CS0067: The event 'C.Add' is never used\n // event Action Add; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"Add\").WithArguments(\"C.Add\"),\n // (6,18): warning CS0067: The event 'C.None' is never used\n // event Action None; // CS0067\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"None\").WithArguments(\"C.None\"));\n }\n\n [Fact, WorkItem(581002, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581002\")]\n public void CS0067WRN_UnreferencedEvent_Virtual()\n {\n var text = @\"class A\n{\n public virtual event System.EventHandler B;\n class C : A\n {\n public override event System.EventHandler B;\n }\n static int Main()\n {\n C c = new C();\n A a = c;\n return 0;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (3,46): warning CS0067: The event 'A.B' is never used\n // public virtual event System.EventHandler B;\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"B\").WithArguments(\"A.B\"),\n // (6,51): warning CS0067: The event 'A.C.B' is never used\n // public override event System.EventHandler B;\n Diagnostic(ErrorCode.WRN_UnreferencedEvent, \"B\").WithArguments(\"A.C.B\"));\n }\n\n\n [Fact, WorkItem(539630, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539630\")]\n public void CS0162WRN_UnreachableCode01()\n {\n var text = @\"\nclass MyTest { }\nclass MyClass\n{\n const MyTest test = null;\n public static int Main()\n {\n goto lab1;\n {\n // The following statements cannot be reached:\n int i = 9; // CS0162 \n i++;\n }\n lab1:\n if (test == null)\n {\n return 0;\n }\n else\n {\n return 1; // CS0162\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"int\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"));\n }\n\n [Fact, WorkItem(530037, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530037\")]\n public void CS0162WRN_UnreachableCode02()\n {\n var text = @\"\nusing System;\n\npublic class Test \n{\n public static void Main(string[] args)\n {\n // (1)\n do\n {\n for (; ; ) { }\n } while (args.Length > 0); // Native CS0162\n // (2)\n for (; ; ) // Roslyn CS0162\n {\n goto L2;\n Console.WriteLine(\"\"Unreachable code\"\");\n L2: // Roslyn CS0162\n break;\n }\n} }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,5): warning CS0162: Unreachable code detected\n // for (; ; ) // Roslyn CS0162\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"for\"),\n // (18,5): warning CS0162: Unreachable code detected\n // L2: // Roslyn CS0162\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"L2\")\n );\n }\n\n [Fact, WorkItem(539873, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539873\"), WorkItem(539981, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539981\")]\n public void CS0162WRN_UnreachableCode04()\n {\n var text = @\"\npublic class Cls\n{\n public static int Main()\n {\n goto Label2;\n return 0;\n Label1:\n return 1;\n Label2:\n goto Label1;\n return 2;\n }\n\n delegate void Sub_0(); \n static void M()\n {\n Sub_0 s1_3 = () => { if (2 == 1) return; else return; };\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"return\"));\n }\n\n [Fact, WorkItem(540901, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540901\")]\n public void CS0162WRN_UnreachableCode06_Loops()\n {\n var text = @\"\nclass Program\n{\n void F()\n {\n }\n void T()\n {\n for (int i = 0; i < 0; F(), i++) // F() is unreachable\n {\n return;\n }\n }\n\n static void Main()\n {\n string[] S = new string[] { \"\"ABC\"\", \"\"XYZ\"\" };\n foreach (string x in S)\n {\n foreach (char y in x)\n {\n goto stop;\n System.Console.WriteLine(y); // unreachable\n }\n\n foreach (char y in x)\n {\n throw new System.Exception();\n System.Console.WriteLine(y); // unreachable\n }\n stop:\n return;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"F\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"System\"),\n Diagnostic(ErrorCode.WRN_UnreachableCode, \"System\"));\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode06_Foreach03()\n {\n var text = @\"\npublic class Test\n{\n static public void Main(string[] args)\n {\n string[] S = new string[] { \"\"ABC\"\", \"\"XYZ\"\" };\n foreach (string x in S)\n {\n foreach (char y in x)\n {\n return;\n System.Console.WriteLine(y);\n }\n }\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, \"System\"));\n }\n\n [Fact]\n public void CS0162WRN_UnreachableCode07_GotoInLambda()\n {\n var text = @\"\nusing System;\nclass Program\n{\n static void Main()\n {\n Action a = () => { goto label1; Console.WriteLine(\"\"unreachable\"\"); label1: Console.WriteLine(\"\"reachable\"\"); };\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, @\"Console\"));\n }\n\n [Fact]\n public void CS0164WRN_UnreferencedLabel()\n {\n var text = @\"\npublic class a\n{\n public int i = 0;\n\n public static void Main()\n {\n int i = 0; // CS0164\n l1: i++;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"l1\").WithLocation(9, 7));\n }\n\n [Fact]\n public void CS0168WRN_UnreferencedVar01()\n {\n var text = @\"\npublic class clx\n{\n public int i;\n}\n\npublic class clz\n{\n public static void Main()\n {\n int j ; // CS0168, uncomment the following line\n // j++;\n clx a; // CS0168, try the following line instead\n // clx a = new clx();\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"j\").WithArguments(\"j\").WithLocation(11, 13),\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"a\").WithArguments(\"a\").WithLocation(13, 13));\n }\n\n [Fact]\n public void CS0168WRN_UnreferencedVar02()\n {\n var text =\n@\"using System;\nclass C\n{\n static void M()\n {\n try { }\n catch (InvalidOperationException e) { }\n catch (InvalidCastException e) { throw; }\n catch (Exception e) { throw e; }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(7, 42),\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(8, 37));\n }\n\n [Fact]\n public void CS0169WRN_UnreferencedField()\n {\n var text = @\"\npublic class ClassX\n{\n int i; // CS0169, i is not used anywhere\n\n public static void Main()\n {\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (4,8): warning CS0169: The field 'ClassX.i' is never used\n // int i; // CS0169, i is not used anywhere\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"i\").WithArguments(\"ClassX.i\")\n );\n }\n\n [Fact]\n public void CS0169WRN_UnreferencedField02()\n {\n var text =\n@\"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(\"\"OtherAssembly\"\")]\n\ninternal class InternalClass\n{\n internal int ActuallyInternal;\n internal int ActuallyInternalAssigned = 0;\n private int ActuallyPrivate;\n private int ActuallyPrivateAssigned = 0;\n public int EffectivelyInternal;\n public int EffectivelyInternalAssigned = 0;\n\n private class PrivateClass\n {\n public int EffectivelyPrivate;\n public int EffectivelyPrivateAssigned = 0;\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (7,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used\n // private int ActuallyPrivate;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"ActuallyPrivate\").WithArguments(\"InternalClass.ActuallyPrivate\"),\n // (8,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used\n // private int ActuallyPrivateAssigned = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"ActuallyPrivateAssigned\").WithArguments(\"InternalClass.ActuallyPrivateAssigned\"),\n // (14,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0\n // public int EffectivelyPrivate;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"EffectivelyPrivate\").WithArguments(\"InternalClass.PrivateClass.EffectivelyPrivate\", \"0\")\n );\n }\n\n [Fact]\n public void CS0169WRN_UnreferencedField03()\n {\n var text =\n@\"internal class InternalClass\n{\n internal int ActuallyInternal;\n internal int ActuallyInternalAssigned = 0;\n private int ActuallyPrivate;\n private int ActuallyPrivateAssigned = 0;\n public int EffectivelyInternal;\n public int EffectivelyInternalAssigned = 0;\n\n private class PrivateClass\n {\n public int EffectivelyPrivate;\n public int EffectivelyPrivateAssigned = 0;\n }\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (3,18): warning CS0649: Field 'InternalClass.ActuallyInternal' is never assigned to, and will always have its default value 0\n // internal int ActuallyInternal;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"ActuallyInternal\").WithArguments(\"InternalClass.ActuallyInternal\", \"0\"),\n // (5,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used\n // private int ActuallyPrivate;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"ActuallyPrivate\").WithArguments(\"InternalClass.ActuallyPrivate\"),\n // (6,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used\n // private int ActuallyPrivateAssigned = 0;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"ActuallyPrivateAssigned\").WithArguments(\"InternalClass.ActuallyPrivateAssigned\"),\n // (7,16): warning CS0649: Field 'InternalClass.EffectivelyInternal' is never assigned to, and will always have its default value 0\n // public int EffectivelyInternal;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"EffectivelyInternal\").WithArguments(\"InternalClass.EffectivelyInternal\", \"0\"),\n // (12,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0\n // public int EffectivelyPrivate;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"EffectivelyPrivate\").WithArguments(\"InternalClass.PrivateClass.EffectivelyPrivate\", \"0\")\n );\n }\n\n [Fact]\n public void CS0183WRN_IsAlwaysTrue()\n {\n var text = @\"using System;\npublic class IsTest10\n{\n public static int Main(String[] args)\n {\n Object obj3 = null;\n String str2 = \"\"Is 'is' too strict, per error CS0183?\"\";\n obj3 = str2;\n\n if (str2 is Object) // no error CS0183\n Console.WriteLine(\"\"str2 is Object\"\");\n\n Int32 int2 = 1;\n if (int2 is Object) // error CS0183\n Console.WriteLine(\"\"int2 is Object\"\");\n\n return 0;\n }\n}\n\";\n\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription { Code = (int)ErrorCode.WRN_IsAlwaysTrue, Line = 14, Column = 13, IsWarning = true });\n\n // TODO: extra checking\n }\n\n // Note: CS0184 tests moved to CodeGenOperator.cs to include IL verification.\n\n [WorkItem(530361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361\")]\n [Fact]\n public void CS0197WRN_ByRefNonAgileField()\n {\n var text = @\"\nclass X : System.MarshalByRefObject\n{\n public int i;\n}\n\nclass M\n{\n public int i;\n static void AddSeventeen(ref int i)\n {\n i += 17;\n }\n\n static void Main()\n {\n X x = new X();\n x.i = 12;\n AddSeventeen(ref x.i); // CS0197\n\n // OK\n M m = new M();\n m.i = 12;\n AddSeventeen(ref m.i);\n }\n}\n \";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,24): warning CS0197: Passing 'X.i' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // AddSeventeen(ref x.i); // CS0197\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"x.i\").WithArguments(\"X.i\"));\n }\n\n [WorkItem(530361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361\")]\n [Fact]\n public void CS0197WRN_ByRefNonAgileField_RefKind()\n {\n var text = @\"\nclass NotByRef\n{\n public int Instance;\n public static int Static;\n}\n\nclass ByRef : System.MarshalByRefObject\n{\n public int Instance;\n public static int Static;\n}\n\nclass Test\n{\n void M(ByRef b, NotByRef n)\n {\n None(n.Instance);\n Out(out n.Instance);\n Ref(ref n.Instance);\n\n None(NotByRef.Static);\n Out(out NotByRef.Static);\n Ref(ref NotByRef.Static);\n\n None(b.Instance);\n Out(out b.Instance);\n Ref(ref b.Instance);\n\n None(ByRef.Static);\n Out(out ByRef.Static);\n Ref(ref ByRef.Static);\n }\n\n void None(int x) { throw null; }\n void Out(out int x) { throw null; }\n void Ref(ref int x) { throw null; }\n}\n \";\n CreateCompilation(text).VerifyDiagnostics(\n // (27,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Out(out b.Instance);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"b.Instance\").WithArguments(\"ByRef.Instance\"),\n // (28,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Ref(ref b.Instance);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"b.Instance\").WithArguments(\"ByRef.Instance\"));\n }\n\n [WorkItem(530361, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361\")]\n [Fact]\n public void CS0197WRN_ByRefNonAgileField_Receiver()\n {\n var text = @\"\nusing System;\n\nclass ByRef : MarshalByRefObject\n{\n public int F;\n\n protected void Ref(ref int x) { }\n\n void Test()\n {\n Ref(ref F);\n\n Ref(ref this.F);\n Ref(ref ((ByRef)this).F);\n }\n}\n\nclass Derived : ByRef\n{\n void Test()\n {\n Ref(ref F);\n\n Ref(ref this.F);\n Ref(ref ((ByRef)this).F);\n\n Ref(ref base.F);\n //Ref(ref ((ByRef)base).F);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (15,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Ref(ref ((ByRef)this).F);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"((ByRef)this).F\").WithArguments(\"ByRef.F\"),\n // (26,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class\n // Ref(ref ((ByRef)this).F);\n Diagnostic(ErrorCode.WRN_ByRefNonAgileField, \"((ByRef)this).F\").WithArguments(\"ByRef.F\"));\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg01()\n {\n var text = @\"public class MyClass\n{\n public static void Main()\n {\n int a = 0; // CS0219\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (5,13): warning CS0219: The variable 'a' is assigned but its value is never used\n // int a = 0; // CS0219\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"a\").WithArguments(\"a\")\n );\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg02()\n {\n var text = @\"\npublic class clx\n{\n static void Main(string[] args)\n {\n int x = 1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\").WithLocation(6, 13));\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg03()\n {\n var text = @\"\npublic class clx\n{\n static void Main(string[] args)\n {\n int? x;\n x = null;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\").WithLocation(6, 14));\n }\n\n [Fact, WorkItem(542473, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542473\"), WorkItem(542474, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542474\")]\n public void CS0219WRN_UnreferencedVarAssg_StructString()\n {\n var text = @\"\nclass program\n{\n static void Main(string[] args)\n {\n s1 y = new s1();\n string s = \"\"\"\";\n }\n}\nstruct s1 { }\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,12): warning CS0219: The variable 'y' is assigned but its value is never used\n // s1 y = new s1();\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"y\").WithArguments(\"y\").WithLocation(6, 12),\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"s\").WithArguments(\"s\").WithLocation(7, 16)\n );\n }\n\n [Fact, WorkItem(542494, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542494\")]\n public void CS0219WRN_UnreferencedVarAssg_Default()\n {\n var text = @\"\nclass S\n{\n public int x = 5;\n}\n\nclass C\n{\n public static void Main()\n {\n var x = default(S);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (11,13): warning CS0219: The variable 'x' is assigned but its value is never used\n // var x = default(S);\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"x\").WithArguments(\"x\").WithLocation(11, 13)\n );\n }\n\n [Fact]\n public void CS0219WRN_UnreferencedVarAssg_For()\n {\n var text = @\"\nclass C\n{\n public static void Main()\n {\n for (int i = 1; ; )\n {\n break;\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,18): warning CS0219: The variable 'i' is assigned but its value is never used\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"i\").WithArguments(\"i\").WithLocation(6, 18)\n );\n }\n\n [Fact, WorkItem(546619, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546619\")]\n public void NoCS0219WRN_UnreferencedVarAssg_ObjectInitializer()\n {\n var text = @\"\nstruct S\n{\n public int X { set {} }\n}\nclass C\n{\n public static void Main()\n {\n S s = new S { X = 2 }; // no error - not a constant\n int? i = new int? { }; // ditto - not the default value (though bitwise equal to it)\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(542472, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542472\")]\n public void CS0251WRN_NegativeArrayIndex()\n {\n var text = @\"\nclass C\n{\n static void Main()\n {\n int[] a = new int[1];\n int[,] b = new int[1, 1];\n a[-1] = 1; // CS0251\n a[-1, -1] = 1; // Dev10 reports CS0022 and CS0251 (twice), Roslyn reports CS0022\n b[-1] = 1; // CS0022\n b[-1, -1] = 1; // fine\n }\n}\n \";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,11): warning CS0251: Indexing an array with a negative index (array indices always start at zero)\n Diagnostic(ErrorCode.WRN_NegativeArrayIndex, \"-1\"),\n // (9,9): error CS0022: Wrong number of indices inside []; expected '1'\n Diagnostic(ErrorCode.ERR_BadIndexCount, \"a[-1, -1]\").WithArguments(\"1\"),\n // (10,9): error CS0022: Wrong number of indices inside []; expected '2'\n Diagnostic(ErrorCode.ERR_BadIndexCount, \"b[-1]\").WithArguments(\"2\"));\n }\n\n [WorkItem(530362, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362\"), WorkItem(670322, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322\")]\n [Fact]\n public void CS0252WRN_BadRefCompareLeft()\n {\n var text =\n@\"class MyClass\n{\n public static void Main()\n {\n string s = \"\"11\"\";\n object o = s + s;\n\n bool b = o == s; // CS0252\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,16): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'\n // bool b = o == s; // CS0252\n Diagnostic(ErrorCode.WRN_BadRefCompareLeft, \"o == s\").WithArguments(\"string\")\n );\n }\n\n [WorkItem(781070, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070\")]\n [Fact]\n public void CS0252WRN_BadRefCompareLeft_02()\n {\n var text =\n@\"using System;\n\npublic class Symbol\n{\n public static bool operator ==(Symbol a, Symbol b)\n {\n return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b);\n }\n public static bool operator !=(Symbol a, Symbol b)\n {\n return !(a == b);\n }\n public override bool Equals(object obj)\n {\n return (obj is Symbol || obj == null) ? this == (Symbol)obj : false;\n }\n public override int GetHashCode()\n {\n return 0;\n }\n}\n\npublic class MethodSymbol : Symbol\n{\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n MethodSymbol a1 = null;\n MethodSymbol a2 = new MethodSymbol();\n\n // In these cases the programmer explicitly inserted a cast to use object equality instead\n // of the user-defined equality operator. Since the programmer did this explicitly, in\n // Roslyn we suppress the diagnostic that was given by the native compiler suggesting casting\n // the object-typed operand back to type Symbol to get value equality.\n Console.WriteLine((object)a1 == a2);\n Console.WriteLine((object)a1 != a2);\n Console.WriteLine((object)a2 == a1);\n Console.WriteLine((object)a2 != a1);\n\n Console.WriteLine(a1 == (object)a2);\n Console.WriteLine(a1 != (object)a2);\n Console.WriteLine(a2 == (object)a1);\n Console.WriteLine(a2 != (object)a1);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [WorkItem(781070, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070\")]\n [Fact]\n public void CS0252WRN_BadRefCompareLeft_03()\n {\n var text =\n@\"using System;\n\npublic class Symbol\n{\n public static bool operator ==(Symbol a, Symbol b)\n {\n return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b);\n }\n public static bool operator !=(Symbol a, Symbol b)\n {\n return !(a == b);\n }\n public override bool Equals(object obj)\n {\n return (obj is Symbol || obj == null) ? this == (Symbol)obj : false;\n }\n public override int GetHashCode()\n {\n return 0;\n }\n}\n\npublic class MethodSymbol : Symbol\n{\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Object a1 = null;\n MethodSymbol a2 = new MethodSymbol();\n\n Console.WriteLine(a1 == a2);\n Console.WriteLine(a1 != a2);\n Console.WriteLine(a2 == a1);\n Console.WriteLine(a2 != a1);\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (34,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol'\n // Console.WriteLine(a1 == a2);\n Diagnostic(ErrorCode.WRN_BadRefCompareLeft, \"a1 == a2\").WithArguments(\"Symbol\"),\n // (35,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol'\n // Console.WriteLine(a1 != a2);\n Diagnostic(ErrorCode.WRN_BadRefCompareLeft, \"a1 != a2\").WithArguments(\"Symbol\"),\n // (36,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol'\n // Console.WriteLine(a2 == a1);\n Diagnostic(ErrorCode.WRN_BadRefCompareRight, \"a2 == a1\").WithArguments(\"Symbol\"),\n // (37,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol'\n // Console.WriteLine(a2 != a1);\n Diagnostic(ErrorCode.WRN_BadRefCompareRight, \"a2 != a1\").WithArguments(\"Symbol\")\n );\n }\n\n [WorkItem(530362, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362\"), WorkItem(670322, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322\")]\n [Fact]\n public void CS0253WRN_BadRefCompareRight()\n {\n var text =\n@\"\nclass MyClass\n{\n public static void Main()\n {\n string s = \"\"11\"\";\n object o = s + s;\n\n bool c = s == o; // CS0253\n // try the following line instead\n // bool c = s == (string)o;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,16): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string'\n // bool c = s == o; // CS0253\n Diagnostic(ErrorCode.WRN_BadRefCompareRight, \"s == o\").WithArguments(\"string\")\n );\n }\n\n [WorkItem(730177, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730177\")]\n [Fact]\n public void CS0253WRN_BadRefCompare_None()\n {\n var text =\n@\"using System;\nclass MyClass\n{\n public static void Main()\n {\n MulticastDelegate x1 = null;\n bool b1 = x1 == null;\n bool b2 = x1 != null;\n bool b3 = null == x1;\n bool b4 = null != x1;\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [WorkItem(542399, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542399\")]\n [Fact]\n public void CS0278WRN_PatternIsAmbiguous01()\n {\n var text = @\"\nusing System.Collections.Generic;\npublic class myTest \n{\n public static void TestForeach(W w) \n where W: IEnumerable, IEnumerable\n {\n foreach (int i in w) {} // CS0278\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,25): warning CS0278: 'W' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable.GetEnumerator()'.\n // foreach (int i in w) {} // CS0278\n Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"w\").WithArguments(\"W\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\"),\n // (8,25): error CS1640: foreach statement cannot operate on variables of type 'W' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable'; try casting to a specific interface instantiation\n // foreach (int i in w) {} // CS0278\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"w\").WithArguments(\"W\", \"System.Collections.Generic.IEnumerable\"));\n }\n\n [Fact]\n public void CS0278WRN_PatternIsAmbiguous02()\n {\n var text =\n@\"using System.Collections;\nusing System.Collections.Generic;\nclass A : IEnumerable\n{\n public IEnumerator GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass B : IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass C : IEnumerable, IEnumerable\n{\n public IEnumerator GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass D : IEnumerable, IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n IEnumerator IEnumerable.GetEnumerator() { return null; }\n}\nclass E\n{\n static void M(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10)\n where T1 : A, IEnumerable // duplicate interfaces\n where T2 : B, IEnumerable // duplicate interfaces\n where T3 : A, IEnumerable, IEnumerable // multiple interfaces\n where T4 : B, IEnumerable, IEnumerable // multiple interfaces\n where T5 : C, IEnumerable // multiple interfaces\n where T6 : D, IEnumerable // multiple interfaces\n where T7 : A, IEnumerable, IEnumerable // duplicate and multiple interfaces\n where T8 : B, IEnumerable, IEnumerable // duplicate and multiple interfaces\n where T9 : C, IEnumerable // duplicate and multiple interfaces\n where T10 : D, IEnumerable // duplicate and multiple interfaces\n {\n foreach (A o in t1) { }\n foreach (B o in t2) { }\n foreach (A o in t3) { }\n foreach (var o in t4) { }\n foreach (C o in t5) { }\n foreach (int o in t6) { }\n foreach (A o in t7) { }\n foreach (var o in t8) { }\n foreach (C o in t9) { }\n foreach (D o in t10) { }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (42,27): warning CS0278: 'T4' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable.GetEnumerator()'.\n Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"t4\").WithArguments(\"T4\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\").WithLocation(42, 27),\n // (42,27): error CS1640: foreach statement cannot operate on variables of type 'T4' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable'; try casting to a specific interface instantiation\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"t4\").WithArguments(\"T4\", \"System.Collections.Generic.IEnumerable\").WithLocation(42, 27),\n // (46,27): warning CS0278: 'T8' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable.GetEnumerator()'.\n Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, \"t8\").WithArguments(\"T8\", \"collection\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\", \"System.Collections.Generic.IEnumerable.GetEnumerator()\").WithLocation(46, 27),\n // (46,27): error CS1640: foreach statement cannot operate on variables of type 'T8' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable'; try casting to a specific interface instantiation\n Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, \"t8\").WithArguments(\"T8\", \"System.Collections.Generic.IEnumerable\").WithLocation(46, 27));\n }\n\n [Fact]\n public void CS0279WRN_PatternStaticOrInaccessible()\n {\n var text = @\"\nusing System.Collections;\n\npublic class myTest : IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n\n internal IEnumerator GetEnumerator()\n {\n return null;\n }\n\n public static void Main()\n {\n foreach (int i in new myTest()) {} // CS0279\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,27): warning CS0279: 'myTest' does not implement the 'collection' pattern. 'myTest.GetEnumerator()' is not a public instance or extension method.\n Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, \"new myTest()\").WithArguments(\"myTest\", \"collection\", \"myTest.GetEnumerator()\"));\n }\n\n [Fact]\n public void CS0280WRN_PatternBadSignature()\n {\n var text = @\"\nusing System.Collections;\n\npublic class ValidBase: IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n\n internal IEnumerator GetEnumerator()\n {\n return null;\n }\n}\n\nclass Derived : ValidBase\n{\n // field, not method\n new public int GetEnumerator;\n}\n\npublic class Test\n{\n public static void Main()\n {\n foreach (int i in new Derived()) {} // CS0280\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (27,25): warning CS0280: 'Derived' does not implement the 'collection' pattern. 'Derived.GetEnumerator' has the wrong signature.\n // foreach (int i in new Derived()) {} // CS0280\n Diagnostic(ErrorCode.WRN_PatternBadSignature, \"new Derived()\").WithArguments(\"Derived\", \"collection\", \"Derived.GetEnumerator\"),\n // (20,19): warning CS0649: Field 'Derived.GetEnumerator' is never assigned to, and will always have its default value 0\n // new public int GetEnumerator;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"GetEnumerator\").WithArguments(\"Derived.GetEnumerator\", \"0\")\n );\n }\n\n [Fact]\n public void CS0414WRN_UnreferencedFieldAssg()\n {\n var text = @\"\nclass C\n{\n private int i = 1; // CS0414\n\n public static void Main()\n { }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (4,16): warning CS0414: The field 'C.i' is assigned but its value is never used\n // private int i = 1; // CS0414\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"i\").WithArguments(\"C.i\")\n );\n }\n\n [Fact]\n public void CS0414WRN_UnreferencedFieldAssg02()\n {\n var text =\n@\"class S\n{\n T1 t1_field = default(T1);\n}\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (3,8): warning CS0414: The field 'S.t1_field' is assigned but its value is never used\n // T1 t1_field = default(T1);\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"t1_field\").WithArguments(\"S.t1_field\").WithLocation(3, 8)\n );\n }\n\n [Fact]\n public void CS0419WRN_AmbiguousXMLReference()\n {\n var text = @\"\ninterface I\n{\n void F();\n void F(int i);\n}\npublic class MyClass\n{\n /// \n public static void MyMethod(int i)\n {\n }\n public static void Main ()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,14): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass'\n // public class MyClass\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"MyClass\").WithArguments(\"MyClass\"),\n // (9,19): warning CS0419: Ambiguous reference in cref attribute: 'I.F'. Assuming 'I.F()', but could have also matched other overloads including 'I.F(int)'.\n // /// \n Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, \"I.F\").WithArguments(\"I.F\", \"I.F()\", \"I.F(int)\"),\n // (13,23): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass.Main()'\n // public static void Main ()\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"Main\").WithArguments(\"MyClass.Main()\"));\n }\n\n [Fact]\n public void CS0420WRN_VolatileByRef()\n {\n var text = @\"\nclass TestClass\n{\n private volatile int i;\n\n public void TestVolatileRef(ref int ii)\n {\n }\n\n public void TestVolatileOut(out int ii)\n {\n ii = 0;\n }\n\n public static void Main()\n {\n TestClass x = new TestClass();\n x.TestVolatileRef(ref x.i); // CS0420 \n x.TestVolatileOut(out x.i); // CS0420 \n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (18,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x.i\").WithArguments(\"TestClass.i\"),\n // (19,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x.i\").WithArguments(\"TestClass.i\"));\n }\n\n [Fact]\n public void CS0420WRN_VolatileByRef_Suppressed()\n {\n var text = @\"\nusing System.Threading;\n\nclass TestClass\n{\n private static volatile int x = 0;\n\n public static void TestVolatileByRef()\n {\n Interlocked.Increment(ref x); // no CS0420 \n Interlocked.Decrement(ref x); // no CS0420\n Interlocked.Add(ref x, 0); // no CS0420\n Interlocked.CompareExchange(ref x, 0, 0); // no CS0420\n Interlocked.Exchange(ref x, 0); // no CS0420\n\n // using fully qualified name\n System.Threading.Interlocked.Increment(ref x); // no CS0420 \n System.Threading.Interlocked.Decrement(ref x); // no CS0420\n System.Threading.Interlocked.Add(ref x, 0); // no CS0420\n System.Threading.Interlocked.CompareExchange(ref x, 0, 0); // no CS0420\n System.Threading.Interlocked.Exchange(ref x, 0); // no CS0420\n\n // passing volatile variables in a nested way\n Interlocked.Increment(ref Method1(ref x).y); // CS0420 for x \n Interlocked.Decrement(ref Method1(ref x).y); // CS0420 for x\n Interlocked.Add(ref Method1(ref x).y, 0); // CS0420 for x\n Interlocked.CompareExchange(ref Method1(ref x).y, 0, 0); // CS0420 for x\n Interlocked.Exchange(ref Method1(ref x).y, 0); // CS0420 for x\n\n // located as a function argument \n goo(Interlocked.Increment(ref x)); // no CS0420\n\n }\n\n public static int goo(int x)\n {\n return x; \n } \n\n public static MyClass Method1(ref int x)\n {\n return new MyClass();\n }\n\n public class MyClass\n {\n public volatile int y = 0;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (24,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (25,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (26,39): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (27,51): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"),\n // (28,44): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"TestClass.x\"));\n }\n\n [WorkItem(728380, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728380\")]\n [Fact]\n public void Repro728380()\n {\n var source = @\"\nclass Test\n{\n static volatile int x;\n unsafe static void goo(int* pX) { }\n\n static int Main()\n {\n unsafe { Test.goo(&x); }\n return 1;\n }\n}\n\";\n CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,27): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer\n // unsafe { Test.goo(&x); }\n Diagnostic(ErrorCode.ERR_FixedNeeded, \"&x\"),\n // (9,28): warning CS0420: 'Test.x': a reference to a volatile field will not be treated as volatile\n // unsafe { Test.goo(&x); }\n Diagnostic(ErrorCode.WRN_VolatileByRef, \"x\").WithArguments(\"Test.x\"));\n }\n\n [Fact, WorkItem(528275, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275\")]\n public void CS0429WRN_UnreachableExpr()\n {\n var text = @\"\npublic class cs0429 \n{\n public static void Main() \n {\n if (false && myTest()) // CS0429\n // Try the following line instead:\n // if (true && myTest())\n {\n }\n else\n {\n int i = 0;\n i++;\n }\n }\n\n static bool myTest() { return true; }\n}\n\";\n // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions.\n // We don't report the warning.\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(528275, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275\"), WorkItem(530071, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530071\")]\n public void CS0429WRN_UnreachableExpr_02()\n {\n var text = @\"\nclass Program\n{\n static bool b = true;\n const bool con = true;\n static void Main(string[] args)\n {\n int x = 1;\n int y = 1;\n int s = true ? x++ : y++; // y++ unreachable\n s = x == y ? x++ : y++; // OK\n s = con ? x++ : y++; // y++ unreachable\n bool con1 = true;\n s = con1 ? x++ : y++; // OK\n s = b ? x++ : y++;\n s = 1 < 2 ? x++ : y++; \t// y++ unreachable\n }\n}\n\";\n // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions.\n // We don't report the warning.\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact, WorkItem(543943, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543943\")]\n public void CS0458WRN_AlwaysNull()\n {\n var text = @\"\npublic class Test \n{\n public static void Main()\n {\n int? x = 0;\n\n x = null + x;\n x = x + default(int?);\n x += new int?();\n\n x = null - x;\n x = x - default(int?);\n x -= new int?();\n\n x = null * x;\n x = x * default(int?);\n x *= new int?();\n\n x = null / x;\n x = x / default(int?);\n x /= new int?();\n\n x = null % x;\n x = x % default(int?);\n x %= new int?();\n\n x = null << x;\n x = x << default(int?);\n x <<= new int?();\n\n x = null >> x;\n x = x >> default(int?);\n x >>= new int?();\n \n x = null & x;\n x = x & default(int?);\n x &= new int?();\n\n x = null | x;\n x = x | default(int?);\n x |= new int?();\n\n x = null ^ x;\n x = x ^ default(int?);\n x ^= new int?();\n\n //The below block of code should not raise a warning\n bool? y = null;\n y = y & null;\n y = y |false;\n y = true | null;\n\n double? d = +default(double?);\n int? i = -default(int?);\n long? l = ~default(long?);\n bool? b = !default(bool?);\n\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null + x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x + default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x += new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null - x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x - default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x -= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null * x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x * default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x *= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null / x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x / default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x /= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null % x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x % default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x %= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null << x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x << default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x <<= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null >> x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x >> default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x >>= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null & x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x & default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x &= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null | x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x | default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x |= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"null ^ x\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x ^ default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"x ^= new int?()\").WithArguments(\"int?\"),\n\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"+default(double?)\").WithArguments(\"double?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"-default(int?)\").WithArguments(\"int?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"~default(long?)\").WithArguments(\"long?\"),\n Diagnostic(ErrorCode.WRN_AlwaysNull, \"!default(bool?)\").WithArguments(\"bool?\")\n );\n }\n\n [Fact]\n public void CS0464WRN_CmpAlwaysFalse()\n {\n var text = @\"\nclass MyClass\n{\n public struct S\n {\n public static bool operator <(S x, S y) { return true; } \n public static bool operator >(S x, S y) { return true; }\n public static bool operator <=(S x, S y) { return true; } \n public static bool operator >=(S x, S y) { return true; }\n\n }\n\n public static void W(bool b)\n {\n System.Console.Write(b ? 't' : 'f');\n }\n\n public static void Main()\n {\n S s = default(S);\n S? t = s;\n int i = 0;\n int? n = i;\n\n W(i < null); // CS0464\n W(i <= null); // CS0464\n W(i > null); // CS0464\n W(i >= null); // CS0464\n\n W(n < null); // CS0464\n W(n <= null); // CS0464\n W(n > null); // CS0464\n W(n >= null); // CS0464\n\n W(s < null); // CS0464\n W(s <= null); // CS0464\n W(s > null); // CS0464\n W(s >= null); // CS0464\n\n W(t < null); // CS0464\n W(t <= null); // CS0464\n W(t > null); // CS0464\n W(t >= null); // CS0464\n\n W(i < default(short?)); // CS0464\n W(i <= default(short?)); // CS0464\n W(i > default(short?)); // CS0464\n W(i >= default(short?)); // CS0464\n\n W(n < default(short?)); // CS0464\n W(n <= default(short?)); // CS0464\n W(n > default(short?)); // CS0464\n W(n >= default(short?)); // CS0464\n\n W(s < default(S?)); // CS0464\n W(s <= default(S?)); // CS0464\n W(s > default(S?)); // CS0464\n W(s >= default(S?)); // CS0464\n\n W(t < default(S?)); // CS0464\n W(t <= default(S?)); // CS0464\n W(t > default(S?)); // CS0464\n W(t >= default(S?)); // CS0464\n\n W(i < new sbyte?()); // CS0464\n W(i <= new sbyte?()); // CS0464\n W(i > new sbyte?()); // CS0464\n W(i >= new sbyte?()); // CS0464\n\n W(n < new sbyte?()); // CS0464\n W(n <= new sbyte?()); // CS0464\n W(n > new sbyte?()); // CS0464\n W(n >= new sbyte?()); // CS0464\n\n W(s < new S?()); // CS0464\n W(s <= new S?()); // CS0464\n W(s > new S?()); // CS0464\n W(s >= new S?()); // CS0464\n\n W(t < new S?()); // CS0464\n W(t <= new S?()); // CS0464\n W(t > new S?()); // CS0464\n W(t >= new S?()); // CS0464\n\n System.Console.WriteLine();\n\n W(null < i); // CS0464\n W(null <= i); // CS0464\n W(null > i); // CS0464\n W(null >= i); // CS0464\n\n W(null < n); // CS0464\n W(null <= n); // CS0464\n W(null > n); // CS0464\n W(null >= n); // CS0464\n\n W(null < s); // CS0464\n W(null <= s); // CS0464\n W(null > s); // CS0464\n W(null >= s); // CS0464\n\n W(null < t); // CS0464\n W(null <= t); // CS0464\n W(null > t); // CS0464\n W(null >= t); // CS0464\n\n W(default(short?) < i); // CS0464\n W(default(short?) <= i); // CS0464\n W(default(short?) > i); // CS0464\n W(default(short?) >= i); // CS0464\n\n W(default(short?) < n); // CS0464\n W(default(short?) <= n); // CS0464\n W(default(short?) > n); // CS0464\n W(default(short?) >= n); // CS0464\n\n W(default(S?) < s); // CS0464\n W(default(S?) <= s); // CS0464\n W(default(S?) > s); // CS0464\n W(default(S?) >= s); // CS0464\n\n W(default(S?) < t); // CS0464\n W(default(S?) <= t); // CS0464\n W(default(S?) > t); // CS0464\n W(default(S?) >= t); // CS0464\n\n W(new sbyte?() < i); // CS0464\n W(new sbyte?() <= i); // CS0464\n W(new sbyte?() > i); // CS0464\n W(new sbyte?() >= i); // CS0464\n\n W(new sbyte?() < n); // CS0464\n W(new sbyte?() <= n); // CS0464\n W(new sbyte?() > n); // CS0464\n W(new sbyte?() > n); // CS0464\n\n W(new S?() < s); // CS0464\n W(new S?() <= s); // CS0464\n W(new S?() > s); // CS0464\n W(new S?() >= s); // CS0464\n\n W(new S?() < t); // CS0464\n W(new S?() <= t); // CS0464\n W(new S?() > t); // CS0464\n W(new S?() > t); // CS0464\n\n System.Console.WriteLine();\n\n W(null > null); // CS0464\n W(null >= null); // CS0464\n W(null < null); // CS0464\n W(null <= null); // CS0464\n }\n}\n\";\n var verifier = CompileAndVerify(source: text, expectedOutput: @\"ffffffffffffffffffffffffffffffffffffffffffffffff\nffffffffffffffffffffffffffffffffffffffffffffffff\nffff\");\n\n CreateCompilation(text).VerifyDiagnostics(\n // (25,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i < null\").WithArguments(\"int?\"),\n // (26,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i <= null\").WithArguments(\"int?\"),\n // (27,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i > null\").WithArguments(\"int?\"),\n // (28,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(i >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i >= null\").WithArguments(\"int?\"),\n // (30,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n < null\").WithArguments(\"int?\"),\n // (31,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n <= null\").WithArguments(\"int?\"),\n // (32,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n > null\").WithArguments(\"int?\"),\n // (33,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(n >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n >= null\").WithArguments(\"int?\"),\n // (35,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s < null\").WithArguments(\"MyClass.S?\"),\n // (36,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s <= null\").WithArguments(\"MyClass.S?\"),\n // (37,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s > null\").WithArguments(\"MyClass.S?\"),\n // (38,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s >= null\").WithArguments(\"MyClass.S?\"),\n // (40,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t < null\").WithArguments(\"MyClass.S?\"),\n // (41,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t <= null\").WithArguments(\"MyClass.S?\"),\n // (42,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t > null\").WithArguments(\"MyClass.S?\"),\n // (43,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t >= null\").WithArguments(\"MyClass.S?\"),\n // (45,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i < default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i < default(short?)\").WithArguments(\"short?\"),\n // (46,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i <= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i <= default(short?)\").WithArguments(\"short?\"),\n // (47,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i > default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i > default(short?)\").WithArguments(\"short?\"),\n // (48,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(i >= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i >= default(short?)\").WithArguments(\"short?\"),\n // (50,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n < default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n < default(short?)\").WithArguments(\"short?\"),\n // (51,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n <= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n <= default(short?)\").WithArguments(\"short?\"),\n // (52,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n > default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n > default(short?)\").WithArguments(\"short?\"),\n // (53,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(n >= default(short?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n >= default(short?)\").WithArguments(\"short?\"),\n // (55,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s < default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s < default(S?)\").WithArguments(\"MyClass.S?\"),\n // (56,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s <= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s <= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (57,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s > default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s > default(S?)\").WithArguments(\"MyClass.S?\"),\n // (58,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s >= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s >= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (60,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t < default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t < default(S?)\").WithArguments(\"MyClass.S?\"),\n // (61,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t <= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t <= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (62,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t > default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t > default(S?)\").WithArguments(\"MyClass.S?\"),\n // (63,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t >= default(S?)); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t >= default(S?)\").WithArguments(\"MyClass.S?\"),\n // (65,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i < new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i < new sbyte?()\").WithArguments(\"sbyte?\"),\n // (66,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i <= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i <= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (67,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i > new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i > new sbyte?()\").WithArguments(\"sbyte?\"),\n // (68,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(i >= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"i >= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (70,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n < new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n < new sbyte?()\").WithArguments(\"sbyte?\"),\n // (71,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n <= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n <= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (72,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n > new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n > new sbyte?()\").WithArguments(\"sbyte?\"),\n // (73,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(n >= new sbyte?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"n >= new sbyte?()\").WithArguments(\"sbyte?\"),\n // (75,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s < new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s < new S?()\").WithArguments(\"MyClass.S?\"),\n // (76,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s <= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s <= new S?()\").WithArguments(\"MyClass.S?\"),\n // (77,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s > new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s > new S?()\").WithArguments(\"MyClass.S?\"),\n // (78,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(s >= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"s >= new S?()\").WithArguments(\"MyClass.S?\"),\n // (80,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t < new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t < new S?()\").WithArguments(\"MyClass.S?\"),\n // (81,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t <= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t <= new S?()\").WithArguments(\"MyClass.S?\"),\n // (82,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t > new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t > new S?()\").WithArguments(\"MyClass.S?\"),\n // (83,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(t >= new S?()); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"t >= new S?()\").WithArguments(\"MyClass.S?\"),\n // (87,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null < i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < i\").WithArguments(\"int?\"),\n // (88,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null <= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= i\").WithArguments(\"int?\"),\n // (89,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null > i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > i\").WithArguments(\"int?\"),\n // (90,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null >= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= i\").WithArguments(\"int?\"),\n // (92,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null < n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < n\").WithArguments(\"int?\"),\n // (93,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null <= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= n\").WithArguments(\"int?\"),\n // (94,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > n\").WithArguments(\"int?\"),\n // (95,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null >= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= n\").WithArguments(\"int?\"),\n // (97,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null < s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < s\").WithArguments(\"MyClass.S?\"),\n // (98,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null <= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= s\").WithArguments(\"MyClass.S?\"),\n // (99,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null > s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > s\").WithArguments(\"MyClass.S?\"),\n // (100,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null >= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= s\").WithArguments(\"MyClass.S?\"),\n // (102,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null < t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < t\").WithArguments(\"MyClass.S?\"),\n // (103,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null <= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= t\").WithArguments(\"MyClass.S?\"),\n // (104,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > t\").WithArguments(\"MyClass.S?\"),\n // (105,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(null >= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= t\").WithArguments(\"MyClass.S?\"),\n // (107,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) < i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) < i\").WithArguments(\"short?\"),\n // (108,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) <= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) <= i\").WithArguments(\"short?\"),\n // (109,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) > i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) > i\").WithArguments(\"short?\"),\n // (110,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) >= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) >= i\").WithArguments(\"short?\"),\n // (112,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) < n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) < n\").WithArguments(\"short?\"),\n // (113,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) <= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) <= n\").WithArguments(\"short?\"),\n // (114,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) > n\").WithArguments(\"short?\"),\n // (115,11): warning CS0464: Comparing with null of type 'short?' always produces 'false'\n // W(default(short?) >= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(short?) >= n\").WithArguments(\"short?\"),\n // (117,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) < s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) < s\").WithArguments(\"MyClass.S?\"),\n // (118,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) <= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) <= s\").WithArguments(\"MyClass.S?\"),\n // (119,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) > s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) > s\").WithArguments(\"MyClass.S?\"),\n // (120,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) >= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) >= s\").WithArguments(\"MyClass.S?\"),\n // (122,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) < t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) < t\").WithArguments(\"MyClass.S?\"),\n // (123,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) <= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) <= t\").WithArguments(\"MyClass.S?\"),\n // (124,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) > t\").WithArguments(\"MyClass.S?\"),\n // (125,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(default(S?) >= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"default(S?) >= t\").WithArguments(\"MyClass.S?\"),\n // (127,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() < i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() < i\").WithArguments(\"sbyte?\"),\n // (128,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() <= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() <= i\").WithArguments(\"sbyte?\"),\n // (129,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() > i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() > i\").WithArguments(\"sbyte?\"),\n // (130,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() >= i); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() >= i\").WithArguments(\"sbyte?\"),\n // (132,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() < n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() < n\").WithArguments(\"sbyte?\"),\n // (133,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() <= n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() <= n\").WithArguments(\"sbyte?\"),\n // (134,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() > n\").WithArguments(\"sbyte?\"),\n // (135,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false'\n // W(new sbyte?() > n); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new sbyte?() > n\").WithArguments(\"sbyte?\"),\n // (137,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() < s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() < s\").WithArguments(\"MyClass.S?\"),\n // (138,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() <= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() <= s\").WithArguments(\"MyClass.S?\"),\n // (139,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() > s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() > s\").WithArguments(\"MyClass.S?\"),\n // (140,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() >= s); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() >= s\").WithArguments(\"MyClass.S?\"),\n // (142,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() < t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() < t\").WithArguments(\"MyClass.S?\"),\n // (143,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() <= t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() <= t\").WithArguments(\"MyClass.S?\"),\n // (144,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() > t\").WithArguments(\"MyClass.S?\"),\n // (145,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false'\n // W(new S?() > t); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"new S?() > t\").WithArguments(\"MyClass.S?\"),\n // (149,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null > null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null > null\").WithArguments(\"int?\"),\n // (150,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null >= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null >= null\").WithArguments(\"int?\"),\n // (151,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null < null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null < null\").WithArguments(\"int?\"),\n // (152,11): warning CS0464: Comparing with null of type 'int?' always produces 'false'\n // W(null <= null); // CS0464\n Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, \"null <= null\").WithArguments(\"int?\")\n );\n }\n\n [Fact]\n public void CS0469WRN_GotoCaseShouldConvert()\n {\n var text = @\"\nclass Test\n{\n static void Main()\n {\n char c = (char)180;\n switch (c)\n {\n case (char)127:\n break;\n\n case (char)180: \n goto case 127; // CS0469\n // try the following line instead\n // goto case (char) 127;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,13): warning CS0469: The 'goto case' value is not implicitly convertible to type 'char'\n // goto case 127; // CS0469\n Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, \"goto case 127;\").WithArguments(\"char\").WithLocation(13, 13)\n );\n }\n\n [Fact, WorkItem(663, \"https://github.com/dotnet/roslyn/issues/663\")]\n public void CS0472WRN_NubExprIsConstBool()\n {\n // Due to a long-standing bug, the native compiler does not produce warnings for \"guid == null\",\n // but does for \"int == null\". Roslyn corrects this lapse and produces warnings for both built-in\n // and user-defined lifted equality operators, but the new warnings for user-defined types are\n // only given with /warn:n where n >= 5.\n\n var text = @\"\nusing System;\nclass MyClass\n{\n public static void W(bool b)\n {\n System.Console.Write(b ? 't' : 'f');\n }\n\n enum E : int { };\n\n public static void Main()\n {\n Guid g = default(Guid);\n Guid? h = g;\n int i = 0;\n int? n = i;\n\n W(i == null); // CS0472\n W(i != null); // CS0472\n W(n == null); // no error\n W(n != null); // no error\n W(g == null); // CS0472\n W(g != null); // CS0472\n W(h == null); // no error\n W(h != null); // no error\n\n W(i == default(short?)); // CS0472\n W(i != default(short?)); // CS0472\n W(n == default(short?)); // no error\n W(n != default(short?)); // no error\n W(g == default(Guid?)); // CS0472\n W(g != default(Guid?)); // CS0472\n W(h == default(Guid?)); // no error\n W(h != default(Guid?)); // no error\n\n W(i == new sbyte?()); // CS0472\n W(i != new sbyte?()); // CS0472\n W(n == new sbyte?()); // no error\n W(n != new sbyte?()); // no error\n W(g == new Guid?()); // CS0472\n W(g != new Guid?()); // CS0472\n W(h == new Guid?()); // no error\n W(h != new Guid?()); // no error\n\n System.Console.WriteLine();\n\n\n W(null == i); // CS0472\n W(null != i); // CS0472\n W(null == n); // no error\n W(null != n); // no error\n W(null == g); // CS0472\n W(null != g); // CS0472\n W(null == h); // no error\n W(null != h); // no error\n\n W(default(long?) == i); // CS0472\n W(default(long?) != i); // CS0472\n W(default(long?) == n); // no error\n W(default(long?) != n); // no error\n W(default(Guid?) == g); // CS0472\n W(default(Guid?) != g); // CS0472\n W(default(Guid?) == h); // no error\n W(default(Guid?) != h); // no error\n\n W(new double?() == i); // CS0472\n W(new double?() != i); // CS0472\n W(new double?() == n); // no error\n W(new double?() != n); // no error\n W(new Guid?() == g); // CS0472\n W(new Guid?() != g); // CS0472\n W(new Guid?() == h); // no error\n W(new Guid?() != h); // no error\n\n System.Console.WriteLine();\n\n W(null == null); // No error, because both sides are nullable, but of course\n W(null != null); // we could give a warning here as well.\n\n System.Console.WriteLine();\n\n //check comparisons with converted constants\n W((E?)1 == null);\n W(null != (E?)1);\n\n W((int?)1 == null);\n W(null != (int?)1);\n\n //check comparisons when null is converted \n\n W(0 == (int?)null);\n W((int?)null != 0);\n \n W(0 == (E?)null);\n W((E?)null != 0);\n }\n}\n\";\n\n string expected = @\"ftftftftftftftftftftftft\nftftftftftftftftftftftft\ntf\nftftftft\";\n var fullExpected = new DiagnosticDescription[] {\n // (19,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(i == null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(19, 11),\n // (20,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(i != null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != null\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(20, 11),\n // (23,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g == null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g == null\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(23, 11),\n // (24,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g != null); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g != null\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(24, 11),\n // (28,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?'\n // W(i == default(short?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == default(short?)\").WithArguments(\"false\", \"int\", \"short?\").WithLocation(28, 11),\n // (29,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'short?'\n // W(i != default(short?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != default(short?)\").WithArguments(\"true\", \"int\", \"short?\").WithLocation(29, 11),\n // (32,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g == default(Guid?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g == default(Guid?)\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(32, 11),\n // (33,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g != default(Guid?)); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g != default(Guid?)\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(33, 11),\n // (37,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'sbyte?'\n // W(i == new sbyte?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == new sbyte?()\").WithArguments(\"false\", \"int\", \"sbyte?\").WithLocation(37, 11),\n // (38,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'sbyte?'\n // W(i != new sbyte?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i != new sbyte?()\").WithArguments(\"true\", \"int\", \"sbyte?\").WithLocation(38, 11),\n // (41,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g == new Guid?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g == new Guid?()\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(41, 11),\n // (42,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(g != new Guid?()); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"g != new Guid?()\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(42, 11),\n // (49,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(null == i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null == i\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(49, 11),\n // (50,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(null != i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != i\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(50, 11),\n // (53,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(null == g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"null == g\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(53, 11),\n // (54,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(null != g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"null != g\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(54, 11),\n // (58,11): warning CS0472: The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?'\n // W(default(long?) == i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"default(long?) == i\").WithArguments(\"false\", \"long\", \"long?\").WithLocation(58, 11),\n // (59,11): warning CS0472: The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?'\n // W(default(long?) != i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"default(long?) != i\").WithArguments(\"true\", \"long\", \"long?\").WithLocation(59, 11),\n // (62,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(default(Guid?) == g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"default(Guid?) == g\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(62, 11),\n // (63,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(default(Guid?) != g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"default(Guid?) != g\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(63, 11),\n // (67,11): warning CS0472: The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?'\n // W(new double?() == i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"new double?() == i\").WithArguments(\"false\", \"double\", \"double?\").WithLocation(67, 11),\n // (68,11): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?'\n // W(new double?() != i); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"new double?() != i\").WithArguments(\"true\", \"double\", \"double?\").WithLocation(68, 11),\n // (71,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(new Guid?() == g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"new Guid?() == g\").WithArguments(\"false\", \"System.Guid\", \"System.Guid?\").WithLocation(71, 11),\n // (72,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?'\n // W(new Guid?() != g); // CS0472\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, \"new Guid?() != g\").WithArguments(\"true\", \"System.Guid\", \"System.Guid?\").WithLocation(72, 11),\n // (84,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W((E?)1 == null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(E?)1 == null\").WithArguments(\"false\", \"MyClass.E\", \"MyClass.E?\").WithLocation(84, 11),\n // (85,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W(null != (E?)1);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != (E?)1\").WithArguments(\"true\", \"MyClass.E\", \"MyClass.E?\").WithLocation(85, 11),\n // (87,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W((int?)1 == null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(int?)1 == null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(87, 11),\n // (88,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(null != (int?)1);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"null != (int?)1\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(88, 11),\n // (92,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W(0 == (int?)null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"0 == (int?)null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(92, 11),\n // (93,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'\n // W((int?)null != 0);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(int?)null != 0\").WithArguments(\"true\", \"int\", \"int?\").WithLocation(93, 11),\n // (95,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W(0 == (E?)null);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"0 == (E?)null\").WithArguments(\"false\", \"MyClass.E\", \"MyClass.E?\").WithLocation(95, 11),\n // (96,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?'\n // W((E?)null != 0);\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"(E?)null != 0\").WithArguments(\"true\", \"MyClass.E\", \"MyClass.E?\").WithLocation(96, 11)\n };\n var compatibleExpected = fullExpected.Where(d => !d.Code.Equals((int)ErrorCode.WRN_NubExprIsConstBool2)).ToArray();\n this.CompileAndVerify(source: text, expectedOutput: expected, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(compatibleExpected);\n this.CompileAndVerify(source: text, expectedOutput: expected).VerifyDiagnostics(fullExpected);\n }\n\n [Fact]\n public void CS0472WRN_NubExprIsConstBool_ConstructorInitializer()\n {\n var text =\n@\"class A\n{\n internal A(bool b)\n {\n }\n}\nclass B : A\n{\n B(int i) : base(i == null)\n {\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (9,21): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n // B(int i) : base(i == null)\n Diagnostic(ErrorCode.WRN_NubExprIsConstBool, \"i == null\").WithArguments(\"false\", \"int\", \"int?\").WithLocation(9, 21));\n }\n\n [Fact]\n public void CS0612WRN_DeprecatedSymbol()\n {\n var text = @\"\nusing System;\nclass MyClass\n{\n [Obsolete]\n public static void ObsoleteMethod()\n {\n }\n\n [Obsolete]\n public static int ObsoleteField;\n}\nclass MainClass\n{\n static public void Main()\n {\n MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated\n MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated\n }\n}\n\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (17,7): warning CS0612: 'MyClass.ObsoleteMethod()' is obsolete\n // MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated\n Diagnostic(ErrorCode.WRN_DeprecatedSymbol, \"MyClass.ObsoleteMethod()\").WithArguments(\"MyClass.ObsoleteMethod()\"),\n // (18,7): warning CS0612: 'MyClass.ObsoleteField' is obsolete\n // MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated\n Diagnostic(ErrorCode.WRN_DeprecatedSymbol, \"MyClass.ObsoleteField\").WithArguments(\"MyClass.ObsoleteField\"));\n }\n\n [Fact, WorkItem(546062, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062\")]\n public void CS0618WRN_DeprecatedSymbol()\n {\n var text = @\"\npublic class ConsoleStub\n{\n public static void Main(string[] args)\n {\n System.Collections.CaseInsensitiveHashCodeProvider x;\n System.Console.WriteLine(x);\n }\n}\";\n CreateCompilation(text).\n VerifyDiagnostics(\n // (6,9): warning CS0618: 'System.Collections.CaseInsensitiveHashCodeProvider' is obsolete: 'Please use StringComparer instead.'\n // System.Collections.CaseInsensitiveHashCodeProvider x;\n Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, \"System.Collections.CaseInsensitiveHashCodeProvider\").WithArguments(\"System.Collections.CaseInsensitiveHashCodeProvider\", \"Please use StringComparer instead.\"),\n // (7,34): error CS0165: Use of unassigned local variable 'x'\n // System.Console.WriteLine(x);\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"x\").WithArguments(\"x\"));\n }\n\n [WorkItem(545347, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347\")]\n [Fact]\n public void CS0649WRN_UnassignedInternalField()\n {\n var text = @\"\nusing System.Collections;\n\nclass MyClass\n{\n Hashtable table; // CS0649\n \n public void Func(object o, string p)\n {\n table[p] = o;\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (6,15): warning CS0649: Field 'MyClass.table' is never assigned to, and will always have its default value null\n // Hashtable table; // CS0649\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"table\").WithArguments(\"MyClass.table\", \"null\")\n );\n }\n\n [Fact, WorkItem(543454, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543454\")]\n public void CS0649WRN_UnassignedInternalField_1()\n {\n var text = @\"\npublic class GenClass { }\npublic class Outer\n{\n internal protected class C1 { }\n public class C2 { }\n internal class Test\n {\n public GenClass Fld;\n }\n public static int Main() { return 0; }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"Fld\").WithArguments(\"Outer.Test.Fld\", \"null\"));\n }\n\n [WorkItem(546449, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546449\")]\n [WorkItem(546949, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546949\")]\n [Fact]\n public void CS0652WRN_VacuousIntegralComp()\n {\n var text = @\"\npublic class Class1\n{\n private static byte i = 0;\n public static void Main()\n {\n const short j = 256;\n if (i == j) // CS0652, 256 is out of range for byte\n i = 0;\n\n // However, we do not give this warning if both sides of the comparison are constants. In those\n // cases, we are probably in machine-generated code anyways.\n\n const byte k = 0;\n if (k == j) {}\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,11): warning CS0652: Comparison to integral constant is useless; the constant is outside the range of type 'byte'\n // if (i == j) // CS0652, 256 is out of range for byte\n Diagnostic(ErrorCode.WRN_VacuousIntegralComp, \"i == j\").WithArguments(\"byte\"));\n }\n\n [WorkItem(546790, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546790\")]\n [Fact]\n public void CS0652WRN_VacuousIntegralComp_ExplicitCast()\n {\n var text = @\"\nusing System;\n\npublic class Program\n{\n public static void Main()\n {\n Int16 wSuiteMask = 0; \n const int VER_SUITE_WH_SERVER = 0x00008000;\n if (VER_SUITE_WH_SERVER == (Int32)wSuiteMask)\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS0665WRN_IncorrectBooleanAssg()\n {\n var text = @\"\nclass Test\n{\n public static void Main()\n {\n bool i = false;\n\n if (i = true) // CS0665\n // try the following line instead\n // if (i == true)\n {\n }\n\n System.Console.WriteLine(i);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,11): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"i = true\"));\n }\n\n [Fact, WorkItem(540777, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777\")]\n public void CS0665WRN_IncorrectBooleanAssg_ConditionalOperator()\n {\n var text = @\"\nclass Program\n{\n static int Main(string[] args)\n {\n bool a = true;\n System.Console.WriteLine(a);\n return ((a = false) ? 50 : 100); // Warning\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"a = false\"));\n }\n\n [Fact]\n public void CS0665WRN_IncorrectBooleanAssg_Contexts()\n {\n var text = @\"\nclass C\n{\n static void Main(string[] args)\n {\n bool b = args.Length > 1;\n\n if (b = false) { }\n while (b = false) { }\n do { } while (b = false);\n for (; b = false; ) { }\n System.Console.WriteLine((b = false) ? 1 : 2);\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,13): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // if (b = false) { }\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (9,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // while (b = false) { }\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (10,23): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // do { } while (b = false);\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (11,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // for (; b = false; ) { }\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (12,35): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // System.Console.WriteLine((b = false) ? 1 : 2);\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"));\n }\n\n [Fact]\n public void CS0665WRN_IncorrectBooleanAssg_Nesting()\n {\n var text = @\"\nclass C\n{\n static void Main(string[] args)\n {\n bool b = args.Length > 1;\n\n if ((b = false)) { } // parens - warn\n if (((b = false))) { } // more parens - warn\n if (M(b = false)) { } // call - do not warn\n if ((bool)(b = false)) { } // cast - do not warn\n if ((b = false) || (b = true)) { } // binary operator - do not warn\n\n B bb = new B();\n if (bb = false) { } // implicit conversion - do not warn\n }\n\n static bool M(bool b) { return b; }\n}\n\nclass B\n{\n public static implicit operator B(bool b)\n {\n return new B();\n }\n\n public static bool operator true(B b)\n {\n return true;\n }\n\n public static bool operator false(B b)\n {\n return false;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,14): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // if ((b = false)) { } // parens - warn\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"),\n // (9,15): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?\n // if (((b = false))) { } // more parens - warn\n Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, \"b = false\"));\n }\n\n [Fact, WorkItem(909, \"https://github.com/dotnet/roslyn/issues/909\")]\n public void CS0675WRN_BitwiseOrSignExtend()\n {\n var text = @\"\npublic class sign\n{\n public static void Main()\n {\n int i32_hi = 1;\n int i32_lo = 1;\n ulong u64 = 1;\n sbyte i08 = 1;\n short i16 = -1;\n\n object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675\n object v2 = (ulong)i32_hi | u64; // CS0675\n object v3 = (ulong)i32_hi | (ulong)i32_lo; // No warning; the sign extension bits are the same on both sides.\n object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675\n object v5 = (int)i08 | (int)i32_lo; // No warning; sign extension is considered to be 'expected' when casting.\n object v6 = (((ulong)i32_hi) << 32) | (uint) i32_lo; // No warning; we've cast to a smaller unsigned type first. \n // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one:\n object v7 = 0x0000BEEFU | (uint)i16; \n object v8 = 0xFFFFBEEFU | (uint)i16; \n object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 \n\n// We should do the exact same logic for nullables.\n\n int? ni32_hi = 1;\n int? ni32_lo = 1;\n ulong? nu64 = 1;\n sbyte? ni08 = 1;\n short? ni16 = -1;\n\n object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675\n object v12 = (ulong?)ni32_hi | nu64; // CS0675\n object v13 = (ulong?)ni32_hi | (ulong?)ni32_lo; // No warning; the sign extension bits are the same on both sides.\n object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675\n object v15 = (int?)ni08 | (int?)ni32_lo; // No warning; sign extension is considered to be 'expected' when casting.\n object v16 = (((ulong?)ni32_hi) << 32) | (uint?) ni32_lo; // No warning; we've cast to a smaller unsigned type first. \n // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one:\n object v17 = 0x0000BEEFU | (uint?)ni16; \n object v18 = 0xFFFFBEEFU | (uint?)ni16; \n object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 \n }\n}\n\nclass Test\n{\n static void Main()\n {\n long bits = 0;\n for (int i = 0; i < 32; i++)\n {\n if (i % 2 == 0)\n {\n bits |= (1 << i);\n bits = bits | (1 << i);\n }\n }\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (12,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(((long)i32_hi) << 32) | i32_lo\"),\n // (13,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v2 = (ulong)i32_hi | u64; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong)i32_hi | u64\"),\n // (15,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong)(uint)(ushort)i08 | (ulong)i32_lo\"),\n // (21,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 \n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"0xDEADBEEFU | (uint)i16\"),\n // (31,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(((long?)ni32_hi) << 32) | ni32_lo\"),\n // (32,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v12 = (ulong?)ni32_hi | nu64; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong?)ni32_hi | nu64\"),\n // (34,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"(ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo\"),\n // (40,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 \n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"0xDEADBEEFU | (uint?)ni16\"),\n // (53,17): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // bits |= (1 << i);\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"bits |= (1 << i)\").WithLocation(53, 17),\n // (54,24): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first\n // bits = bits | (1 << i);\n Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, \"bits | (1 << i)\").WithLocation(54, 24)\n );\n }\n\n [Fact]\n public void CS0728WRN_AssignmentToLockOrDispose01()\n {\n CreateCompilation(@\"\nusing System;\npublic class ValidBase : IDisposable\n{\n public void Dispose() { }\n}\n\npublic class Logger\n{\n public static void dummy()\n {\n ValidBase vb = null;\n using (vb) \n {\n vb = null; // CS0728\n }\n vb = null;\n }\n public static void Main() { }\n}\")\n .VerifyDiagnostics(\n // (15,13): warning CS0728: Possibly incorrect assignment to local 'vb' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.\n Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, \"vb\").WithArguments(\"vb\"));\n }\n\n [Fact]\n public void CS0728WRN_AssignmentToLockOrDispose02()\n {\n CreateCompilation(\n@\"class D : System.IDisposable\n{\n public void Dispose() { }\n}\nclass C\n{\n static void M()\n {\n D d = new D();\n using (d)\n {\n N(ref d);\n }\n lock (d)\n {\n N(ref d);\n }\n }\n static void N(ref D d)\n {\n }\n}\")\n .VerifyDiagnostics(\n Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, \"d\").WithArguments(\"d\").WithLocation(12, 19),\n Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, \"d\").WithArguments(\"d\").WithLocation(16, 19));\n }\n\n [WorkItem(543615, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615\"), WorkItem(546550, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546550\")]\n [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]\n public void CS0811ERR_DebugFullNameTooLong()\n {\n var text = @\"\nusing System;\nusing System.Collections.Generic;\n\nnamespace TestNamespace\n{\n using VeryLong = List>>>>>>>>>>>>>>>>>>>>>>>>>>>; // CS0811\n\n class Test\n {\n static int Main()\n {\n VeryLong goo = null;\n Console.WriteLine(goo);\n return 1;\n }\n }\n}\n\";\n\n var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.DebugExe);\n\n var exebits = new System.IO.MemoryStream();\n var pdbbits = new System.IO.MemoryStream();\n var result = compilation.Emit(exebits, pdbbits, options: TestOptions.NativePdbEmit);\n\n result.Diagnostics.Verify(\n // (12,20): warning CS0811: The fully qualified name for 'AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is too long for debug information. Compile without '/debug' option.\n // static int Main()\n Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, \"Main\").WithArguments(\"AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\").WithLocation(12, 20));\n }\n\n [Fact]\n public void CS1058WRN_UnreachableGeneralCatch()\n {\n var text =\n@\"class C\n{\n static void M()\n {\n try { }\n catch (System.Exception) { }\n catch (System.IO.IOException) { }\n catch { }\n try { }\n catch (System.IO.IOException) { }\n catch (System.Exception) { }\n catch { }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"System.IO.IOException\").WithArguments(\"System.Exception\").WithLocation(7, 16),\n Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, \"catch\").WithLocation(8, 9),\n Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, \"catch\").WithLocation(12, 9));\n }\n\n // [Fact(Skip = \"11486\")]\n // public void CS1060WRN_UninitializedField()\n // {\n // var text = @\"\n //namespace CS1060\n //{\n // public class U\n // {\n // public int i;\n // }\n //\n // public struct S\n // {\n // public U u;\n // }\n // public class Test\n // {\n // static void Main()\n // {\n // S s;\n // s.u.i = 5; // CS1060\n // }\n // }\n //}\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_UninitializedField, Line = 18, Column = 13, IsWarning = true } });\n // }\n\n // [Fact()]\n // public void CS1064ERR_DebugFullNameTooLong()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = 1064, Line = 7, Column = 5, IsWarning = true } }\n // );\n // }\n\n [Fact]\n public void CS1570WRN_XMLParseError()\n {\n var text = @\"\nnamespace ns\n{\n // the following line generates CS1570\n /// returns true if < 5 \n // try this instead\n // /// returns true if &lt;5 \n\n public class MyClass\n {\n public static void Main ()\n {\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (5,35): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.'\n // /// returns true if < 5 \n Diagnostic(ErrorCode.WRN_XMLParseError, \"\"),\n // (5,35): warning CS1570: XML comment has badly formed XML -- '5'\n // /// returns true if < 5 \n Diagnostic(ErrorCode.WRN_XMLParseError, \" \").WithArguments(\"5\"),\n // (11,26): warning CS1591: Missing XML comment for publicly visible type or member 'ns.MyClass.Main()'\n // public static void Main ()\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"Main\").WithArguments(\"ns.MyClass.Main()\"));\n }\n\n [Fact]\n public void CS1571WRN_DuplicateParamTag()\n {\n var text = @\"\n/// help text\npublic class MyClass\n{\n /// Used to indicate status.\n /// An initial.\n /// Used to indicate status. // CS1571\n public static void MyMethod(int Int1, char Char1)\n {\n }\n\n /// help text\n public static void Main ()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,15): warning CS1571: XML comment has a duplicate param tag for 'Int1'\n // /// Used to indicate status. // CS1571\n Diagnostic(ErrorCode.WRN_DuplicateParamTag, \"name='Int1'\").WithArguments(\"Int1\"));\n }\n\n [Fact]\n public void CS1572WRN_UnmatchedParamTag()\n {\n var text = @\"\n/// help text\npublic class MyClass\n{\n /// Used to indicate status.\n /// Used to indicate status.\n /// ??? // CS1572\n public static void MyMethod(int Int1, char Char1)\n {\n }\n\n /// help text\n public static void Main ()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,21): warning CS1572: XML comment has a param tag for 'Char2', but there is no parameter by that name\n // /// ??? // CS1572\n Diagnostic(ErrorCode.WRN_UnmatchedParamTag, \"Char2\").WithArguments(\"Char2\"));\n }\n\n [Fact]\n public void CS1573WRN_MissingParamTag()\n {\n var text = @\"\n/// \npublic class MyClass\n{\n /// Used to indicate status.\n /// enter a comment for Char1?\n public static void MyMethod(int Int1, char Char1)\n {\n }\n /// \n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (7,48): warning CS1573: Parameter 'Char1' has no matching param tag in the XML comment for 'MyClass.MyMethod(int, char)' (but other parameters do)\n // public static void MyMethod(int Int1, char Char1)\n Diagnostic(ErrorCode.WRN_MissingParamTag, \"Char1\").WithArguments(\"Char1\", \"MyClass.MyMethod(int, char)\"));\n }\n\n [Fact]\n public void CS1574WRN_BadXMLRef()\n {\n var text = @\"\n/// \npublic class C\n{\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,16): warning CS1574: XML comment has cref attribute 'D' that could not be resolved\n // /// \n Diagnostic(ErrorCode.WRN_BadXMLRef, \"D\").WithArguments(\"D\"));\n }\n\n [Fact]\n public void CS1580WRN_BadXMLRefParamType()\n {\n var text = @\"\n/// // CS1580\npublic class MyClass\n{\n /// help text\n public static void Main()\n {\n }\n /// help text\n public void Test(int i)\n {\n }\n /// help text\n public void Test(char i)\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,20): warning CS1580: Invalid type for parameter 'i' in XML comment cref attribute: 'Test(i)'\n // /// // CS1580\n Diagnostic(ErrorCode.WRN_BadXMLRefParamType, \"i\").WithArguments(\"i\", \"Test(i)\"),\n // (2,20): warning CS1574: XML comment has cref attribute 'Test(i)' that could not be resolved\n // /// // CS1580\n Diagnostic(ErrorCode.WRN_BadXMLRef, \"Test(i)\").WithArguments(\"Test(i)\"));\n }\n\n [Fact]\n public void CS1581WRN_BadXMLRefReturnType()\n {\n var text = @\"\n/// help text\npublic class MyClass\n{\n /// help text\n public static void Main()\n {\n }\n /// help text\n public static explicit operator int(MyClass f)\n {\n return 0;\n }\n}\n/// // CS1581\npublic class MyClass2\n{\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (15,20): warning CS1581: Invalid return type in XML comment cref attribute\n // /// // CS1581\n Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, \"intt\").WithArguments(\"intt\", \"MyClass.explicit operator intt(MyClass)\"),\n // (15,20): warning CS1574: XML comment has cref attribute 'MyClass.explicit operator intt(MyClass)' that could not be resolved\n // /// // CS1581\n Diagnostic(ErrorCode.WRN_BadXMLRef, \"MyClass.explicit operator intt(MyClass)\").WithArguments(\"explicit operator intt(MyClass)\"));\n }\n\n [Fact]\n public void CS1584WRN_BadXMLRefSyntax()\n {\n var text = @\"\n/// \npublic class MyClass1\n{\n /// \n public static MyClass1 operator /(MyClass1 a1, MyClass1 a2)\n {\n return null;\n }\n /// \n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (10,24): warning CS1584: XML comment has syntactically incorrect cref attribute 'MyClass1.operator@'\n // /// \n Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, \"MyClass1.operator\").WithArguments(\"MyClass1.operator@\"),\n // (10,41): warning CS1658: Overloadable operator expected. See also error CS1037.\n // /// \n Diagnostic(ErrorCode.WRN_ErrorOverride, \"@\").WithArguments(\"Overloadable operator expected\", \"1037\"),\n // (10,41): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @\n // /// \n Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, \"\"));\n }\n\n [Fact]\n public void CS1587WRN_UnprocessedXMLComment()\n {\n var text = @\"\n/// test // CS1587, tag not allowed on namespace\nnamespace MySpace\n{\n class MyClass\n {\n public static void Main()\n {\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, \"/\"));\n }\n\n [Fact]\n public void CS1589WRN_NoResolver()\n {\n var text = @\"\n/// // CS1589\nclass Test\n{\n public static void Main()\n {\n }\n}\n\";\n var c = CreateCompilation(\n new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) },\n options: TestOptions.ReleaseDll.WithXmlReferenceResolver(null));\n\n c.VerifyDiagnostics(\n // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name=\"test\"]/' of file 'CS1589.doc' -- References to XML documents are not supported.\n // /// // CS1589\n Diagnostic(ErrorCode.WRN_FailedInclude, @\"\").\n WithArguments(\"CS1589.doc\", @\"MyDocs/MyMembers[@name=\"\"test\"\"]/\", \"References to XML documents are not supported.\"));\n }\n\n [Fact]\n public void CS1589WRN_FailedInclude()\n {\n var text = @\"\n/// // CS1589\nclass Test\n{\n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name=\"test\"]/' of file 'CS1589.doc' -- Unable to find the specified file.\n // /// // CS1589\n Diagnostic(ErrorCode.WRN_FailedInclude, @\"\").\n WithArguments(\"CS1589.doc\", @\"MyDocs/MyMembers[@name=\"\"test\"\"]/\", \"File not found.\"));\n }\n\n [Fact]\n public void CS1590WRN_InvalidInclude()\n {\n var text = @\"\n/// // CS1590\nclass Test\n{\n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute\n // /// // CS1590\n Diagnostic(ErrorCode.WRN_InvalidInclude, @\"\").WithArguments(\"Missing file attribute\"));\n }\n\n [Fact]\n public void CS1591WRN_MissingXMLComment()\n {\n var text = @\"\n/// text\npublic class Test\n{\n // /// text\n public static void Main() // CS1591\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'Test.Main()'\n // public static void Main() // CS1591\n Diagnostic(ErrorCode.WRN_MissingXMLComment, \"Main\").WithArguments(\"Test.Main()\"));\n }\n\n [ConditionalFact(typeof(WindowsDesktopOnly), Reason = \"https://github.com/dotnet/roslyn/issues/18610\")]\n public void CS1592WRN_XMLParseIncludeError()\n {\n var xmlFile = Temp.CreateFile(extension: \".xml\").WriteAllText(\"&\");\n var sourceTemplate = @\"\n/// \npublic class Test {{ }}\n\";\n var comp = CreateCompilationWithMscorlib40AndDocumentationComments(string.Format(sourceTemplate, xmlFile.Path));\n\n using (new EnsureEnglishUICulture())\n {\n comp.VerifyDiagnostics(\n // dcf98d2ac30a.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.'\n Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments(\"Data at the root level is invalid.\"));\n }\n }\n\n [Fact]\n public void CS1658WRN_ErrorOverride()\n {\n var text = @\"\n/// \npublic class Test \n{\n ///\n public static int Main() \n {\n return 0;\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''\n // /// \n Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @\"\"\"\").WithArguments(\"\"),\n // (2,20): warning CS1658: Identifier expected. See also error CS1001.\n // /// \n Diagnostic(ErrorCode.WRN_ErrorOverride, @\"\"\"\").WithArguments(\"Identifier expected\", \"1001\"));\n }\n\n // TODO (tomat): Also fix AttributeTests.DllImport_AttributeRedefinition\n [Fact(Skip = \"530377\"), WorkItem(530377, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530377\"), WorkItem(685159, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685159\")]\n public void CS1685WRN_MultiplePredefTypes()\n {\n var text = @\"\npublic static class C\n{\n public static void Extension(this int X) {}\n}\";\n // include both mscorlib 4.0 and System.Core 3.5, both of which contain ExtensionAttribute\n // These libraries are not yet in our suite\n CreateEmptyCompilation(text).\n VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MultiplePredefTypes, \"\"));\n }\n\n [Fact, WorkItem(530379, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379\")]\n public void CS1690WRN_CallOnNonAgileField()\n {\n var text = @\"\nusing System;\n\nclass WarningCS1690 : MarshalByRefObject\n{\n int i = 5;\n\n public static void Main()\n {\n WarningCS1690 e = new WarningCS1690();\n e.i.ToString(); // CS1690\n int i = e.i;\n i.ToString();\n e.i = i;\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_CallOnNonAgileField, Line = 11, Column = 9, IsWarning = true } });\n }\n\n [Fact, WorkItem(530379, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379\")]\n public void CS1690WRN_CallOnNonAgileField_Variations()\n {\n var text = @\"\nusing System;\n\nstruct S\n{\n public event Action Event;\n public int Field;\n public int Property { get; set; }\n public int this[int x] { get { return 0; } set { } }\n public void M() { }\n\n class WarningCS1690 : MarshalByRefObject\n {\n S s;\n\n public static void Main()\n {\n WarningCS1690 w = new WarningCS1690();\n w.s.Event = null;\n w.s.Event += null;\n w.s.Property++;\n w.s[0]++;\n w.s.M();\n Action a = w.s.M;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (19,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.Event = null;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (20,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.Event += null;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (21,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.Property++;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (22,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s[0]++;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (23,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // w.s.M();\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n // (24,24): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class\n // Action a = w.s.M;\n Diagnostic(ErrorCode.WRN_CallOnNonAgileField, \"w.s\").WithArguments(\"S.WarningCS1690.s\"),\n\n // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0\n // public int Field;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"Field\").WithArguments(\"S.Field\", \"0\"),\n // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used\n // public event Action Event;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"Event\").WithArguments(\"S.Event\"));\n }\n\n [Fact, WorkItem(530379, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379\")]\n public void CS1690WRN_CallOnNonAgileField_Class()\n {\n var text = @\"\nusing System;\n\nclass S\n{\n public event Action Event;\n public int Field;\n public int Property { get; set; }\n public int this[int x] { get { return 0; } set { } }\n public void M() { }\n\n class WarningCS1690 : MarshalByRefObject\n {\n S s;\n\n public static void Main()\n {\n WarningCS1690 w = new WarningCS1690();\n w.s.Event = null;\n w.s.Event += null;\n w.s.Property++;\n w.s[0]++;\n w.s.M();\n Action a = w.s.M;\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,11): warning CS0649: Field 'S.WarningCS1690.s' is never assigned to, and will always have its default value null\n // S s;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"s\").WithArguments(\"S.WarningCS1690.s\", \"null\"),\n // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0\n // public int Field;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"Field\").WithArguments(\"S.Field\", \"0\"),\n // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used\n // public event Action Event;\n Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, \"Event\").WithArguments(\"S.Event\"));\n }\n\n // [Fact()]\n // public void CS1707WRN_DelegateNewMethBind()\n // {\n // var text = @\"\n //\";\n // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_DelegateNewMethBind, Line = 7, Column = 5, IsWarning = true } }\n // );\n // }\n\n [Fact(), WorkItem(530384, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530384\")]\n public void CS1709WRN_EmptyFileName()\n {\n var text = @\"\nclass Test\n{\n static void Main()\n {\n#pragma checksum \"\"\"\" \"\"{406EA660-64CF-4C82-B6F0-42D48172A799}\"\" \"\"\"\" // CS1709\n }\n}\n\";\n //EDMAURER no longer giving this low-value warning.\n CreateCompilation(text).\n VerifyDiagnostics();\n //VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptyFileName, @\"\"\"\"));\n }\n\n [Fact]\n public void CS1710WRN_DuplicateTypeParamTag()\n {\n var text = @\"\nclass Stack\n{\n}\n/// can be an int\n/// can be an int\nclass MyStackWrapper\n{\n // Open constructed type Stack.\n Stack stack;\n public MyStackWrapper(Stack s)\n {\n stack = s;\n }\n}\nclass CMain\n{\n public static void Main()\n {\n }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (6,16): warning CS1710: XML comment has a duplicate typeparam tag for 'MyType'\n // /// can be an int\n Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @\"name=\"\"MyType\"\"\").WithArguments(\"MyType\"));\n }\n\n [Fact]\n public void CS1711WRN_UnmatchedTypeParamTag()\n {\n var text = @\"\n///can be an int\nclass CMain\n{\n public static void Main() { }\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (2,21): warning CS1711: XML comment has a typeparam tag for 'WrongName', but there is no type parameter by that name\n // ///can be an int\n Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, \"WrongName\").WithArguments(\"WrongName\"));\n }\n\n [Fact]\n public void CS1712WRN_MissingTypeParamTag()\n {\n var text = @\"\n///A generic list delegate.\n///The first type stored by the list.\npublic delegate void List();\n\n///\npublic class Test\n{\n ///\n public static void Main()\n {\n }\n}\t\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (4,29): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'List' (but other type parameters do)\n // public delegate void List();\n Diagnostic(ErrorCode.WRN_MissingTypeParamTag, \"W\").WithArguments(\"W\", \"List\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf()\n {\n var text = @\"\npublic class Test\n{\n public static void Main()\n {\n int x = 0;\n x = x; // CS1717\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text,\n new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_AssignmentToSelf, Line = 7, Column = 7, IsWarning = true } });\n }\n\n [WorkItem(543470, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543470\")]\n [Fact]\n public void CS1717WRN_AssignmentToSelf02()\n {\n var text = @\"\nclass C\n{\n void M(object p)\n {\n object oValue = p;\n if (oValue is int)\n {\n //(SQL 9.0) 653716 + common sense\n oValue = (double) ((int) oValue);\n }\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf03()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n int f;\n event Action e;\n\n void Test(int p)\n {\n int l = 0;\n\n l = l;\n p = p;\n f = f;\n e = e;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (13,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // l = l;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"l = l\"),\n // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // p = p;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"p = p\"),\n // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // f = f;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"f = f\"),\n // (16,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // e = e;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"e = e\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf04()\n {\n var text = @\"\nusing System;\n\nclass Program\n{\n int f;\n event Action e;\n \n static int sf;\n static event Action se;\n\n void Test(Program other)\n {\n f = this.f;\n e = this.e;\n\n f = other.f; //fine\n e = other.e; //fine\n\n sf = sf;\n se = se;\n\n sf = Program.sf;\n se = Program.se;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // f = this.f;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"f = this.f\"),\n // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // e = this.e;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"e = this.e\"),\n // (20,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // sf = sf;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"sf = sf\"),\n // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // se = se;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"se = se\"),\n // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // sf = Program.sf;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"sf = Program.sf\"),\n // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // se = Program.se;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"se = Program.se\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf05()\n {\n var text = @\"\nusing System.Linq;\n\nclass Program\n{\n static void Main(string[] args)\n {\n var unused = from x in args select x = x;\n }\n}\n\";\n // CONSIDER: dev11 reports WRN_AssignmentToSelf.\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (8,44): error CS1947: Range variable 'x' cannot be assigned to -- it is read only\n // var unused = from x in args select x = x;\n Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, \"x\").WithArguments(\"x\"));\n }\n\n [Fact]\n public void CS1717WRN_AssignmentToSelf06()\n {\n var text = @\"\nclass C\n{\n void M(\n byte b,\n sbyte sb,\n short s,\n ushort us,\n int i,\n uint ui,\n long l,\n ulong ul,\n float f,\n double d,\n decimal m,\n bool bo,\n object o,\n C cl,\n S st)\n {\n b = (byte)b;\n sb = (sbyte)sb;\n s = (short)s;\n us = (ushort)us;\n i = (int)i;\n ui = (uint)ui;\n l = (long)l;\n ul = (ulong)ul;\n f = (float)f; // Not reported by dev11.\n d = (double)d; // Not reported by dev11.\n m = (decimal)m;\n bo = (bool)bo;\n o = (object)o;\n cl = (C)cl;\n st = (S)st;\n }\n}\n\nstruct S\n{\n}\n\";\n // CONSIDER: dev11 does not strip off float or double identity-conversions and, thus,\n // does not warn about those assignments.\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // b = (byte)b;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"b = (byte)b\"),\n // (22,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // sb = (sbyte)sb;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"sb = (sbyte)sb\"),\n // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // s = (short)s;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"s = (short)s\"),\n // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // us = (ushort)us;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"us = (ushort)us\"),\n // (25,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // i = (int)i;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"i = (int)i\"),\n // (26,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // ui = (uint)ui;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"ui = (uint)ui\"),\n // (27,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // l = (long)l;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"l = (long)l\"),\n // (28,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // ul = (ulong)ul;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"ul = (ulong)ul\"),\n // (29,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // f = (float)f; // Not reported by dev11.\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"f = (float)f\"),\n // (30,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // d = (double)d; // Not reported by dev11.\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"d = (double)d\"),\n // (31,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // m = (decimal)m;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"m = (decimal)m\"),\n // (32,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // bo = (bool)bo;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"bo = (bool)bo\"),\n // (33,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // o = (object)o;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"o = (object)o\"),\n // (34,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // cl = (C)cl;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"cl = (C)cl\"),\n // (35,9): warning CS1717: Assignment made to same variable; did you mean to assign something else?\n // st = (S)st;\n Diagnostic(ErrorCode.WRN_AssignmentToSelf, \"st = (S)st\"));\n }\n\n [Fact, WorkItem(546493, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546493\")]\n public void CS1718WRN_ComparisonToSelf()\n {\n var text = @\"\nclass Tester\n{\n static int j = 123;\n static void Main()\n {\n int i = 0;\n if (i == i) i++;\n if (j == Tester.j) j++;\n }\n}\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (8,13): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // if (i == i) i++;\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"i == i\"),\n // (9,13): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // if (j == Tester.j) j++;\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"j == Tester.j\"));\n }\n\n [Fact, WorkItem(580501, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580501\")]\n public void CS1718WRN_ComparisonToSelf2()\n {\n var text = @\"\nusing System.Linq;\nclass Tester\n{\n static void Main()\n {\n var q = from int x1 in new[] { 2, 9, 1, 8, }\n where x1 > x1 // CS1718\n select x1;\n }\n}\n\";\n\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (8,15): warning CS1718: Comparison made to same variable; did you mean to compare something else?\n // where x1 > x1 // CS1718\n Diagnostic(ErrorCode.WRN_ComparisonToSelf, \"x1 > x1\"));\n }\n\n [Fact]\n public void CS1720WRN_DotOnDefault01()\n {\n var source =\n@\"class A\n{\n internal object P { get; set; }\n}\ninterface I\n{\n object P { get; set; }\n}\nstatic class C\n{\n static void M()\n where T2 : new()\n where T3 : struct\n where T4 : class\n where T5 : T1\n where T6 : A\n where T7 : I\n {\n default(int).GetHashCode();\n default(object).GetHashCode();\n default(T1).GetHashCode();\n default(T2).GetHashCode();\n default(T3).GetHashCode();\n default(T4).GetHashCode();\n default(T5).GetHashCode();\n default(T6).GetHashCode();\n default(T7).GetHashCode();\n default(T6).P = null;\n default(T7).P = null;\n default(int).E();\n default(object).E();\n default(T1).E();\n default(T2).E();\n default(T3).E();\n default(T4).E();\n default(T5).E();\n default(T6).E(); // Dev10 (incorrectly) reports CS1720\n default(T7).E();\n }\n static void E(this object o) { }\n}\";\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (20,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object' is null\n // default(object).GetHashCode();\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(object).GetHashCode\").WithArguments(\"object\").WithLocation(20, 9),\n // (24,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null\n // default(T4).GetHashCode();\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T4).GetHashCode\").WithArguments(\"T4\").WithLocation(24, 9),\n // (26,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null\n // default(T6).GetHashCode();\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T6).GetHashCode\").WithArguments(\"T6\").WithLocation(26, 9),\n // (28,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null\n // default(T6).P = null;\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T6).P\").WithArguments(\"T6\").WithLocation(28, 9));\n CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, options: TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable)).VerifyDiagnostics(\n );\n }\n\n [Fact]\n public void CS1720WRN_DotOnDefault02()\n {\n var source =\n@\"class A\n{\n internal object this[object index] { get { return null; } set { } }\n}\nstruct S\n{\n internal object this[object index] { get { return null; } set { } }\n}\ninterface I\n{\n object this[object index] { get; set; }\n}\nclass C\n{\n unsafe static void M()\n where T1 : A\n where T2 : I\n where T3 : struct, I\n where T4 : class, I\n {\n object o;\n o = default(int*)[0];\n o = default(A)[0];\n o = default(S)[0];\n o = default(I)[0];\n o = default(object[])[0];\n o = default(T1)[0];\n o = default(T2)[0];\n o = default(T3)[0];\n o = default(T4)[0];\n default(int*)[1] = 1;\n default(A)[1] = o;\n default(I)[1] = o;\n default(object[])[1] = o;\n default(T1)[1] = o;\n default(T2)[1] = o;\n default(T3)[1] = o;\n default(T4)[1] = o;\n }\n}\";\n CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // (23,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(A)[0]\").WithArguments(\"A\").WithLocation(23, 13),\n // (25,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(I)[0]\").WithArguments(\"I\").WithLocation(25, 13),\n // (26,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(object[])[0]\").WithArguments(\"object[]\").WithLocation(26, 13),\n // (27,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T1)[0]\").WithArguments(\"T1\").WithLocation(27, 13),\n // (30,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T4)[0]\").WithArguments(\"T4\").WithLocation(30, 13),\n // (32,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(A)[1]\").WithArguments(\"A\").WithLocation(32, 9),\n // (33,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(I)[1]\").WithArguments(\"I\").WithLocation(33, 9),\n // (34,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(object[])[1]\").WithArguments(\"object[]\").WithLocation(34, 9),\n // (35,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T1)[1]\").WithArguments(\"T1\").WithLocation(35, 9),\n // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T3)[1]\").WithLocation(37, 9), // Incorrect? See CS0131ERR_AssgLvalueExpected03 unit test.\n // (38,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null\n Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(T4)[1]\").WithArguments(\"T4\").WithLocation(38, 9));\n CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer\n // default(T3)[1] = o;\n Diagnostic(ErrorCode.ERR_AssgLvalueExpected, \"default(T3)[1]\").WithLocation(37, 9));\n }\n\n [Fact]\n public void CS1720WRN_DotOnDefault03()\n {\n var source =\n@\"static class A\n{\n static void Main()\n {\n System.Console.WriteLine(default(string).IsNull());\n }\n\n internal static bool IsNull(this string val)\n {\n return (object)val == null; \n }\n}\n\";\n CompileAndVerifyWithMscorlib40(source, expectedOutput: \"True\", references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(\n // Do not report the following warning:\n // (5,34): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null\n // System.Console.WriteLine(default(string).IsNull());\n // Diagnostic(ErrorCode.WRN_DotOnDefault, \"default(string).IsNull\").WithArguments(\"string\").WithLocation(5, 34)\n );\n CompileAndVerifyWithMscorlib40(source, expectedOutput: \"True\", references: new[] { Net40.SystemCore }).VerifyDiagnostics();\n }\n\n [Fact]\n public void CS1723WRN_BadXMLRefTypeVar()\n {\n var text = @\"\n///A generic list class.\n/// // CS1723\npublic class List\n{\n}\n\";\n CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics(\n // (3,15): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter\n // /// // CS1723\n Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, \"T\").WithArguments(\"T\"));\n }\n\n [Fact]\n public void CS1974WRN_DynamicDispatchToConditionalMethod()\n {\n var text = @\"\nusing System.Diagnostics;\nclass Myclass\n{\n static void Main()\n {\n dynamic d = null;\n // Warning because Goo might be conditional.\n Goo(d); \n // No warning; only the two-parameter Bar is conditional.\n Bar(d);\n }\n\n [Conditional(\"\"DEBUG\"\")]\n static void Goo(string d) {}\n\n [Conditional(\"\"DEBUG\"\")]\n static void Bar(int x, int y) {}\n \n static void Bar(string x) {}\n}\";\n\n var comp = CreateCompilationWithMscorlib40AndSystemCore(text);\n comp.VerifyDiagnostics(\n// (9,9): warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime because one or more applicable overloads are conditional methods.\n// Goo(d); \nDiagnostic(ErrorCode.WRN_DynamicDispatchToConditionalMethod, \"Goo(d)\").WithArguments(\"Goo\"));\n }\n\n [Fact]\n public void CS1981WRN_IsDynamicIsConfusing()\n {\n var text = @\"\npublic class D : C { }\npublic class C\n{\n public static int Main()\n {\n // is dynamic\n bool bi = 123 is dynamic; \n // dynamicType is valueType\n dynamic i2 = 123;\n bi = i2 is int;\n // dynamicType is refType\n dynamic c = new D();\n bi = c is C;\n dynamic c2 = new C();\n bi = c is C;\n\n // valueType as dynamic\n int i = 123 as dynamic;\n // refType as dynamic\n dynamic c3 = new D() as dynamic;\n // dynamicType as dynamic\n dynamic s = \"\"asd\"\";\n string s2 = s as dynamic;\n // default(dynamic)\n dynamic d = default(dynamic); \n // dynamicType as valueType : generate error\n int k = i2 as int;\n // dynamicType as refType \n C c4 = c3 as C;\n\n return 0;\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (7,19): warning CS1981: Using 'is' to test compatibility with 'dynamic'\n // is essentially identical to testing compatibility with 'Object' and will\n // succeed for all non-null values\n Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, \"123 is dynamic\").WithArguments(\"is\", \"dynamic\", \"Object\"),\n // (7,19): warning CS0183: The given expression is always of the provided ('dynamic') type\n Diagnostic(ErrorCode.WRN_IsAlwaysTrue, \"123 is dynamic\").WithArguments(\"dynamic\"),\n // (27,17): error CS0077: The as operator must be used with a reference type\n // or nullable type ('int' is a non-nullable value type)\n Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, \"i2 as int\").WithArguments(\"int\"),\n // (26,17): warning CS0219: The variable 'd' is assigned but its value is never used\n Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, \"d\").WithArguments(\"d\"));\n }\n\n [Fact]\n public void CS7003ERR_UnexpectedUnboundGenericName()\n {\n var text = @\"\nclass C\n{\n void M(System.Type t)\n {\n M(typeof(C>)); //unbound inside bound\n M(typeof(C<>[])); //array of unbound\n M(typeof(C<>.D)); //unbound containing bound\n M(typeof(C.D<>)); //bound containing unbound\n M(typeof(D<,>[])); //multiple type parameters\n }\n\n class D { }\n}\n\nclass D {}\";\n\n // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new.\n CreateCompilation(text).VerifyDiagnostics(\n // (6,20): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"C<>\"),\n // (7,18): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"C<>\"),\n // (8,18): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"C<>\"),\n // (9,25): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"D<>\"),\n // (10,18): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"D<,>\"));\n }\n\n [Fact]\n public void CS7003ERR_UnexpectedUnboundGenericName_Nested()\n {\n var text = @\"\nclass Outer\n{\n public static void Print()\n {\n System.Console.WriteLine(typeof(Inner<>));\n System.Console.WriteLine(typeof(Inner));\n System.Console.WriteLine(typeof(Inner));\n\n System.Console.WriteLine(typeof(Outer<>.Inner<>));\n System.Console.WriteLine(typeof(Outer<>.Inner)); //CS7003\n System.Console.WriteLine(typeof(Outer<>.Inner)); //CS7003\n\n System.Console.WriteLine(typeof(Outer.Inner<>)); //CS7003\n System.Console.WriteLine(typeof(Outer.Inner));\n System.Console.WriteLine(typeof(Outer.Inner));\n\n System.Console.WriteLine(typeof(Outer.Inner<>)); //CS7003\n System.Console.WriteLine(typeof(Outer.Inner));\n System.Console.WriteLine(typeof(Outer.Inner));\n }\n\n class Inner { }\n}\";\n\n // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new.\n CreateCompilation(text).VerifyDiagnostics(\n // (11,41): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Outer<>\"),\n // (12,41): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Outer<>\"),\n // (14,50): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Inner<>\"),\n // (18,52): error CS7003: Unexpected use of an unbound generic name\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Inner<>\"));\n }\n\n [Fact(), WorkItem(529583, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529583\")]\n public void CS7003ERR_UnexpectedUnboundGenericName_Attributes()\n {\n var text = @\"\nusing System;\n\nclass Outer\n{\n public class Inner\n {\n\n }\n}\n\n[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]\nclass Attr : Attribute\n{\n public Attr(Type t)\n {\n }\n}\n\n[Attr(typeof(Outer<>.Inner<>))]\n[Attr(typeof(Outer.Inner<>))]\n[Attr(typeof(Outer<>.Inner))]\n[Attr(typeof(Outer.Inner))]\npublic class Test\n{\n public static void Main()\n {\n }\n}\";\n\n // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new.\n CreateCompilation(text).VerifyDiagnostics(\n // (21,25): error CS7003: Unexpected use of an unbound generic name\n // [Attr(typeof(Outer.Inner<>))]\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Inner<>\"),\n // (22,14): error CS7003: Unexpected use of an unbound generic name\n // [Attr(typeof(Outer<>.Inner))]\n Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, \"Outer<>\"));\n }\n\n [Fact]\n public void CS7013WRN_MetadataNameTooLong()\n {\n var text = @\"\nnamespace Namespace1.Namespace2\n{\n public interface I\n {\n void Goo();\n }\n\n public class OuterGenericClass\n {\n public class NestedClass : OuterGenericClass { }\n\n public class C : I\n {\n void I.Goo()\n {\n }\n }\n }\n}\n\";\n // This error will necessarily have a very long error string.\n CreateCompilation(text).VerifyEmitDiagnostics(\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, \"Goo\").WithArguments(\"Namespace1.Namespace2.I.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass,Namespace1.Namespace2.OuterGenericClass.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo\"));\n }\n\n #endregion\n\n #region shotgun tests\n\n [Fact]\n public void DelegateCreationBad()\n {\n var text = @\"\nnamespace CSSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n }\n\n delegate void D1();\n delegate void D2();\n\n delegate int D3(int x);\n\n static D1 d1;\n static D2 d2;\n static D3 d3;\n\n internal virtual void V() { }\n void M() { }\n static void S() { }\n\n static int M2(int x) { return x; }\n\n static void F(Program p)\n {\n // Error cases\n d1 = new D1(2 + 2);\n d1 = new D1(d3);\n d1 = new D1(2, 3);\n d1 = new D1(x: 3);\n d1 = new D1(M2);\n }\n }\n}\n\";\n var comp = CreateCompilation(text);\n comp.VerifyDiagnostics(\n // (28,25): error CS0149: Method name expected\n // d1 = new D1(2 + 2);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"2 + 2\").WithLocation(28, 25),\n // (29,18): error CS0123: No overload for 'Program.D3.Invoke(int)' matches delegate 'Program.D1'\n // d1 = new D1(d3);\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"new D1(d3)\").WithArguments(\"CSSample.Program.D3.Invoke(int)\", \"CSSample.Program.D1\").WithLocation(29, 18),\n // (30,25): error CS0149: Method name expected\n // d1 = new D1(2, 3);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"2, 3\").WithLocation(30, 25),\n // (31,28): error CS0149: Method name expected\n // d1 = new D1(x: 3);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"3\").WithLocation(31, 28),\n // (32,18): error CS0123: No overload for 'M2' matches delegate 'Program.D1'\n // d1 = new D1(M2);\n Diagnostic(ErrorCode.ERR_MethDelegateMismatch, \"new D1(M2)\").WithArguments(\"M2\", \"CSSample.Program.D1\").WithLocation(32, 18),\n // (16,19): warning CS0169: The field 'Program.d2' is never used\n // static D2 d2;\n Diagnostic(ErrorCode.WRN_UnreferencedField, \"d2\").WithArguments(\"CSSample.Program.d2\").WithLocation(16, 19),\n // (17,19): warning CS0649: Field 'Program.d3' is never assigned to, and will always have its default value null\n // static D3 d3;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"d3\").WithArguments(\"CSSample.Program.d3\", \"null\").WithLocation(17, 19));\n }\n\n [Fact, WorkItem(7359, \"https://github.com/dotnet/roslyn/issues/7359\")]\n public void DelegateCreationWithRefOut()\n {\n var source = @\"\nusing System;\npublic class Program\n{\n static Func Goo(Func t) { return t; }\n static Func Bar = Goo(x => x);\n static Func BarP => Goo(x => x);\n static T Id(T id) => id;\n\n static void Test(Func Baz)\n {\n var k = Bar;\n var z1 = new Func(ref Bar); // compat\n var z2 = new Func(ref Baz); // compat\n var z3 = new Func(ref k); // compat\n var z4 = new Func(ref x => x);\n var z5 = new Func(ref Goo(x => x));\n var z6 = new Func(ref BarP); \n var z7 = new Func(ref new Func(x => x));\n var z8 = new Func(ref Program.BarP); \n var z9 = new Func(ref Program.Goo(x => x));\n var z10 = new Func(ref Id); // compat\n var z11 = new Func(ref new(x => x));\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (16,47): error CS1510: A ref or out argument must be an assignable variable\n // var z4 = new Func(ref x => x);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x\").WithLocation(16, 47),\n // (17,47): error CS1510: A ref or out argument must be an assignable variable\n // var z5 = new Func(ref Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Goo(x => x)\").WithLocation(17, 47),\n // (18,43): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z6 = new Func(ref BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"ref BarP\").WithArguments(\"Program.BarP\").WithLocation(18, 43),\n // (19,47): error CS1510: A ref or out argument must be an assignable variable\n // var z7 = new Func(ref new Func(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new Func(x => x)\").WithLocation(19, 47),\n // (20,43): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z8 = new Func(ref Program.BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"ref Program.BarP\").WithArguments(\"Program.BarP\").WithLocation(20, 43),\n // (21,47): error CS1510: A ref or out argument must be an assignable variable\n // var z9 = new Func(ref Program.Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Program.Goo(x => x)\").WithLocation(21, 47),\n // (23,48): error CS1510: A ref or out value must be an assignable variable\n // var z11 = new Func(ref new(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new(x => x)\").WithLocation(23, 48)\n );\n\n CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (13,47): error CS0149: Method name expected\n // var z1 = new Func(ref Bar); // compat\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(13, 47),\n // (14,47): error CS0149: Method name expected\n // var z2 = new Func(ref Baz); // compat\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(14, 47),\n // (15,47): error CS0149: Method name expected\n // var z3 = new Func(ref k); // compat\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(15, 47),\n // (16,47): error CS1510: A ref or out argument must be an assignable variable\n // var z4 = new Func(ref x => x);\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"x => x\").WithLocation(16, 47),\n // (17,47): error CS1510: A ref or out argument must be an assignable variable\n // var z5 = new Func(ref Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Goo(x => x)\").WithLocation(17, 47),\n // (18,47): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z6 = new Func(ref BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"BarP\").WithArguments(\"Program.BarP\").WithLocation(18, 47),\n // (19,47): error CS1510: A ref or out argument must be an assignable variable\n // var z7 = new Func(ref new Func(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new Func(x => x)\").WithLocation(19, 47),\n // (20,47): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var z8 = new Func(ref Program.BarP); \n Diagnostic(ErrorCode.ERR_RefProperty, \"Program.BarP\").WithArguments(\"Program.BarP\").WithLocation(20, 47),\n // (21,47): error CS1510: A ref or out argument must be an assignable variable\n // var z9 = new Func(ref Program.Goo(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"Program.Goo(x => x)\").WithLocation(21, 47),\n // (22,48): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z10 = new Func(ref Id); // compat\n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(22, 48),\n // (23,48): error CS1510: A ref or out value must be an assignable variable\n // var z11 = new Func(ref new(x => x));\n Diagnostic(ErrorCode.ERR_RefLvalueExpected, \"new(x => x)\").WithLocation(23, 48)\n );\n }\n\n [Fact, WorkItem(7359, \"https://github.com/dotnet/roslyn/issues/7359\")]\n public void DelegateCreationWithRefOut_Parens()\n {\n // these are allowed in compat mode without the parenthesis\n // with parenthesis, it behaves like strict mode\n var source = @\"\nusing System;\npublic class Program\n{\n static Func Goo(Func t) { return t; }\n static Func Bar = Goo(x => x);\n\n static T Id(T id) => id;\n\n static void Test(Func Baz)\n {\n var k = Bar;\n var z1 = new Func(ref (Bar)); \n var z2 = new Func(ref (Baz)); \n var z3 = new Func(ref (k)); \n var z10 = new Func(ref (Id)); \n // these all are still valid for compat mode, no errors should be reported for compat mode\n var z4 = new Func(ref Bar); \n var z5 = new Func(ref Baz); \n var z6 = new Func(ref k); \n var z7 = new Func(ref Id); \n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (13,48): error CS0149: Method name expected\n // var z1 = new Func(ref (Bar)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(13, 48),\n // (14,48): error CS0149: Method name expected\n // var z2 = new Func(ref (Baz)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(14, 48),\n // (15,48): error CS0149: Method name expected\n // var z3 = new Func(ref (k)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(15, 48),\n // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z10 = new Func(ref (Id)); \n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(16, 49));\n\n CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(\n // (13,48): error CS0149: Method name expected\n // var z1 = new Func(ref (Bar)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(13, 48),\n // (14,48): error CS0149: Method name expected\n // var z2 = new Func(ref (Baz)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(14, 48),\n // (15,48): error CS0149: Method name expected\n // var z3 = new Func(ref (k)); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(15, 48),\n // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z10 = new Func(ref (Id)); \n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(16, 49),\n // (18,47): error CS0149: Method name expected\n // var z4 = new Func(ref Bar); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Bar\").WithLocation(18, 47),\n // (19,47): error CS0149: Method name expected\n // var z5 = new Func(ref Baz); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz\").WithLocation(19, 47),\n // (20,47): error CS0149: Method name expected\n // var z6 = new Func(ref k); \n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"k\").WithLocation(20, 47),\n // (21,47): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group'\n // var z7 = new Func(ref Id); \n Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, \"Id\").WithArguments(\"Id\", \"method group\").WithLocation(21, 47));\n }\n\n [Fact, WorkItem(7359, \"https://github.com/dotnet/roslyn/issues/7359\")]\n public void DelegateCreationWithRefOut_MultipleArgs()\n {\n var source = @\"\nusing System;\npublic class Program\n{\n static Func BarP => null;\n static void Test(Func Baz)\n {\n var a = new Func(ref Baz, Baz.Invoke);\n var b = new Func(Baz, ref Baz.Invoke);\n var c = new Func(ref Baz, ref Baz.Invoke);\n var d = new Func(ref BarP, BarP.Invoke);\n var e = new Func(BarP, ref BarP.Invoke);\n var f = new Func(ref BarP, ref BarP.Invoke);\n }\n}\";\n CreateCompilation(source).VerifyDiagnostics(\n // (8,46): error CS0149: Method name expected\n // var a = new Func(ref Baz, Baz.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz, Baz.Invoke\").WithLocation(8, 46),\n // (9,42): error CS0149: Method name expected\n // var b = new Func(Baz, ref Baz.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz, ref Baz.Invoke\").WithLocation(9, 42),\n // (10,46): error CS0149: Method name expected\n // var c = new Func(ref Baz, ref Baz.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"Baz, ref Baz.Invoke\").WithLocation(10, 46),\n // (11,42): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var d = new Func(ref BarP, BarP.Invoke);\n Diagnostic(ErrorCode.ERR_RefProperty, \"ref BarP\").WithArguments(\"Program.BarP\").WithLocation(11, 42),\n // (11,46): error CS0149: Method name expected\n // var d = new Func(ref BarP, BarP.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"BarP, BarP.Invoke\").WithLocation(11, 46),\n // (12,42): error CS0149: Method name expected\n // var e = new Func(BarP, ref BarP.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"BarP, ref BarP.Invoke\").WithLocation(12, 42),\n // (13,42): error CS0206: A property or indexer may not be passed as an out or ref parameter\n // var f = new Func(ref BarP, ref BarP.Invoke);\n Diagnostic(ErrorCode.ERR_RefProperty, \"ref BarP\").WithArguments(\"Program.BarP\").WithLocation(13, 42),\n // (13,46): error CS0149: Method name expected\n // var f = new Func(ref BarP, ref BarP.Invoke);\n Diagnostic(ErrorCode.ERR_MethodNameExpected, \"BarP, ref BarP.Invoke\").WithLocation(13, 46)\n );\n }\n\n [WorkItem(538430, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538430\")]\n [Fact]\n public void NestedGenericAccessibility()\n {\n var text = @\"\npublic class C\n{\n}\npublic class E\n{\n class D : C\n {\n }\n}\n\";\n DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] {\n });\n }\n\n [WorkItem(542419, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419\")]\n [Fact]\n public void EmptyAngleBrackets()\n {\n var text = @\"\nclass Program\n{\n int f;\n int P { get; set; }\n int M() { return 0; }\n interface I { }\n class C { }\n struct S { }\n delegate void D();\n\n void Test(object p)\n {\n int l = 0;\n\n Test(l<>);\n Test(p<>);\n\n Test(f<>);\n Test(P<>);\n Test(M<>());\n\n Test(this.f<>);\n Test(this.P<>);\n Test(this.M<>());\n\n System.Func m;\n \n m = M<>;\n m = this.M<>;\n\n I<> i1 = null;\n C<> c1 = new C();\n C c2 = new C<>();\n S<> s1 = new S();\n S s2 = new S<>();\n D<> d1 = null;\n\n Program.I<> i2 = null;\n Program.C<> c3 = new Program.C();\n Program.C c4 = new Program.C<>();\n Program.S<> s3 = new Program.S();\n Program.S s4 = new Program.S<>();\n Program.D<> d2 = null;\n\n Test(default(I<>));\n Test(default(C<>));\n Test(default(S<>));\n\n Test(default(Program.I<>));\n Test(default(Program.C<>));\n Test(default(Program.S<>));\n\n string s;\n\n s = typeof(I<>).Name;\n s = typeof(C<>).Name;\n s = typeof(S<>).Name;\n \n s = typeof(Program.I<>).Name;\n s = typeof(Program.C<>).Name;\n s = typeof(Program.S<>).Name;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (16,14): error CS0307: The variable 'l' cannot be used with type arguments\n // Test(l<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"l<>\").WithArguments(\"l\", \"variable\").WithLocation(16, 14),\n // (17,14): error CS0307: The variable 'object' cannot be used with type arguments\n // Test(p<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"p<>\").WithArguments(\"object\", \"variable\").WithLocation(17, 14),\n // (19,14): error CS0307: The field 'Program.f' cannot be used with type arguments\n // Test(f<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"f<>\").WithArguments(\"Program.f\", \"field\").WithLocation(19, 14),\n // (20,14): error CS0307: The property 'Program.P' cannot be used with type arguments\n // Test(P<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"P<>\").WithArguments(\"Program.P\", \"property\").WithLocation(20, 14),\n // (21,14): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // Test(M<>());\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(21, 14),\n // (23,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.f<>);\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.f<>\").WithLocation(23, 14),\n // (23,19): error CS0307: The field 'Program.f' cannot be used with type arguments\n // Test(this.f<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"f<>\").WithArguments(\"Program.f\", \"field\").WithLocation(23, 19),\n // (24,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.P<>);\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.P<>\").WithLocation(24, 14),\n // (24,19): error CS0307: The property 'Program.P' cannot be used with type arguments\n // Test(this.P<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"P<>\").WithArguments(\"Program.P\", \"property\").WithLocation(24, 19),\n // (25,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.M<>());\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.M<>\").WithLocation(25, 14),\n // (25,19): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // Test(this.M<>());\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(25, 19),\n // (29,13): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // m = M<>;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(29, 13),\n // (30,13): error CS8389: Omitting the type argument is not allowed in the current context\n // m = this.M<>;\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.M<>\").WithLocation(30, 13),\n // (30,18): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments\n // m = this.M<>;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"M<>\").WithArguments(\"Program.M()\", \"method\").WithLocation(30, 18),\n // (32,9): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // I<> i1 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(32, 9),\n // (33,9): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // C<> c1 = new C();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(33, 9),\n // (34,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // C c2 = new C<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(34, 20),\n // (35,9): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // S<> s1 = new S();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(35, 9),\n // (36,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // S s2 = new S<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(36, 20),\n // (37,9): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments\n // D<> d1 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"D<>\").WithArguments(\"Program.D\", \"type\").WithLocation(37, 9),\n // (39,17): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // Program.I<> i2 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(39, 17),\n // (40,17): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Program.C<> c3 = new Program.C();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(40, 17),\n // (41,36): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Program.C c4 = new Program.C<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(41, 36),\n // (42,17): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Program.S<> s3 = new Program.S();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(42, 17),\n // (43,36): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Program.S s4 = new Program.S<>();\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(43, 36),\n // (44,17): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments\n // Program.D<> d2 = null;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"D<>\").WithArguments(\"Program.D\", \"type\").WithLocation(44, 17),\n // (46,22): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // Test(default(I<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(46, 22),\n // (47,22): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Test(default(C<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(47, 22),\n // (48,22): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Test(default(S<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(48, 22),\n // (50,30): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // Test(default(Program.I<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(50, 30),\n // (51,30): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // Test(default(Program.C<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(51, 30),\n // (52,30): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // Test(default(Program.S<>));\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(52, 30),\n // (56,20): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // s = typeof(I<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(56, 20),\n // (57,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // s = typeof(C<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(57, 20),\n // (58,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // s = typeof(S<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(58, 20),\n // (60,28): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments\n // s = typeof(Program.I<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"I<>\").WithArguments(\"Program.I\", \"type\").WithLocation(60, 28),\n // (61,28): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments\n // s = typeof(Program.C<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"C<>\").WithArguments(\"Program.C\", \"type\").WithLocation(61, 28),\n // (62,28): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments\n // s = typeof(Program.S<>).Name;\n Diagnostic(ErrorCode.ERR_HasNoTypeVars, \"S<>\").WithArguments(\"Program.S\", \"type\").WithLocation(62, 28),\n // (4,9): warning CS0649: Field 'Program.f' is never assigned to, and will always have its default value 0\n // int f;\n Diagnostic(ErrorCode.WRN_UnassignedInternalField, \"f\").WithArguments(\"Program.f\", \"0\").WithLocation(4, 9)\n );\n }\n\n [WorkItem(542419, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419\")]\n [Fact]\n public void EmptyAngleBrackets_Events()\n {\n var text = @\"\nclass Program\n{\n event System.Action E;\n event System.Action F { add { } remove { } }\n\n void Test(T p)\n {\n Test(E<>);\n Test(this.E<>);\n\n E<> += null; //parse error\n F<> += null; //parse error\n\n this.E<> += null; //parse error\n this.F<> += null; //parse error\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // Parser\n\n // (12,11): error CS1525: Invalid expression term '>'\n // E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(12, 11),\n // (12,13): error CS1525: Invalid expression term '+='\n // E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(12, 13),\n // (13,11): error CS1525: Invalid expression term '>'\n // F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(13, 11),\n // (13,13): error CS1525: Invalid expression term '+='\n // F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(13, 13),\n // (15,16): error CS1525: Invalid expression term '>'\n // this.E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(15, 16),\n // (15,18): error CS1525: Invalid expression term '+='\n // this.E<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(15, 18),\n // (16,16): error CS1525: Invalid expression term '>'\n // this.F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \">\").WithArguments(\">\").WithLocation(16, 16),\n // (16,18): error CS1525: Invalid expression term '+='\n // this.F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_InvalidExprTerm, \"+=\").WithArguments(\"+=\").WithLocation(16, 18),\n\n // Binder\n\n // (9,14): error CS0307: The event 'Program.E' cannot be used with type arguments\n // Test(E<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"E<>\").WithArguments(\"Program.E\", \"event\").WithLocation(9, 14),\n // (10,14): error CS8389: Omitting the type argument is not allowed in the current context\n // Test(this.E<>);\n Diagnostic(ErrorCode.ERR_OmittedTypeArgument, \"this.E<>\").WithLocation(10, 14),\n // (10,19): error CS0307: The event 'Program.E' cannot be used with type arguments\n // Test(this.E<>);\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"E<>\").WithArguments(\"Program.E\", \"event\").WithLocation(10, 19),\n // (13,9): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -=\n // F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_BadEventUsageNoField, \"F\").WithArguments(\"Program.F\").WithLocation(13, 9),\n // (16,14): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -=\n // this.F<> += null; //parse error\n Diagnostic(ErrorCode.ERR_BadEventUsageNoField, \"F\").WithArguments(\"Program.F\").WithLocation(16, 14));\n }\n\n [WorkItem(542419, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419\")]\n [WorkItem(542679, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542679\")]\n [Fact]\n public void EmptyAngleBrackets_TypeParameters()\n {\n var text = @\"\nclass Program\n{\n void Test(T p)\n {\n Test(default(T<>));\n string s = typeof(T<>).Name;\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6, 24): error CS0307: The type parameter 'T' cannot be used with type arguments\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"T<>\").WithArguments(\"T\", \"type parameter\"),\n // (7,27): error CS0307: The type parameter 'T' cannot be used with type arguments\n Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, \"T<>\").WithArguments(\"T\", \"type parameter\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_TypeWithCorrectArity()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n C<>.M();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0305: Using the generic type 'C' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"C<>\").WithArguments(\"C\", \"type\", \"1\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_MethodWithCorrectArity()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n M<>();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"M<>\").WithArguments(\"M\", \"method group\", \"1\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_QualifiedTypeWithCorrectArity()\n {\n var text = @\"\nclass A\n{\n class C\n {\n static void M()\n {\n A.C<>.M();\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (8,15): error CS0305: Using the generic type 'A.C' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"C<>\").WithArguments(\"A.C\", \"type\", \"1\"));\n }\n\n [Fact, WorkItem(542796, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796\")]\n public void EmptyAngleBrackets_QualifiedMethodWithCorrectArity()\n {\n var text = @\"\nclass C\n{\n static void M()\n {\n C.M<>();\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments\n Diagnostic(ErrorCode.ERR_BadArity, \"C.M<>\").WithArguments(\"M\", \"method group\", \"1\"));\n }\n\n [Fact]\n public void NamesTooLong()\n {\n var longE = new String('e', 1024);\n\n var builder = new System.Text.StringBuilder();\n\n builder.Append(@\"\nclass C\n{\n\");\n builder.AppendFormat(\"int {0}1;\\n\", longE);\n builder.AppendFormat(\"event System.Action {0}2;\\n\", longE);\n builder.AppendFormat(\"public void {0}3() {{ }}\\n\", longE);\n builder.AppendFormat(\"public void goo(int {0}4) {{ }}\\n\", longE);\n builder.AppendFormat(\"public string {0}5 {{ get; set; }}\\n\", longE);\n\n builder.AppendLine(@\"\n}\n\");\n CreateCompilation(builder.ToString(), null, TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)).VerifyEmitDiagnostics(\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //event\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //backing field\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(\"add_\" + longE + 2), //accessor\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(\"remove_\" + longE + 2), //accessor\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 3).WithArguments(longE + 3),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 4).WithArguments(longE + 4),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(longE + 5),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(\"<\" + longE + 5 + \">k__BackingField\"),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, \"get\").WithArguments(\"get_\" + longE + 5),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, \"set\").WithArguments(\"set_\" + longE + 5),\n Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 1).WithArguments(longE + 1)\n );\n }\n #endregion\n\n #region regression tests\n\n [WorkItem(541605, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541605\")]\n [Fact]\n public void CS0019ERR_ImplicitlyTypedVariableAssignedNullCoalesceExpr()\n {\n CreateCompilation(@\"\nclass Test\n{\n public static void Main()\n {\n var p = null ?? null; //CS0019\n }\n}\n\").VerifyDiagnostics(\n // error CS0019: Operator '??' cannot be applied to operands of type '' and ''\n Diagnostic(ErrorCode.ERR_BadBinaryOps, \"null ?? null\").WithArguments(\"??\", \"\", \"\"));\n }\n\n [WorkItem(528577, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528577\")]\n [Fact(Skip = \"528577\")]\n public void CS0122ERR_InaccessibleGenericType()\n {\n CreateCompilation(@\"\npublic class Top\n{\n class Outer\n {\n }\n}\n\npublic class MyClass\n{\n public static void Main()\n {\n var test = new Top.Outer();\n }\n}\n\").VerifyDiagnostics(\n // (13,33): error CS0122: 'Top.Outer' is inaccessible due to its protection level\n // var test = new Top.Outer();\n Diagnostic(ErrorCode.ERR_BadAccess, \"new Top.Outer()\").WithArguments(\"Top.Outer\"));\n }\n\n [WorkItem(528591, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528591\")]\n [Fact]\n public void CS0121ERR_IncorrectErrorSpan1()\n {\n CreateCompilation(@\"\nclass Test\n{\n public static void Method1(int a, long b)\n {\n }\n\n public static void Method1(long a, int b)\n {\n }\n\n public static void Main()\n {\n Method1(10, 20); //CS0121\n }\n}\n\").VerifyDiagnostics(\n // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Method1(int, long)' and 'Test.Method1(long, int)'\n // Method1(10, 20)\n Diagnostic(ErrorCode.ERR_AmbigCall, \"Method1\").WithArguments(\"Test.Method1(int, long)\", \"Test.Method1(long, int)\"));\n }\n\n [WorkItem(528592, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528592\")]\n [Fact]\n public void CS0121ERR_IncorrectErrorSpan2()\n {\n CreateCompilation(@\"\npublic class Class1\n{\n public Class1(int a, long b)\n {\n }\n\n public Class1(long a, int b)\n {\n }\n}\n\nclass Test\n{\n public static void Main()\n {\n var i1 = new Class1(10, 20); //CS0121\n }\n}\n\").VerifyDiagnostics(\n // (17,18): error CS0121: The call is ambiguous between the following methods or properties: 'Class1.Class1(int, long)' and 'Class1.Class1(long, int)'\n // new Class1(10, 20)\n Diagnostic(ErrorCode.ERR_AmbigCall, \"Class1\").WithArguments(\"Class1.Class1(int, long)\", \"Class1.Class1(long, int)\"));\n }\n\n [WorkItem(542468, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542468\")]\n [Fact]\n public void CS1513ERR_RbraceExpected_DevDiv9741()\n {\n var text = @\"\nclass Program\n{\n private delegate string D();\n static void Main(string[] args)\n {\n D d = delegate\n {\n .ToString();\n };\n }\n} \n\";\n // Used to assert.\n CreateCompilation(text).VerifyDiagnostics(\n // (8,10): error CS1513: } expected\n // {\n Diagnostic(ErrorCode.ERR_RbraceExpected, \"\").WithLocation(8, 10),\n // (9,14): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()'\n // .ToString();\n Diagnostic(ErrorCode.ERR_ObjectRequired, \"ToString\").WithArguments(\"object.ToString()\").WithLocation(9, 14),\n // (7,15): error CS1643: Not all code paths return a value in anonymous method of type 'Program.D'\n // D d = delegate\n Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, \"delegate\").WithArguments(\"anonymous method\", \"Program.D\").WithLocation(7, 15)\n );\n }\n\n [WorkItem(543473, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543473\")]\n [Fact]\n public void CS0815ERR_CannotAssignLambdaExpressionToAnImplicitlyTypedLocalVariable()\n {\n var text =\n@\"class Program\n{\n static void Main(string[] args)\n {\n var a1 = checked((a) => a);\n }\n}\";\n\n CreateCompilation(text).VerifyDiagnostics(\n // (5,26): error CS8917: The delegate type could not be inferred.\n // var a1 = checked((a) => a);\n Diagnostic(ErrorCode.ERR_CannotInferDelegateType, \"(a) => a\").WithLocation(5, 26));\n }\n\n [Fact, WorkItem(543665, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543665\")]\n public void CS0246ERR_SingleTypeNameNotFound_UndefinedTypeInDelegateSignature()\n {\n var text = @\"\nusing System;\nclass Test\n{\n static void Main()\n {\n var d = (Action>)delegate(List t) {};\n }\n}\";\n CreateCompilation(text).VerifyDiagnostics(\n // (7,41): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?)\n // var d = (Action>)delegate(List t) {};\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"List\").WithArguments(\"List<>\").WithLocation(7, 41),\n // (7,21): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?)\n // var d = (Action>)delegate(List t) {};\n Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, \"List\").WithArguments(\"List<>\").WithLocation(7, 21)\n );\n }\n\n [Fact]\n [WorkItem(633183, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183\")]\n public void CS0199ERR_RefReadonlyStatic_StaticFieldInitializer()\n {\n var source = @\"\nclass Program\n{\n Program(ref string s) { }\n static readonly Program Field1 = new Program(ref Program.Field2);\n static readonly string Field2 = \"\"\"\";\n static void Main() { }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics();\n }\n\n [Fact]\n [WorkItem(633183, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183\")]\n public void CS0199ERR_RefReadonlyStatic_NestedStaticFieldInitializer()\n {\n var source = @\"\nclass Program\n{\n Program(ref string s) { }\n static readonly Program Field1 = new Program(ref Program.Field2);\n static readonly string Field2 = \"\"\"\";\n static void Main() { }\n\n class Inner\n {\n static readonly Program Field3 = new Program(ref Program.Field2);\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (11,58): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor)\n // static readonly Program Field3 = new Program(ref Program.Field2);\n Diagnostic(ErrorCode.ERR_RefReadonlyStatic, \"Program.Field2\").WithLocation(11, 58)\n);\n }\n\n [Fact]\n public void BadYield_MultipleReasons()\n {\n var source = @\"\nusing System.Collections.Generic;\n\nclass Program\n{\n IEnumerable Test()\n {\n try\n {\n try\n {\n yield return 11; // CS1626\n }\n catch\n {\n yield return 12; // CS1626\n }\n finally\n {\n yield return 13; // CS1625\n }\n }\n catch\n {\n try\n {\n yield return 21; // CS1626\n }\n catch\n {\n yield return 22; // CS1631\n }\n finally\n {\n yield return 23; // CS1625\n }\n }\n finally\n {\n try\n {\n yield return 31; // CS1625\n }\n catch\n {\n yield return 32; // CS1625\n }\n finally\n {\n yield return 33; // CS1625\n }\n }\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (12,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return 11; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\"),\n // (16,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return 12; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\"),\n // (20,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 13; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n\n // (27,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause\n // yield return 21; // CS1626\n Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, \"yield\"),\n // (31,17): error CS1631: Cannot yield a value in the body of a catch clause\n // yield return 22; // CS1631\n Diagnostic(ErrorCode.ERR_BadYieldInCatch, \"yield\"),\n // (35,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 23; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n\n // (42,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 31; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n // (46,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 32; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n // (50,17): error CS1625: Cannot yield in the body of a finally clause\n // yield return 33; // CS1625\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"));\n }\n\n [Fact]\n public void BadYield_Lambda()\n {\n var source = @\"\nusing System;\nusing System.Collections.Generic;\n\nclass Program\n{\n IEnumerable Test()\n {\n try\n {\n }\n finally\n {\n Action a = () => { yield break; };\n Action b = () =>\n {\n try\n {\n }\n finally\n {\n yield break;\n }\n };\n }\n\n yield break;\n }\n}\n\";\n\n CreateCompilation(source).VerifyDiagnostics(\n // (14,32): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression\n // Action a = () => { yield break; };\n Diagnostic(ErrorCode.ERR_YieldInAnonMeth, \"yield\"),\n\n // CONSIDER: ERR_BadYieldInFinally is redundant, but matches dev11.\n\n // (22,21): error CS1625: Cannot yield in the body of a finally clause\n // yield break;\n Diagnostic(ErrorCode.ERR_BadYieldInFinally, \"yield\"),\n // (22,21): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression\n // yield break;\n Diagnostic(ErrorCode.ERR_YieldInAnonMeth, \"yield\"));\n }\n\n #endregion\n\n [Fact]\n public void Bug528147()\n {\n var text = @\"\nusing System;\n \ninterface I { }\n \nclass A\n{\n private class B { }\n public class C : I\n {\n }\n}\n \nclass Program\n{\n delegate void D(A.C x);\n \n static void M(I c)\n {\n Console.WriteLine(\"\"I\"\");\n }\n\n static void Main()\n {\n D d = M;\n d(null);\n }\n}\n\";\n\n CreateCompilation(text).VerifyDiagnostics(\n// (25,15): error CS0122: 'Program.M(I)' is inaccessible due to its protection level\n// D d = M;\nDiagnostic(ErrorCode.ERR_BadAccess, \"M\").WithArguments(\"Program.M(I)\")\n );\n }\n\n [WorkItem(630799, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630799\")]\n [Fact]\n public void Bug630799()\n {\n var text = @\"\nusing System;\n \nclass Program\n{\n static void Goo() where T : S where S : Exception\n {\n try\n {\n }\n catch(S e)\n {\n }\n catch(T e)\n {\n }\n }\n}\n\";\n CreateCompilation(text).VerifyDiagnostics(\n // (14,15): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('S')\n // catch(T e)\n Diagnostic(ErrorCode.ERR_UnreachableCatch, \"T\").WithArguments(\"S\").WithLocation(14, 15),\n // (11,17): warning CS0168: The variable 'e' is declared but never used\n // catch(S e)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(11, 17),\n // (14,17): warning CS0168: The variable 'e' is declared but never used\n // catch(T e)\n Diagnostic(ErrorCode.WRN_UnreferencedVar, \"e\").WithArguments(\"e\").WithLocation(14, 17)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccess001()\n {\n var text = @\"\nclass Program\n{\n public int P1\n {\n set { }\n }\n\n public void V() { }\n\n static void Main(string[] args)\n {\n var x = 123 ?.ToString();\n\n var p = new Program();\n var x1 = p.P1 ?.ToString();\n var x2 = p.V() ?.ToString();\n var x3 = p.V ?.ToString();\n var x4 = ()=> { return 1; } ?.ToString();\n }\n}\n\";\n CreateCompilationWithMscorlib45(text).VerifyDiagnostics(\n // (13,21): error CS0023: Operator '?' cannot be applied to operand of type 'int'\n // var x = 123 ?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"int\").WithLocation(13, 21),\n // (16,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor\n // var x1 = p.P1 ?.ToString();\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"p.P1\").WithArguments(\"Program.P1\").WithLocation(16, 18),\n // (17,24): error CS0023: Operator '?' cannot be applied to operand of type 'void'\n // var x2 = p.V() ?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"void\").WithLocation(17, 24),\n // (18,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context\n // var x3 = p.V ?.ToString();\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"V\").WithArguments(\"Program.V()\", \"method\").WithLocation(18, 20),\n // (19,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression'\n // var x4 = ()=> { return 1; } ?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"()=> { return 1; } ?.ToString()\").WithArguments(\"?\", \"lambda expression\").WithLocation(19, 18)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccess002_notIn5()\n {\n var text = @\"\nclass Program\n{\n public int? P1\n {\n get { return null; }\n } \n\n public void V() { }\n\n static void Main(string[] args)\n {\n var p = new Program();\n var x1 = p.P1 ?.ToString;\n }\n}\n\";\n CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics(\n // (14,18): error CS8026: Feature 'null propagation operator' is not available in C# 5. Please use language version 6 or greater.\n // var x1 = p.P1 ?.ToString;\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, \"p.P1 ?.ToString\").WithArguments(\"null propagating operator\", \"6\").WithLocation(14, 18),\n // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group'\n // var x1 = p.P1 ?.ToString;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"method group\").WithLocation(14, 23)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccess002()\n {\n var text = @\"\nclass Program\n{\n public int? P1\n {\n get { return null; }\n } \n\n public void V() { }\n\n static void Main(string[] args)\n {\n var p = new Program();\n var x1 = p.P1 ?.ToString;\n }\n}\n\";\n CreateCompilationWithMscorlib45(text).VerifyDiagnostics(\n // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group'\n // var x1 = p.P1 ?.ToString;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"method group\").WithLocation(14, 23)\n );\n }\n\n\n [Fact]\n [CompilerTrait(CompilerFeature.IOperation)]\n [WorkItem(23009, \"https://github.com/dotnet/roslyn/issues/23009\")]\n public void ConditionalElementAccess001()\n {\n var text = @\"\nclass Program\n{\n public int P1\n {\n set { }\n }\n\n public void V() \n { \n var x6 = base?.ToString();\n }\n\n static void Main(string[] args)\n {\n var x = 123 ?[1,2];\n\n var p = new Program();\n var x1 = p.P1 ?[1,2];\n var x2 = p.V() ?[1,2];\n var x3 = p.V ?[1,2];\n var x4 = ()=> { return 1; } ?[1,2];\n\n var x5 = null?.ToString();\n }\n}\n\";\n var compilation = CreateCompilationWithMscorlib45(text).VerifyDiagnostics(\n // (11,18): error CS0175: Use of keyword 'base' is not valid in this context\n // var x6 = base?.ToString();\n Diagnostic(ErrorCode.ERR_BaseIllegal, \"base\").WithLocation(11, 18),\n // (16,21): error CS0023: Operator '?' cannot be applied to operand of type 'int'\n // var x = 123 ?[1,2];\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"int\").WithLocation(16, 21),\n // (19,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor\n // var x1 = p.P1 ?[1,2];\n Diagnostic(ErrorCode.ERR_PropertyLacksGet, \"p.P1\").WithArguments(\"Program.P1\").WithLocation(19, 18),\n // (20,24): error CS0023: Operator '?' cannot be applied to operand of type 'void'\n // var x2 = p.V() ?[1,2];\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"void\").WithLocation(20, 24),\n // (21,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context\n // var x3 = p.V ?[1,2];\n Diagnostic(ErrorCode.ERR_BadSKunknown, \"V\").WithArguments(\"Program.V()\", \"method\").WithLocation(21, 20),\n // (22,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression'\n // var x4 = ()=> { return 1; } ?[1,2];\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"()=> { return 1; } ?[1,2]\").WithArguments(\"?\", \"lambda expression\").WithLocation(22, 18),\n // (24,22): error CS0023: Operator '?' cannot be applied to operand of type ''\n // var x5 = null?.ToString();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"\").WithLocation(24, 22)\n );\n var tree = compilation.SyntaxTrees.Single();\n var node = tree.GetRoot().DescendantNodes().OfType().First();\n\n Assert.Equal(\"base?.ToString()\", node.ToString());\n\n compilation.VerifyOperationTree(node, expectedOperationTree:\n@\"\nIConditionalAccessOperation (OperationKind.ConditionalAccess, Type: ?, IsInvalid) (Syntax: 'base?.ToString()')\n Operation: \n IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base')\n WhenNotNull: \n IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')\n Instance Receiver: \n IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base')\n Arguments(0)\n\");\n }\n\n [Fact]\n [WorkItem(976765, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765\")]\n public void ConditionalMemberAccessPtr()\n {\n var text = @\"\nusing System;\n \nclass Program\n{\n unsafe static void Main()\n {\n IntPtr? intPtr = null;\n var p = intPtr?.ToPointer();\n }\n}\n\n\";\n CreateCompilationWithMscorlib45(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(\n // (9,23): error CS0023: Operator '?' cannot be applied to operand of type 'void*'\n // var p = intPtr?.ToPointer();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"void*\").WithLocation(9, 23)\n );\n }\n\n [Fact]\n [WorkItem(991490, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991490\")]\n public void ConditionalMemberAccessExprLambda()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nclass Program\n{\n static void M(T x)\n {\n Expression> s = () => x?.ToString();\n Expression> c = () => x.ToString()?[0];\n Expression> c1 = () => x.ToString()?.Length;\n\n Expression> c2 = () => x?.ToString()?.Length;\n}\n\n static void Main()\n {\n M((string)null);\n }\n}\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (9,44): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> s = () => x?.ToString();\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x?.ToString()\").WithLocation(9, 44),\n // (10,43): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c = () => x.ToString()?[0];\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x.ToString()?[0]\").WithLocation(10, 43),\n // (11,43): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c1 = () => x.ToString()?.Length;\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x.ToString()?.Length\").WithLocation(11, 43),\n // (13,43): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c2 = () => x?.ToString()?.Length;\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \"x?.ToString()?.Length\").WithLocation(13, 43),\n // (13,45): error CS8072: An expression tree lambda may not contain a null propagating operator.\n // Expression> c2 = () => x?.ToString()?.Length;\n Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, \".ToString()?.Length\").WithLocation(13, 45)\n );\n }\n\n [Fact]\n [WorkItem(915609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609\")]\n public void DictionaryInitializerInExprLambda()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void M(T x)\n {\n Expression>> s = () => new Dictionary () {[1] = 2};\n}\n\n static void Main()\n {\n M((string)null);\n }\n}\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics(\n // (10,87): error CS8073: An expression tree lambda may not contain a dictionary initializer.\n // Expression>> s = () => new Dictionary () {[1] = 2};\n Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, \"[1]\").WithLocation(10, 87)\n );\n }\n\n [Fact]\n [WorkItem(915609, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609\")]\n public void DictionaryInitializerInExprLambda1()\n {\n var text = @\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n\nnamespace ConsoleApplication31\n{\n class Program\n {\n static void Main(string[] args)\n {\n var o = new Goo();\n var x = o.E.Compile()().Pop();\n System.Console.WriteLine(x);\n }\n }\n\n static class StackExtensions\n {\n public static void Add(this Stack s, T x) => s.Push(x);\n }\n\n class Goo\n {\n public Expression>> E = () => new Stack { 42 };\n }\n}\n\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics(\n // (25,72): error CS8075: An expression tree lambda may not contain an extension collection element initializer.\n // public Expression>> E = () => new Stack { 42 };\n Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, \"42\").WithLocation(25, 72)\n );\n }\n\n [WorkItem(310, \"https://github.com/dotnet/roslyn/issues/310\")]\n [Fact]\n public void ExtensionElementInitializerInExpressionLambda()\n {\n var text = @\"\nusing System;\nusing System.Collections;\nusing System.Linq.Expressions;\nclass C\n{\n static void Main()\n {\n Expression> e = () => new C { H = { [\"\"Key\"\"] = \"\"Value\"\" } };\n Console.WriteLine(e);\n var c = e.Compile().Invoke();\n Console.WriteLine(c.H[\"\"Key\"\"]);\n }\n readonly Hashtable H = new Hashtable();\n}\n\n\";\n CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics(\n // (9,53): error CS8073: An expression tree lambda may not contain a dictionary initializer.\n // Expression> e = () => new C { H = { [\"Key\"] = \"Value\" } };\n Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, @\"[\"\"Key\"\"]\").WithLocation(9, 53)\n );\n }\n\n [WorkItem(12900, \"https://github.com/dotnet/roslyn/issues/12900\")]\n [WorkItem(17138, \"https://github.com/dotnet/roslyn/issues/17138\")]\n [Fact]\n public void CSharp7FeaturesInExprTrees()\n {\n var source = @\"\nusing System;\n//using System.Collections;\nusing System.Linq.Expressions;\nclass C\n{\n static void Main()\n {\n // out variable declarations\n Expression> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1\n\n // pattern matching\n object o = 3;\n Expression> e2 = () => o is int y && y == 3; // ERROR 2\n\n // direct tuple creation could be OK, as it is just a constructor invocation,\n // not for long tuples the generated code is more complex, and we would\n // prefer custom expression trees to express the semantics.\n Expression> e3 = () => (1, o); // ERROR 3: tuple literal\n Expression> e4 = () => (1, 2); // ERROR 4: tuple literal\n\n // tuple conversions\n (byte, byte) t1 = (1, 2);\n Expression> e5 = () => t1; // OK, identity conversion\n Expression> e6 = () => t1; // ERROR 5: tuple conversion\n\n Expression> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method\n\n // discard\n Expression> e8 = () => TryGetThree(out int _);\n Expression> e9 = () => TryGetThree(out var _);\n Expression> e10 = () => _ = (bool)o;\n Expression> e11 = () => _ = (_, _) = GetTuple();\n Expression> e12 = () => _ = var (a, _) = GetTuple();\n Expression> e13 = () => _ = (var a, var _) = GetTuple();\n Expression> e14 = () => TryGetThree(out _);\n }\n\n static bool TryGetThree(out int three)\n {\n three = 3;\n return true;\n }\n\n static int three = 3;\n static ref int GetRefThree()\n {\n return ref three;\n }\n static int TakeRef(ref int x)\n {\n Console.WriteLine(\"\"wow\"\");\n return x;\n }\n static (object, object) GetTuple()\n {\n return (null, null);\n }\n}\nnamespace System\n{\n struct ValueTuple\n {\n public T1 Item1;\n public T2 Item2;\n public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; }\n }\n}\n\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Indicates that the use of on a member is meant to be treated as a tuple with element names.\n /// \n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )]\n public sealed class TupleElementNamesAttribute : Attribute\n {\n public TupleElementNamesAttribute(string[] transformNames) { }\n }\n}\n\";\n var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe);\n compilation.VerifyDiagnostics(\n // (34,50): error CS8185: A declaration is not allowed in this context.\n // Expression> e12 = () => _ = var (a, _) = GetTuple();\n Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, \"var (a, _)\").WithLocation(34, 50),\n // (35,51): error CS8185: A declaration is not allowed in this context.\n // Expression> e13 = () => _ = (var a, var _) = GetTuple();\n Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, \"var a\").WithLocation(35, 51),\n // (10,59): error CS8198: An expression tree may not contain an out argument variable declaration.\n // Expression> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, \"int x\").WithLocation(10, 59),\n // (14,43): error CS8122: An expression tree may not contain an 'is' pattern-matching operator.\n // Expression> e2 = () => o is int y && y == 3; // ERROR 2\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, \"o is int y\").WithLocation(14, 43),\n // (19,45): error CS8143: An expression tree may not contain a tuple literal.\n // Expression> e3 = () => (1, o); // ERROR 3: tuple literal\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, \"(1, o)\").WithLocation(19, 45),\n // (20,49): error CS8143: An expression tree may not contain a tuple literal.\n // Expression> e4 = () => (1, 2); // ERROR 4: tuple literal\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, \"(1, 2)\").WithLocation(20, 49),\n // (25,49): error CS8144: An expression tree may not contain a tuple conversion.\n // Expression> e6 = () => t1; // ERROR 5: tuple conversion\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, \"t1\").WithLocation(25, 49),\n // (27,54): error CS8156: An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference\n // Expression> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method\n Diagnostic(ErrorCode.ERR_RefReturningCallInExpressionTree, \"GetRefThree()\").WithLocation(27, 54),\n // (30,59): error CS8205: An expression tree may not contain a discard.\n // Expression> e8 = () => TryGetThree(out int _);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, \"int _\").WithLocation(30, 59),\n // (31,59): error CS8205: An expression tree may not contain a discard.\n // Expression> e9 = () => TryGetThree(out var _);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, \"var _\").WithLocation(31, 59),\n // (32,44): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e10 = () => _ = (bool)o;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"_ = (bool)o\").WithLocation(32, 44),\n // (33,46): error CS0832: An expression tree may not contain an assignment operator\n // Expression> e11 = () => _ = (_, _) = GetTuple();\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, \"_ = (_, _) = GetTuple()\").WithLocation(33, 46),\n // (33,50): error CS8143: An expression tree may not contain a tuple literal.\n // Expression> e11 = () => _ = (_, _) = GetTuple();\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, \"(_, _)\").WithLocation(33, 50),\n // (36,60): error CS8205: An expression tree may not contain a discard.\n // Expression> e14 = () => TryGetThree(out _);\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, \"_\").WithLocation(36, 60)\n );\n }\n\n [Fact]\n public void DictionaryInitializerInCS5()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n var s = new Dictionary () {[1] = 2};\n }\n}\n\";\n CreateCompilationWithMscorlib45(text,\n new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef },\n parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics(\n // (8,46): error CS8026: Feature 'dictionary initializer' is not available in C# 5. Please use language version 6 or greater.\n // var s = new Dictionary () {[1] = 2};\n Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, \"[1] = 2\").WithArguments(\"dictionary initializer\", \"6\").WithLocation(8, 46)\n );\n }\n\n [Fact]\n public void DictionaryInitializerDataFlow()\n {\n var text = @\"\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n int i;\n var s = new Dictionary () {[i] = 2};\n\n i = 1;\n System.Console.WriteLine(i);\n }\n\n static void Goo()\n {\n int i;\n var s = new Dictionary () {[i = 1] = 2};\n\n System.Console.WriteLine(i);\n }\n}\n\";\n CreateCompilationWithMscorlib45(text,\n new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef },\n parseOptions: TestOptions.Regular).VerifyDiagnostics(\n // (9,47): error CS0165: Use of unassigned local variable 'i'\n // var s = new Dictionary () {[i] = 2};\n Diagnostic(ErrorCode.ERR_UseDefViolation, \"i\").WithArguments(\"i\").WithLocation(9, 47)\n );\n }\n\n [Fact]\n public void ConditionalMemberAccessNotStatement()\n {\n var text = @\"\nclass Program\n{\n static void Main()\n {\n var x = new int[10];\n\n x?.Length;\n x?[1];\n x?.ToString()[1];\n }\n}\n\";\n CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x?.Length;\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x?.Length\").WithLocation(8, 9),\n // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x?[1];\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x?[1]\").WithLocation(9, 9),\n // (10,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement\n // x?.ToString()[1];\n Diagnostic(ErrorCode.ERR_IllegalStatement, \"x?.ToString()[1]\").WithLocation(10, 9)\n );\n }\n\n [WorkItem(23422, \"https://github.com/dotnet/roslyn/issues/23422\")]\n [Fact]\n public void ConditionalMemberAccessRefLike()\n {\n var text = @\"\nclass Program\n{\n static void Main(string[] args)\n {\n var o = new Program();\n\n o?.F(); // this is ok\n\n var x = o?.F();\n\n var y = o?.F() ?? default;\n\n var z = o?.F().field ?? default;\n }\n\n S2 F() => throw null;\n}\n\npublic ref struct S1\n{\n\n}\n\npublic ref struct S2\n{\n public S1 field;\n}\n\";\n CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics(\n // (10,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2'\n // var x = o?.F();\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"S2\").WithLocation(10, 18),\n // (12,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2'\n // var y = o?.F() ?? default;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"S2\").WithLocation(12, 18),\n // (14,18): error CS0023: Operator '?' cannot be applied to operand of type 'S1'\n // var z = o?.F().field ?? default;\n Diagnostic(ErrorCode.ERR_BadUnaryOp, \"?\").WithArguments(\"?\", \"S1\").WithLocation(14, 18)\n );\n }\n\n [Fact]\n [WorkItem(1179322, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179322\")]\n public void LabelSameNameAsParameter()\n {\n var text = @\"\nclass Program\n{\n static object M(object obj, object value)\n {\n if (((string)obj).Length == 0) value: new Program();\n }\n}\n\";\n var compilation = CreateCompilation(text);\n compilation.GetParseDiagnostics().Verify();\n\n // Make sure the compiler can handle producing method body diagnostics for this pattern when \n // queried via an API (command line compile would exit after parse errors were reported). \n compilation.GetMethodBodyDiagnostics().Verify(\n // (6,41): error CS1023: Embedded statement cannot be a declaration or labeled statement\n // if (((string)obj).Length == 0) value: new Program();\n Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, \"value: new Program();\").WithLocation(6, 41),\n // (6,41): warning CS0164: This label has not been referenced\n // if (((string)obj).Length == 0) value: new Program();\n Diagnostic(ErrorCode.WRN_UnreferencedLabel, \"value\").WithLocation(6, 41),\n // (4,19): error CS0161: 'Program.M(object, object)': not all code paths return a value\n // static object M(object obj, object value)\n Diagnostic(ErrorCode.ERR_ReturnExpected, \"M\").WithArguments(\"Program.M(object, object)\").WithLocation(4, 19));\n }\n\n [Fact]\n public void ThrowInExpressionTree()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static bool b = true;\n static object o = string.Empty;\n static void Main(string[] args)\n {\n Expression> e1 = () => o ?? throw null;\n Expression> e2 = () => b ? throw null : o;\n Expression> e3 = () => b ? o : throw null;\n Expression> e4 = () => throw null;\n }\n }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (13,54): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e1 = () => o ?? throw null;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(13, 54),\n // (14,53): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e2 = () => b ? throw null : o;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(14, 53),\n // (15,57): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e3 = () => b ? o : throw null;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(15, 57),\n // (16,49): error CS8188: An expression tree may not contain a throw-expression.\n // Expression> e4 = () => throw null;\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, \"throw null\").WithLocation(16, 49)\n );\n }\n\n [Fact, WorkItem(17674, \"https://github.com/dotnet/roslyn/issues/17674\")]\n public void VoidDiscardAssignment()\n {\n var text = @\"\nclass Program\n{\n public static void Main(string[] args)\n {\n _ = M();\n }\n static void M() { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (6,9): error CS8209: A value of type 'void' may not be assigned.\n // _ = M();\n Diagnostic(ErrorCode.ERR_VoidAssignment, \"_\").WithLocation(6, 9)\n );\n }\n\n [Fact, WorkItem(22880, \"https://github.com/dotnet/roslyn/issues/22880\")]\n public void AttributeCtorInParam()\n {\n var text = @\"\n[A(1)]\nclass A : System.Attribute {\n A(in int x) { }\n}\n\n[B()]\nclass B : System.Attribute {\n B(in int x = 1) { }\n}\n\";\n CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(\n // (2,2): error CS8358: Cannot use attribute constructor 'A.A(in int)' because it has 'in' parameters.\n // [A(1)]\n Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, \"A(1)\").WithArguments(\"A.A(in int)\").WithLocation(2, 2),\n // (7,2): error CS8358: Cannot use attribute constructor 'B.B(in int)' because it has 'in' parameters.\n // [B()]\n Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, \"B()\").WithArguments(\"B.B(in int)\").WithLocation(7, 2)\n );\n }\n\n [Fact]\n public void ERR_ExpressionTreeContainsSwitchExpression()\n {\n var text = @\"\nusing System;\nusing System.Linq.Expressions;\n\npublic class C\n{\n public int Test()\n {\n Expression> e = a => a switch { 0 => 1, _ => 2 }; // CS8411\n return 1;\n }\n}\";\n CreateCompilationWithMscorlib40AndSystemCore(text, parseOptions: TestOptions.RegularWithRecursivePatterns).VerifyDiagnostics(\n // (9,45): error CS8411: An expression tree may not contain a switch expression.\n // Expression> e = a => a switch { 0 => 1, _ => 2 }; // CS8411\n Diagnostic(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, \"a switch { 0 => 1, _ => 2 }\").WithLocation(9, 45)\n );\n }\n\n [Fact]\n public void PointerGenericConstraintTypes()\n {\n var source = @\"\nnamespace A\n{\n class D {}\n}\n\nclass B {}\n\nunsafe class C where T : byte*\n where U : unmanaged\n where V : U*\n where X : object*\n where Y : B*\n where Z : A.D*\n{\n void M1() where A : byte* {}\n void M2() where A : unmanaged \n where B : A* {}\n void M3() where A : object* {}\n void M4() where A : B* {}\n void M5() where A : T {}\n}\";\n var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);\n comp.VerifyDiagnostics(\n // (9,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // unsafe class C where T : byte*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"byte*\").WithLocation(9, 44),\n // (11,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where V : U*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"U*\").WithLocation(11, 44),\n // (12,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where X : object*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"object*\").WithLocation(12, 44),\n // (13,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where Y : B*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"B*\").WithLocation(13, 44),\n // (14,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where Z : A.D*\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"A.D*\").WithLocation(14, 44),\n // (16,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // void M1() where A : byte* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"byte*\").WithLocation(16, 28),\n // (18,31): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // where B : A* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"A*\").WithLocation(18, 31),\n // (19,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // void M3() where A : object* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"object*\").WithLocation(19, 28),\n // (20,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // void M4() where A : B* {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"B*\").WithLocation(20, 28)\n );\n }\n\n [Fact]\n public void ArrayGenericConstraintTypes()\n {\n var source = @\"class A where T : object[] {}\";\n\n var comp = CreateCompilation(source);\n comp.VerifyDiagnostics(\n // (1,22): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.\n // class A where T : object[] {}\n Diagnostic(ErrorCode.ERR_BadConstraintType, \"object[]\").WithLocation(1, 22));\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":427,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinuePdbTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Immutable;\nusing System.Linq;\nusing System.Reflection.Metadata;\nusing System.Reflection.Metadata.Ecma335;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.UnitTests;\nusing Microsoft.CodeAnalysis.Emit;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests\n{\n public class EditAndContinuePdbTests : EditAndContinueTestBase\n {\n [Theory]\n [MemberData(nameof(ExternalPdbFormats))]\n public void MethodExtents(DebugInformationFormat format)\n {\n var source0 = MarkedSource(WithWindowsLineBreaks(@\"#pragma checksum \"\"C:\\Enc1.cs\"\" \"\"{ff1816ec-aa5e-4d10-87f7-6f4963833460}\"\" \"\"1111111111111111111111111111111111111111\"\"\nusing System;\n\npublic class C\n{\n int A() => 1; \n \n void F() \n { \n#line 10 \"\"C:\\F\\A.cs\"\" \n Console.WriteLine();\n#line 20 \"\"C:\\F\\B.cs\"\"\n Console.WriteLine();\n#line default\n }\n\n int E() => 1;\n\n void G()\n {\n Func H1 = () => 1;\n\n Action H2 = () =>\n {\n Func H3 = () => 3;\n\n };\n }\n} \n\"), fileName: @\"C:\\Enc1.cs\");\n\n var source1 = MarkedSource(WithWindowsLineBreaks(@\"#pragma checksum \"\"C:\\Enc1.cs\"\" \"\"{ff1816ec-aa5e-4d10-87f7-6f4963833460}\"\" \"\"2222222222222222222222222222222222222222\"\"\nusing System;\n\npublic class C\n{\n int A() => 1; \n \n void F() \n { \n#line 10 \"\"C:\\F\\A.cs\"\" \n Console.WriteLine();\n#line 10 \"\"C:\\F\\C.cs\"\"\n Console.WriteLine();\n#line default\n }\n\n void G()\n {\n Func H1 = () => 1;\n\n Action H2 = () =>\n {\n Func H3 = () => 3;\n Func H4 = () => 4;\n };\n }\n\n int E() => 1;\n}\n\"), fileName: @\"C:\\Enc1.cs\");\n\n var source2 = MarkedSource(WithWindowsLineBreaks(@\"#pragma checksum \"\"C:\\Enc1.cs\"\" \"\"{ff1816ec-aa5e-4d10-87f7-6f4963833460}\"\" \"\"3333333333333333333333333333333333333333\"\"\nusing System;\n\npublic class C\n{\n int A() => 3; \n \n void F() \n { \n#line 10 \"\"C:\\F\\B.cs\"\"\n Console.WriteLine();\n#line 10 \"\"C:\\F\\E.cs\"\"\n Console.WriteLine();\n#line default\n }\n\n void G()\n {\n \n\n Action H2 = () =>\n {\n \n Func H4 = () => 4;\n };\n }\n\n int E() => 1; \n\n int B() => 4;\n}\n\"), fileName: @\"C:\\Enc1.cs\");\n\n var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: \"EncMethodExtents\");\n var compilation1 = compilation0.WithSource(source1.Tree);\n var compilation2 = compilation1.WithSource(source2.Tree);\n\n compilation0.VerifyDiagnostics();\n compilation1.VerifyDiagnostics();\n compilation2.VerifyDiagnostics();\n\n var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format));\n var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);\n\n var f0 = compilation0.GetMember(\"C.F\");\n var f1 = compilation1.GetMember(\"C.F\");\n var f2 = compilation2.GetMember(\"C.F\");\n\n var g0 = compilation0.GetMember(\"C.G\");\n var g1 = compilation1.GetMember(\"C.G\");\n var g2 = compilation2.GetMember(\"C.G\");\n\n var a1 = compilation1.GetMember(\"C.A\");\n var a2 = compilation2.GetMember(\"C.A\");\n\n var b2 = compilation2.GetMember(\"C.B\");\n\n var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);\n\n var syntaxMap1 = GetSyntaxMapFromMarkers(source0, source1);\n var diff1 = compilation1.EmitDifference(\n generation0,\n ImmutableArray.Create(\n SemanticEdit.Create(SemanticEditKind.Update, f0, f1, syntaxMap1, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Update, g0, g1, syntaxMap1, preserveLocalVariables: true)));\n\n diff1.VerifySynthesizedMembers(\n \"C: {<>c}\",\n \"C.<>c: {<>9__3_0, <>9__3_2, <>9__3_3#1, <>9__3_1, b__3_0, b__3_1, b__3_2, b__3_3#1}\");\n\n var reader1 = diff1.GetMetadata().Reader;\n\n CheckEncLogDefinitions(reader1,\n Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),\n Row(5, TableIndex.Field, EditAndContinueOperation.Default),\n Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),\n Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default));\n\n if (format == DebugInformationFormat.PortablePdb)\n {\n using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff1.PdbDelta);\n\n CheckEncMap(pdbProvider.GetMetadataReader(),\n Handle(2, TableIndex.MethodDebugInformation),\n Handle(4, TableIndex.MethodDebugInformation),\n Handle(8, TableIndex.MethodDebugInformation),\n Handle(9, TableIndex.MethodDebugInformation),\n Handle(10, TableIndex.MethodDebugInformation),\n Handle(11, TableIndex.MethodDebugInformation));\n }\n\n diff1.VerifyPdb(Enumerable.Range(0x06000001, 20), @\"\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\");\n var syntaxMap2 = GetSyntaxMapFromMarkers(source1, source2);\n var diff2 = compilation2.EmitDifference(\n diff1.NextGeneration,\n ImmutableArray.Create(\n SemanticEdit.Create(SemanticEditKind.Update, f1, f2, syntaxMap2, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Update, g1, g2, syntaxMap2, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Update, a1, a2, syntaxMap2, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Insert, null, b2)));\n\n diff2.VerifySynthesizedMembers(\n \"C: {<>c}\",\n \"C.<>c: {<>9__3_3#1, <>9__3_1, b__3_1, b__3_3#1, <>9__3_0, <>9__3_2, b__3_0, b__3_2}\");\n\n var reader2 = diff2.GetMetadata().Reader;\n\n CheckEncLogDefinitions(reader2,\n Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),\n Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default));\n\n if (format == DebugInformationFormat.PortablePdb)\n {\n using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff2.PdbDelta);\n\n CheckEncMap(pdbProvider.GetMetadataReader(),\n Handle(1, TableIndex.MethodDebugInformation),\n Handle(2, TableIndex.MethodDebugInformation),\n Handle(4, TableIndex.MethodDebugInformation),\n Handle(9, TableIndex.MethodDebugInformation),\n Handle(11, TableIndex.MethodDebugInformation),\n Handle(12, TableIndex.MethodDebugInformation));\n }\n\n diff2.VerifyPdb(Enumerable.Range(0x06000001, 20), @\"\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\");\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Immutable;\nusing System.Linq;\nusing System.Reflection.Metadata;\nusing System.Reflection.Metadata.Ecma335;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.UnitTests;\nusing Microsoft.CodeAnalysis.Emit;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests\n{\n public class EditAndContinuePdbTests : EditAndContinueTestBase\n {\n [Theory]\n [MemberData(nameof(ExternalPdbFormats))]\n public void MethodExtents(DebugInformationFormat format)\n {\n var source0 = MarkedSource(WithWindowsLineBreaks(@\"#pragma checksum \"\"C:\\Enc1.cs\"\" \"\"{ff1816ec-aa5e-4d10-87f7-6f4963833460}\"\" \"\"1111111111111111111111111111111111111111\"\"\nusing System;\n\npublic class C\n{\n int A() => 1; \n \n void F() \n { \n#line 10 \"\"C:\\F\\A.cs\"\" \n Console.WriteLine();\n#line 20 \"\"C:\\F\\B.cs\"\"\n Console.WriteLine();\n#line default\n }\n\n int E() => 1;\n\n void G()\n {\n Func H1 = () => 1;\n\n Action H2 = () =>\n {\n Func H3 = () => 3;\n\n };\n }\n} \n\"), fileName: @\"C:\\Enc1.cs\");\n\n var source1 = MarkedSource(WithWindowsLineBreaks(@\"#pragma checksum \"\"C:\\Enc1.cs\"\" \"\"{ff1816ec-aa5e-4d10-87f7-6f4963833460}\"\" \"\"2222222222222222222222222222222222222222\"\"\nusing System;\n\npublic class C\n{\n int A() => 1; \n \n void F() \n { \n#line 10 \"\"C:\\F\\A.cs\"\" \n Console.WriteLine();\n#line 10 \"\"C:\\F\\C.cs\"\"\n Console.WriteLine();\n#line default\n }\n\n void G()\n {\n Func H1 = () => 1;\n\n Action H2 = () =>\n {\n Func H3 = () => 3;\n Func H4 = () => 4;\n };\n }\n\n int E() => 1;\n}\n\"), fileName: @\"C:\\Enc1.cs\");\n\n var source2 = MarkedSource(WithWindowsLineBreaks(@\"#pragma checksum \"\"C:\\Enc1.cs\"\" \"\"{ff1816ec-aa5e-4d10-87f7-6f4963833460}\"\" \"\"3333333333333333333333333333333333333333\"\"\nusing System;\n\npublic class C\n{\n int A() => 3; \n \n void F() \n { \n#line 10 \"\"C:\\F\\B.cs\"\"\n Console.WriteLine();\n#line 10 \"\"C:\\F\\E.cs\"\"\n Console.WriteLine();\n#line default\n }\n\n void G()\n {\n \n\n Action H2 = () =>\n {\n \n Func H4 = () => 4;\n };\n }\n\n int E() => 1; \n\n int B() => 4;\n}\n\"), fileName: @\"C:\\Enc1.cs\");\n\n var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: \"EncMethodExtents\");\n var compilation1 = compilation0.WithSource(source1.Tree);\n var compilation2 = compilation1.WithSource(source2.Tree);\n\n compilation0.VerifyDiagnostics();\n compilation1.VerifyDiagnostics();\n compilation2.VerifyDiagnostics();\n\n var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format));\n var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);\n\n var f0 = compilation0.GetMember(\"C.F\");\n var f1 = compilation1.GetMember(\"C.F\");\n var f2 = compilation2.GetMember(\"C.F\");\n\n var g0 = compilation0.GetMember(\"C.G\");\n var g1 = compilation1.GetMember(\"C.G\");\n var g2 = compilation2.GetMember(\"C.G\");\n\n var a1 = compilation1.GetMember(\"C.A\");\n var a2 = compilation2.GetMember(\"C.A\");\n\n var b2 = compilation2.GetMember(\"C.B\");\n\n var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);\n\n var syntaxMap1 = GetSyntaxMapFromMarkers(source0, source1);\n var diff1 = compilation1.EmitDifference(\n generation0,\n ImmutableArray.Create(\n SemanticEdit.Create(SemanticEditKind.Update, f0, f1, syntaxMap1, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Update, g0, g1, syntaxMap1, preserveLocalVariables: true)));\n\n diff1.VerifySynthesizedMembers(\n \"C: {<>c}\",\n \"C.<>c: {<>9__3_0, <>9__3_2, <>9__3_3#1, <>9__3_1, b__3_0, b__3_1, b__3_2, b__3_3#1}\");\n\n var reader1 = diff1.GetMetadata().Reader;\n\n CheckEncLogDefinitions(reader1,\n Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),\n Row(5, TableIndex.Field, EditAndContinueOperation.Default),\n Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),\n Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default));\n\n if (format == DebugInformationFormat.PortablePdb)\n {\n using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff1.PdbDelta);\n\n CheckEncMap(pdbProvider.GetMetadataReader(),\n Handle(2, TableIndex.MethodDebugInformation),\n Handle(4, TableIndex.MethodDebugInformation),\n Handle(8, TableIndex.MethodDebugInformation),\n Handle(9, TableIndex.MethodDebugInformation),\n Handle(10, TableIndex.MethodDebugInformation),\n Handle(11, TableIndex.MethodDebugInformation));\n }\n\n diff1.VerifyPdb(Enumerable.Range(0x06000001, 20), @\"\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\");\n var syntaxMap2 = GetSyntaxMapFromMarkers(source1, source2);\n var diff2 = compilation2.EmitDifference(\n diff1.NextGeneration,\n ImmutableArray.Create(\n SemanticEdit.Create(SemanticEditKind.Update, f1, f2, syntaxMap2, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Update, g1, g2, syntaxMap2, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Update, a1, a2, syntaxMap2, preserveLocalVariables: true),\n SemanticEdit.Create(SemanticEditKind.Insert, null, b2)));\n\n diff2.VerifySynthesizedMembers(\n \"C: {<>c}\",\n \"C.<>c: {<>9__3_3#1, <>9__3_1, b__3_1, b__3_3#1, <>9__3_0, <>9__3_2, b__3_0, b__3_2}\");\n\n var reader2 = diff2.GetMetadata().Reader;\n\n CheckEncLogDefinitions(reader2,\n Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),\n Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),\n Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),\n Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default));\n\n if (format == DebugInformationFormat.PortablePdb)\n {\n using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff2.PdbDelta);\n\n CheckEncMap(pdbProvider.GetMetadataReader(),\n Handle(1, TableIndex.MethodDebugInformation),\n Handle(2, TableIndex.MethodDebugInformation),\n Handle(4, TableIndex.MethodDebugInformation),\n Handle(9, TableIndex.MethodDebugInformation),\n Handle(11, TableIndex.MethodDebugInformation),\n Handle(12, TableIndex.MethodDebugInformation));\n }\n\n diff2.VerifyPdb(Enumerable.Range(0x06000001, 20), @\"\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\");\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":428,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.es.xlf"},"before_content":{"kind":"string","value":"\n\n \n \n \n Remove this value when another is added.\n Quite este valor cuando se agregue otro.\n https://github.com/Microsoft/msbuild/issues/1661\n \n \n \n"},"after_content":{"kind":"string","value":"\n\n \n \n \n Remove this value when another is added.\n Quite este valor cuando se agregue otro.\n https://github.com/Microsoft/msbuild/issues/1661\n \n \n \n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":429,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Dependencies/Collections/Internal/ICollectionCalls`1.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Generic;\n\nnamespace Microsoft.CodeAnalysis.Collections.Internal\n{\n /// \n /// Provides static methods to invoke members on value types that explicitly implement\n /// the member.\n /// \n /// \n /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is\n /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a\n /// normal call to an implicitly implemented member.\n /// \n internal static class ICollectionCalls\n {\n public static bool IsReadOnly(ref TCollection collection)\n where TCollection : ICollection\n => collection.IsReadOnly;\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Collections.Generic;\n\nnamespace Microsoft.CodeAnalysis.Collections.Internal\n{\n /// \n /// Provides static methods to invoke members on value types that explicitly implement\n /// the member.\n /// \n /// \n /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is\n /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a\n /// normal call to an implicitly implemented member.\n /// \n internal static class ICollectionCalls\n {\n public static bool IsReadOnly(ref TCollection collection)\n where TCollection : ICollection\n => collection.IsReadOnly;\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":430,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./eng/prepare-tests.ps1"},"before_content":{"kind":"string","value":"[CmdletBinding(PositionalBinding=$false)]\nparam ([string]$configuration = \"Debug\")\n\nSet-StrictMode -version 2.0\n$ErrorActionPreference=\"Stop\"\n\ntry {\n . (Join-Path $PSScriptRoot \"build-utils.ps1\")\n Push-Location $RepoRoot\n\n $dotnet = Ensure-DotnetSdk\n # permissions issues make this a pain to do in PrepareTests itself.\n Remove-Item -Recurse -Force \"$RepoRoot\\artifacts\\testPayload\" -ErrorAction SilentlyContinue\n Exec-Console $dotnet \"$RepoRoot\\artifacts\\bin\\PrepareTests\\$configuration\\net5.0\\PrepareTests.dll --source $RepoRoot --destination $RepoRoot\\artifacts\\testPayload\"\n exit 0\n}\ncatch {\n Write-Host $_\n exit 1\n}\nfinally {\n Pop-Location\n}\n"},"after_content":{"kind":"string","value":"[CmdletBinding(PositionalBinding=$false)]\nparam ([string]$configuration = \"Debug\")\n\nSet-StrictMode -version 2.0\n$ErrorActionPreference=\"Stop\"\n\ntry {\n . (Join-Path $PSScriptRoot \"build-utils.ps1\")\n Push-Location $RepoRoot\n\n $dotnet = Ensure-DotnetSdk\n # permissions issues make this a pain to do in PrepareTests itself.\n Remove-Item -Recurse -Force \"$RepoRoot\\artifacts\\testPayload\" -ErrorAction SilentlyContinue\n Exec-Console $dotnet \"$RepoRoot\\artifacts\\bin\\PrepareTests\\$configuration\\net5.0\\PrepareTests.dll --source $RepoRoot --destination $RepoRoot\\artifacts\\testPayload\"\n exit 0\n}\ncatch {\n Write-Host $_\n exit 1\n}\nfinally {\n Pop-Location\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":431,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/EditorFeatures/Test2/Rename/InlineRenameTests.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Threading\nImports Microsoft.CodeAnalysis.CodeActions\nImports Microsoft.CodeAnalysis.CodeRefactorings\nImports Microsoft.CodeAnalysis.Debugging\nImports Microsoft.CodeAnalysis.Editor.Host\nImports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking\nImports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces\nImports Microsoft.CodeAnalysis.IntroduceVariable\nImports Microsoft.CodeAnalysis.Notification\nImports Microsoft.CodeAnalysis.Options\nImports Microsoft.CodeAnalysis.Remote.Testing\nImports Microsoft.CodeAnalysis.Rename\nImports Microsoft.CodeAnalysis.Shared.Utilities\nImports Microsoft.VisualStudio.Text\n\nNamespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename\n <[UseExportProvider]>\n Public Class InlineRenameTests\n Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper\n\n Public Sub New(outputHelper As Abstractions.ITestOutputHelper)\n _outputHelper = outputHelper\n End Sub\n\n \n \n Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n object [|$$test|] = new object();\n var other = [|test|];\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"renamed\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"renamedtest\")\n End Using\n End Function\n\n \n \n Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n f = (int _, string [|$$_|]) => { _ = null; return 1; };\n }\n}\n ]]>\n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:=\"_\", renameTextPrefix:=\"change\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n , host)\n\n Dim options = workspace.CurrentSolution.Options\n workspace.TryApplyChanges(\n workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True)))\n\n Dim session = StartSession(workspace)\n\n Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n ' User could use copy & paste to enter invalid character\n textBuffer.Insert(selectedSpan, \"<>\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Test1<>\")\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n [|$$x|])\n {\n foreach (var (y1, y2) in [|x|])\n {\n }\n }\n void Deconstruct(out int i, out int j) { i = 0; j = 0; }\n}\n ]]>\n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"x\", \"change\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n x)\n {\n foreach (var (y1, y2) in x)\n {\n }\n var (z1, z2) = this;\n [|Deconstruct|](out var t1, out var t2);\n }\n void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; }\n}\n ]]>\n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"Deconstruct\", \"Changed\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n Await WaitForRename(workspace)\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace,\n originalTextToRename As String,\n renameTextPrefix As String,\n Optional renameOverloads As Boolean = False,\n Optional renameInStrings As Boolean = False,\n Optional renameInComments As Boolean = False,\n Optional renameFile As Boolean = False,\n Optional fileToRename As DocumentId = Nothing) As Task\n Dim optionSet = workspace.Options\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads)\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings)\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments)\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile)\n workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet))\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor\n renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix)\n\n Dim replacementText = renameTextPrefix + originalTextToRename\n Await WaitForRename(workspace)\n\n Await VerifyTagsAreCorrect(workspace, replacementText)\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, replacementText)\n\n If renameFile Then\n If fileToRename Is Nothing Then\n VerifyFileName(workspace, replacementText)\n Else\n VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText)\n End If\n End If\n End Function\n\n \n \n \n Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass Program\n{\n public void [|$$goo|]()\n {\n [|goo|]();\n }\n\n public void [|goo|]&lt;T&gt;()\n {\n [|goo|]&lt;T&gt;();\n }\n\n public void [|goo|](int i)\n {\n [|goo|](i);\n }\n}\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nImports System.Collections.Generic\nImports System.Linq\nImports System\n\nPublic Class Program\n Sub Main(args As String())\n\n End Sub\n\n Public Sub [|$$goo|]()\n [|goo|]()\n End Sub\n\n Public Sub [|goo|](of T)()\n [|goo|](of T)()\n End Sub\n\n Public Sub [|goo|](s As String)\n [|goo|](s)\n End Sub\n\n Public Shared Sub [|goo|](d As Double)\n [|goo|](d)\n End Sub\nEnd Class\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nPublic Class Program\n Sub Main([|$$args|] As String())\n\n End Sub\nEnd Class\n \n \n' args\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"args\", \"bar\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"Test1.vb\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n\n ' https://github.com/dotnet/roslyn/issues/36075\n ' VerifyFileRename(workspace, \"ABC\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n \n \n Proj2\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"F\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n \n \n Proj2\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"F\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"AB\")\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n \n Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n [|goo|]! \n public void [|$$goo|]()\n {\n // [|goo|] GOO\n /* [|goo|] */\n [|goo|]();\n\n var a = \"goo\";\n var b = $\"{1}goo{2}\";\n }\n\n public void goo(int i)\n {\n goo(i);\n }\n}]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n [|goo|]! \n public void [|$$goo|]()\n {\n // [|goo|] GOO\n /* [|goo|] */\n [|goo|]();\n\n var a = \"goo\";\n var b = $\"{1}goo{2}\";\n }\n\n public void [|goo|](int i)\n {\n [|goo|](i);\n }\n}]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True, renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n [|goo|]! \n public void [|$$goo|]()\n {\n // [|goo|] GOO\n /* [|goo|] */\n [|goo|]();\n\n var a = \"[|goo|]\";\n var b = $\"{1}[|goo|]{2}\";\n }\n\n public void goo(int i)\n {\n goo(i);\n }\n}]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True, renameInStrings:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n \n Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n\n\nClass Program\n\t''' <[|goo|]> [|goo|]! \n\tPublic Sub [|$$goo|]()\n\t\t' [|goo|] GOO\n\t\t' [|goo|]\n\t\t[|goo|]()\n\n\t\tDim a = \"goo\"\n\t\tDim b = $\"{1}goo{2}\"\n\tEnd Sub\n\n\tPublic Sub goo(i As Integer)\n\t\tgoo(i)\n\tEnd Sub\nEnd Class\n]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n\n\nClass Program\n\t''' <[|goo|]> [|goo|]! \n\tPublic Sub [|$$goo|]()\n\t\t' [|goo|] GOO\n\t\t' [|goo|]\n\t\t[|goo|]()\n\n\t\tDim a = \"goo\"\n\t\tDim b = $\"{1}goo{2}\"\n\tEnd Sub\n\n\tPublic Sub [|goo|](i As Integer)\n\t\t[|goo|](i)\n\tEnd Sub\nEnd Class\n]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True, renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n\n\nClass Program\n\t''' <[|goo|]> [|goo|]! \n\tPublic Sub [|$$goo|]()\n\t\t' [|goo|] GOO\n\t\t' [|goo|]\n\t\t[|goo|]()\n\n\t\tDim a = \"[|goo|]\"\n\t\tDim b = $\"{1}[|goo|]{2}\"\n\tEnd Sub\n\n\tPublic Sub goo(i As Integer)\n\t\tgoo(i)\n\tEnd Sub\nEnd Class\n]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True, renameInStrings:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Sub SimpleEditAndCancel(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n Dim initialTextSnapshot = textBuffer.CurrentSnapshot\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Cancel()\n\n ' Assert the file is what it started as\n Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText())\n\n ' Assert the file name didn't change\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Sub\n\n \n \n \n Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$dynamic|]\n {\n void M()\n {\n [|dynamic|] d;\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"goo\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"goodynamic\")\n End Using\n End Function\n\n \n \n Public Sub ReadOnlyRegionsCreated(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class $$C\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n Dim buffer = workspace.Documents.Single().GetTextBuffer()\n\n ' Typing at the beginning and end of our span should work\n Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Assert.False(buffer.IsReadOnly(cursorPosition))\n Assert.False(buffer.IsReadOnly(cursorPosition + 1))\n\n ' Replacing our span should work\n Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1)))\n\n ' Make sure we can't type at the start or end\n Assert.True(buffer.IsReadOnly(0))\n Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length))\n\n session.Cancel()\n\n ' Assert the file name didn't change\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Sub\n\n \n \n \n Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n $$C c; class C { }\n \n , host)\n\n Dim session = StartSession(workspace)\n Dim buffer = workspace.Documents.Single().GetTextBuffer()\n\n ' Typing at the beginning and end of our span should work\n Assert.False(buffer.IsReadOnly(0))\n Assert.False(buffer.IsReadOnly(1))\n\n ' Replacing our span should work\n Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1)))\n\n session.Cancel()\n\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Sub\n\n \n \n Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost)\n Using result = RenameEngineResult.Create(_outputHelper,\n \n \n \n abstract class AAAA\n {\n public abstract void [|Goo|]();\n }\n\n class BBBB : AAAA\n {\n public override void [|Goo|]() { }\n }\n\n class DDDD : BBBB\n {\n public override void [|Goo|]() { }\n }\n class CCCC : AAAA\n {\n public override void [|$$Goo|]() { }\n }\n \n \n , host:=host, renameTo:=\"GooBar\")\n\n End Using\n End Sub\n\n \n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n\n session.Cancel()\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n VerifyFileName(workspace, \"BarTest1\")\n\n textBuffer.Insert(caretPosition, \"Baz\")\n Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1)\n End Using\n End Function\n\n \n \n Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n ' Preview should not return null\n Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService)\n previewService.ReturnsNull = False\n\n Dim session = StartSession(workspace)\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit(previewChanges:=True)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n Assert.True(previewService.Called)\n Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title)\n Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, \"Goo\", \"BarGoo\"), previewService.Description)\n Assert.Equal(\"Goo\", previewService.TopLevelName)\n Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph)\n End Using\n End Function\n\n \n \n Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService)\n previewService.ReturnsNull = True\n\n Dim session = StartSession(workspace)\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit(previewChanges:=True)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n Assert.True(previewService.Called)\n\n ' Session should still be up; type some more\n caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n textBuffer.Insert(caretPosition, \"Cat\")\n\n previewService.ReturnsNull = False\n previewService.Called = False\n session.Commit(previewChanges:=True)\n Await VerifyTagsAreCorrect(workspace, \"CatBarGoo\")\n Assert.True(previewService.Called)\n\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nClass C\n Sub [|M$$|]()\n End Sub\n\n Sub Test()\n#If Proj1 Then\n [|M|]()\n#End If\n#If Proj2 Then\n [|M|]()\n#End If\n End Sub\nEnd Class\n \n \n \n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"o\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Mo\")\n\n textBuffer.Insert(caretPosition + 1, \"w\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Mow\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Mow\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nClass C\n Dim [|m$$|] As Integer\n\n Sub Test()\n#If Proj1 Then\n Dim x = [|m|]\n#End If\n#If Proj2 Then\n Dim x = [|m|]\n#End If\n End Sub\nEnd Class\n \n \n \n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"ma\")\n\n textBuffer.Insert(caretPosition + 1, \"w\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"maw\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"maw\")\n End Using\n End Function\n\n \n \n \n \n Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void M()\n {\n var z = {|introducelocal:5 + 5|};\n var q = [|x$$|];\n }\n\n int [|x|];\n}\n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n textBuffer.Insert(caretPosition, \"yz\")\n Await WaitForRename(workspace)\n\n ' Invoke a CodeAction\n Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider()\n Dim actions = New List(Of CodeAction)\n Dim context = New CodeRefactoringContext(\n workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id),\n workspace.Documents.Single().AnnotatedSpans()(\"introducelocal\").Single(),\n Sub(a) actions.Add(a),\n CancellationToken.None)\n\n workspace.Documents.Single().AnnotatedSpans.Clear()\n introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait()\n\n Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService)\n\n Dim actualSeverity As NotificationSeverity = Nothing\n Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback)\n notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity\n\n editHandler.Apply(\n workspace,\n workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id),\n Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None),\n \"unused\",\n New ProgressTracker(),\n CancellationToken.None)\n\n ' CodeAction should be rejected\n Assert.Equal(NotificationSeverity.Error, actualSeverity)\n Assert.Equal(\"\nclass C\n{\n void M()\n {\n var z = 5 + 5;\n var q = xyz;\n }\n\n int xyz;\n}\",\n textBuffer.CurrentSnapshot.GetText())\n\n ' Rename should still be active\n Await VerifyTagsAreCorrect(workspace, \"xyz\")\n\n textBuffer.Insert(caretPosition + 2, \"q\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"xyzq\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M$$|]()\n {\n nameof([|M|]).ToString();\n }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M|]()\n {\n nameof([|M$$|]).ToString();\n }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M$$|]()\n {\n nameof(M).ToString();\n }\n\n void M(int x) { }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M|]()\n {\n nameof([|M$$|]).ToString();\n }\n\n void [|M|](int x) { }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|$$M|]()\n {\n nameof([|M|]).ToString();\n }\n\n void [|M|](int x) { }\n}\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"M\", \"Sa\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameCommitsWhenDebuggingStarts(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n ' Make sure the RenameService's ActiveSession is still there\n Dim renameService = workspace.GetService(Of IInlineRenameService)()\n Assert.NotNull(renameService.ActiveSession)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n\n ' Simulate starting a debugging session\n Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService)\n debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run)\n\n ' Ensure the rename was committed\n Assert.Null(renameService.ActiveSession)\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameCommitsWhenExitingDebuggingBreakMode(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n ' Make sure the RenameService's ActiveSession is still there\n Dim renameService = workspace.GetService(Of IInlineRenameService)()\n Assert.NotNull(renameService.ActiveSession)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n\n ' Simulate ending break mode in the debugger (by stepping or continuing)\n Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService)\n debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run)\n\n ' Ensure the rename was committed\n Assert.Null(renameService.ActiveSession)\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n \n Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task\n ' Everything on the last line of main is parsed as a single invocation expression\n ' with CType(...) as the receiver and everything else as arguments.\n ' Rename doesn't expect to see CType as the receiver of an invocation.\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nModule Module1\n Sub Main()\n Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3}\n Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)(\n CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing)\n End Sub\nEnd Module\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"q\")\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"qp\")\n End Using\n End Function\n\n \n \n \n Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n int x;\n x = 2;\n void [|$$M|]() { }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Delete(New Span(caretPosition, 1))\n textBuffer.Insert(caretPosition, \"x\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"x\")\n End Using\n End Function\n\n \n \n \n Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nPublic Class Class1 \n Public Property [|$$Field1|] As Integer\nEnd Class \n\nPublic Class Class2 \n Public Shared Property DataSource As IEnumerable(Of Class1) \n Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = \n ( \n From data \n In DataSource \n Group By \n data.Field1\n Into Group1 = Group \n ).ToDictionary( \n Function(group) group.Field1,\n Function(group) group.Group1) \nEnd Class \n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Delete(New Span(caretPosition, 1))\n textBuffer.Insert(caretPosition, \"x\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"xield1\")\n End Using\n End Function\n\n \n \n \n Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nClass C\n Sub New(a As Action)\n End Sub\n\n Public ReadOnly Property Vm As C\n\n Public ReadOnly Property Crash As New C(Sub()\n Vm.Sav()\n End Sub)\n\n Public Function Sav$$() As Boolean\n Return False\n End Function\n\n Public Function Save() As Boolean\n Return False\n End Function\nEnd Class\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n ' Ensure the rename doesn't crash\n textBuffer.Insert(caretPosition, \"e\")\n session.Commit()\n End Using\n End Sub\n\n \n \n Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n partial class [|$$Goo|]\n {\n void Blah()\n {\n }\n }\n \n \n partial class Goo\n {\n void BlahBlah()\n {\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n partial class [|$$Test1|]\n {\n void Blah()\n {\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n }\n }\n\n class Test2\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n }\n }\n\n class Test1\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n enum [|$$Test1|]\n {\n One,\n Two,\n Three\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n interface [|$$Test1|]\n {\n void Blah();\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyUnsupportedFileRename(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n interface Test1\n {\n void [|$$Blah|]();\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n , host)\n\n ' Disable document changes to make sure file rename is not supported. \n ' Linked workspace files will report that applying changes to document\n ' info is not allowed; this is intended to mimic that behavior\n ' and make sure inline rename works as intended.\n workspace.CanApplyChangeDocument = False\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass [|$$Test1|]\n{\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Delete(New Span(caretPosition, 1))\n textBuffer.Insert(caretPosition, \"t\")\n\n session.Commit()\n VerifyFileName(workspace, \"test1\")\n End Using\n End Sub\n\n \n \n Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n textBuffer.Delete(New Span(caretPosition, \"Bar\".Length))\n\n Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False)\n Assert.False(committed)\n\n Await VerifyTagsAreCorrect(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class Test1\n {\n void Blah()\n {\n [|$$Test2|] t2 = new [|Test2|]();\n }\n }\n \n \n class Test2\n {\n }\n \n \n , host)\n\n Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = \"Test2.cs\")\n Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:=\"Test2\", renameTextPrefix:=\"Test2Changed\", renameFile:=True, fileToRename:=docToRename.Id)\n End Using\n End Function\n\n \n \n \n Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"D\")\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n record [|$$Goo|](int a);\n class C\n {\n [|Goo|] g;\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n record [|$$Goo|](int a) { }\n class C\n {\n [|Goo|] g;\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n record [|$$Goo|](int a) { }\n class C\n {\n [|Goo|] g = new [|Goo|](1);\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class C\n {\n void M()\n {\n _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ;\n }\n\n public C [|$$Goo|] { get; set; }\n public C Other { get; set; }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameInComment(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$MyClass|]\n {\n /// \n /// Initializes ;\n /// \n MyClass() \n {\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n session.ApplyReplacementText(\"Example\", True)\n session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True)\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"Example\")\n End Using\n End Function\n\n End Class\nEnd Namespace\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Threading\nImports Microsoft.CodeAnalysis.CodeActions\nImports Microsoft.CodeAnalysis.CodeRefactorings\nImports Microsoft.CodeAnalysis.Debugging\nImports Microsoft.CodeAnalysis.Editor.Host\nImports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking\nImports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces\nImports Microsoft.CodeAnalysis.IntroduceVariable\nImports Microsoft.CodeAnalysis.Notification\nImports Microsoft.CodeAnalysis.Options\nImports Microsoft.CodeAnalysis.Remote.Testing\nImports Microsoft.CodeAnalysis.Rename\nImports Microsoft.CodeAnalysis.Shared.Utilities\nImports Microsoft.VisualStudio.Text\n\nNamespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename\n <[UseExportProvider]>\n Public Class InlineRenameTests\n Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper\n\n Public Sub New(outputHelper As Abstractions.ITestOutputHelper)\n _outputHelper = outputHelper\n End Sub\n\n \n \n Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n object [|$$test|] = new object();\n var other = [|test|];\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"renamed\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"renamedtest\")\n End Using\n End Function\n\n \n \n Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n f = (int _, string [|$$_|]) => { _ = null; return 1; };\n }\n}\n ]]>\n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:=\"_\", renameTextPrefix:=\"change\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n , host)\n\n Dim options = workspace.CurrentSolution.Options\n workspace.TryApplyChanges(\n workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True)))\n\n Dim session = StartSession(workspace)\n\n Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n ' User could use copy & paste to enter invalid character\n textBuffer.Insert(selectedSpan, \"<>\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Test1<>\")\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n [|$$x|])\n {\n foreach (var (y1, y2) in [|x|])\n {\n }\n }\n void Deconstruct(out int i, out int j) { i = 0; j = 0; }\n}\n ]]>\n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"x\", \"change\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n x)\n {\n foreach (var (y1, y2) in x)\n {\n }\n var (z1, z2) = this;\n [|Deconstruct|](out var t1, out var t2);\n }\n void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; }\n}\n ]]>\n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"Deconstruct\", \"Changed\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n Await WaitForRename(workspace)\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace,\n originalTextToRename As String,\n renameTextPrefix As String,\n Optional renameOverloads As Boolean = False,\n Optional renameInStrings As Boolean = False,\n Optional renameInComments As Boolean = False,\n Optional renameFile As Boolean = False,\n Optional fileToRename As DocumentId = Nothing) As Task\n Dim optionSet = workspace.Options\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads)\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings)\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments)\n optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile)\n workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet))\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor\n renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix)\n\n Dim replacementText = renameTextPrefix + originalTextToRename\n Await WaitForRename(workspace)\n\n Await VerifyTagsAreCorrect(workspace, replacementText)\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, replacementText)\n\n If renameFile Then\n If fileToRename Is Nothing Then\n VerifyFileName(workspace, replacementText)\n Else\n VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText)\n End If\n End If\n End Function\n\n \n \n \n Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass Program\n{\n public void [|$$goo|]()\n {\n [|goo|]();\n }\n\n public void [|goo|]&lt;T&gt;()\n {\n [|goo|]&lt;T&gt;();\n }\n\n public void [|goo|](int i)\n {\n [|goo|](i);\n }\n}\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nImports System.Collections.Generic\nImports System.Linq\nImports System\n\nPublic Class Program\n Sub Main(args As String())\n\n End Sub\n\n Public Sub [|$$goo|]()\n [|goo|]()\n End Sub\n\n Public Sub [|goo|](of T)()\n [|goo|](of T)()\n End Sub\n\n Public Sub [|goo|](s As String)\n [|goo|](s)\n End Sub\n\n Public Shared Sub [|goo|](d As Double)\n [|goo|](d)\n End Sub\nEnd Class\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nPublic Class Program\n Sub Main([|$$args|] As String())\n\n End Sub\nEnd Class\n \n \n' args\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"args\", \"bar\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"Test1.vb\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n\n ' https://github.com/dotnet/roslyn/issues/36075\n ' VerifyFileRename(workspace, \"ABC\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n \n \n Proj2\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"F\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n \n \n Proj2\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"F\", \"AB\", renameInComments:=True)\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"AB\")\n\n Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = \"C.cs\"))\n End Using\n End Function\n\n \n \n \n \n Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n [|goo|]! \n public void [|$$goo|]()\n {\n // [|goo|] GOO\n /* [|goo|] */\n [|goo|]();\n\n var a = \"goo\";\n var b = $\"{1}goo{2}\";\n }\n\n public void goo(int i)\n {\n goo(i);\n }\n}]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n [|goo|]! \n public void [|$$goo|]()\n {\n // [|goo|] GOO\n /* [|goo|] */\n [|goo|]();\n\n var a = \"goo\";\n var b = $\"{1}goo{2}\";\n }\n\n public void [|goo|](int i)\n {\n [|goo|](i);\n }\n}]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True, renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n [|goo|]! \n public void [|$$goo|]()\n {\n // [|goo|] GOO\n /* [|goo|] */\n [|goo|]();\n\n var a = \"[|goo|]\";\n var b = $\"{1}[|goo|]{2}\";\n }\n\n public void goo(int i)\n {\n goo(i);\n }\n}]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True, renameInStrings:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n \n Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n\n\nClass Program\n\t''' <[|goo|]> [|goo|]! \n\tPublic Sub [|$$goo|]()\n\t\t' [|goo|] GOO\n\t\t' [|goo|]\n\t\t[|goo|]()\n\n\t\tDim a = \"goo\"\n\t\tDim b = $\"{1}goo{2}\"\n\tEnd Sub\n\n\tPublic Sub goo(i As Integer)\n\t\tgoo(i)\n\tEnd Sub\nEnd Class\n]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n\n\nClass Program\n\t''' <[|goo|]> [|goo|]! \n\tPublic Sub [|$$goo|]()\n\t\t' [|goo|] GOO\n\t\t' [|goo|]\n\t\t[|goo|]()\n\n\t\tDim a = \"goo\"\n\t\tDim b = $\"{1}goo{2}\"\n\tEnd Sub\n\n\tPublic Sub [|goo|](i As Integer)\n\t\t[|goo|](i)\n\tEnd Sub\nEnd Class\n]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameOverloads:=True, renameInComments:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n\n\nClass Program\n\t''' <[|goo|]> [|goo|]! \n\tPublic Sub [|$$goo|]()\n\t\t' [|goo|] GOO\n\t\t' [|goo|]\n\t\t[|goo|]()\n\n\t\tDim a = \"[|goo|]\"\n\t\tDim b = $\"{1}[|goo|]{2}\"\n\tEnd Sub\n\n\tPublic Sub goo(i As Integer)\n\t\tgoo(i)\n\tEnd Sub\nEnd Class\n]]>\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"goo\", \"bar\", renameInComments:=True, renameInStrings:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Sub SimpleEditAndCancel(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n Dim initialTextSnapshot = textBuffer.CurrentSnapshot\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Cancel()\n\n ' Assert the file is what it started as\n Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText())\n\n ' Assert the file name didn't change\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Sub\n\n \n \n \n Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$dynamic|]\n {\n void M()\n {\n [|dynamic|] d;\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"goo\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"goodynamic\")\n End Using\n End Function\n\n \n \n Public Sub ReadOnlyRegionsCreated(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class $$C\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n Dim buffer = workspace.Documents.Single().GetTextBuffer()\n\n ' Typing at the beginning and end of our span should work\n Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Assert.False(buffer.IsReadOnly(cursorPosition))\n Assert.False(buffer.IsReadOnly(cursorPosition + 1))\n\n ' Replacing our span should work\n Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1)))\n\n ' Make sure we can't type at the start or end\n Assert.True(buffer.IsReadOnly(0))\n Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length))\n\n session.Cancel()\n\n ' Assert the file name didn't change\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Sub\n\n \n \n \n Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n $$C c; class C { }\n \n , host)\n\n Dim session = StartSession(workspace)\n Dim buffer = workspace.Documents.Single().GetTextBuffer()\n\n ' Typing at the beginning and end of our span should work\n Assert.False(buffer.IsReadOnly(0))\n Assert.False(buffer.IsReadOnly(1))\n\n ' Replacing our span should work\n Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1)))\n\n session.Cancel()\n\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Sub\n\n \n \n Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost)\n Using result = RenameEngineResult.Create(_outputHelper,\n \n \n \n abstract class AAAA\n {\n public abstract void [|Goo|]();\n }\n\n class BBBB : AAAA\n {\n public override void [|Goo|]() { }\n }\n\n class DDDD : BBBB\n {\n public override void [|Goo|]() { }\n }\n class CCCC : AAAA\n {\n public override void [|$$Goo|]() { }\n }\n \n \n , host:=host, renameTo:=\"GooBar\")\n\n End Using\n End Sub\n\n \n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n VerifyFileName(workspace, \"BarTest1\")\n End Using\n End Function\n\n \n \n \n Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n\n session.Cancel()\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n Dim document = workspace.Documents.Single()\n Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)\n\n textBuffer.Insert(caretPosition, \"Bar\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"BarTest1\")\n Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)\n VerifyFileName(workspace, \"BarTest1\")\n\n textBuffer.Insert(caretPosition, \"Baz\")\n Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1)\n End Using\n End Function\n\n \n \n Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n ' Preview should not return null\n Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService)\n previewService.ReturnsNull = False\n\n Dim session = StartSession(workspace)\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit(previewChanges:=True)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n Assert.True(previewService.Called)\n Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title)\n Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, \"Goo\", \"BarGoo\"), previewService.Description)\n Assert.Equal(\"Goo\", previewService.TopLevelName)\n Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph)\n End Using\n End Function\n\n \n \n Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService)\n previewService.ReturnsNull = True\n\n Dim session = StartSession(workspace)\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit(previewChanges:=True)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n Assert.True(previewService.Called)\n\n ' Session should still be up; type some more\n caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n textBuffer.Insert(caretPosition, \"Cat\")\n\n previewService.ReturnsNull = False\n previewService.Called = False\n session.Commit(previewChanges:=True)\n Await VerifyTagsAreCorrect(workspace, \"CatBarGoo\")\n Assert.True(previewService.Called)\n\n VerifyFileName(workspace, \"Test1.cs\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nClass C\n Sub [|M$$|]()\n End Sub\n\n Sub Test()\n#If Proj1 Then\n [|M|]()\n#End If\n#If Proj2 Then\n [|M|]()\n#End If\n End Sub\nEnd Class\n \n \n \n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"o\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Mo\")\n\n textBuffer.Insert(caretPosition + 1, \"w\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Mow\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Mow\")\n End Using\n End Function\n\n \n \n Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nClass C\n Dim [|m$$|] As Integer\n\n Sub Test()\n#If Proj1 Then\n Dim x = [|m|]\n#End If\n#If Proj2 Then\n Dim x = [|m|]\n#End If\n End Sub\nEnd Class\n \n \n \n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"ma\")\n\n textBuffer.Insert(caretPosition + 1, \"w\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"maw\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"maw\")\n End Using\n End Function\n\n \n \n \n \n Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void M()\n {\n var z = {|introducelocal:5 + 5|};\n var q = [|x$$|];\n }\n\n int [|x|];\n}\n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n textBuffer.Insert(caretPosition, \"yz\")\n Await WaitForRename(workspace)\n\n ' Invoke a CodeAction\n Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider()\n Dim actions = New List(Of CodeAction)\n Dim context = New CodeRefactoringContext(\n workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id),\n workspace.Documents.Single().AnnotatedSpans()(\"introducelocal\").Single(),\n Sub(a) actions.Add(a),\n CancellationToken.None)\n\n workspace.Documents.Single().AnnotatedSpans.Clear()\n introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait()\n\n Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService)\n\n Dim actualSeverity As NotificationSeverity = Nothing\n Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback)\n notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity\n\n editHandler.Apply(\n workspace,\n workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id),\n Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None),\n \"unused\",\n New ProgressTracker(),\n CancellationToken.None)\n\n ' CodeAction should be rejected\n Assert.Equal(NotificationSeverity.Error, actualSeverity)\n Assert.Equal(\"\nclass C\n{\n void M()\n {\n var z = 5 + 5;\n var q = xyz;\n }\n\n int xyz;\n}\",\n textBuffer.CurrentSnapshot.GetText())\n\n ' Rename should still be active\n Await VerifyTagsAreCorrect(workspace, \"xyz\")\n\n textBuffer.Insert(caretPosition + 2, \"q\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"xyzq\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M$$|]()\n {\n nameof([|M|]).ToString();\n }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M|]()\n {\n nameof([|M$$|]).ToString();\n }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M$$|]()\n {\n nameof(M).ToString();\n }\n\n void M(int x) { }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|M|]()\n {\n nameof([|M$$|]).ToString();\n }\n\n void [|M|](int x) { }\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.First().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"a\")\n Await WaitForRename(workspace)\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n\n session.Commit()\n Await VerifyTagsAreCorrect(workspace, \"Ma\")\n End Using\n End Function\n\n \n \n Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass C\n{\n void [|$$M|]()\n {\n nameof([|M|]).ToString();\n }\n\n void [|M|](int x) { }\n}\n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"M\", \"Sa\", renameOverloads:=True)\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameCommitsWhenDebuggingStarts(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n ' Make sure the RenameService's ActiveSession is still there\n Dim renameService = workspace.GetService(Of IInlineRenameService)()\n Assert.NotNull(renameService.ActiveSession)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n\n ' Simulate starting a debugging session\n Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService)\n debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run)\n\n ' Ensure the rename was committed\n Assert.Null(renameService.ActiveSession)\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n \n Public Async Function RenameCommitsWhenExitingDebuggingBreakMode(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n [|Goo|] f = new [|Goo|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n ' Make sure the RenameService's ActiveSession is still there\n Dim renameService = workspace.GetService(Of IInlineRenameService)()\n Assert.NotNull(renameService.ActiveSession)\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n\n ' Simulate ending break mode in the debugger (by stepping or continuing)\n Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService)\n debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run)\n\n ' Ensure the rename was committed\n Assert.Null(renameService.ActiveSession)\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n \n Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task\n ' Everything on the last line of main is parsed as a single invocation expression\n ' with CType(...) as the receiver and everything else as arguments.\n ' Rename doesn't expect to see CType as the receiver of an invocation.\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nModule Module1\n Sub Main()\n Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3}\n Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)(\n CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing)\n End Sub\nEnd Module\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"q\")\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"qp\")\n End Using\n End Function\n\n \n \n \n Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n int x;\n x = 2;\n void [|$$M|]() { }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Delete(New Span(caretPosition, 1))\n textBuffer.Insert(caretPosition, \"x\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"x\")\n End Using\n End Function\n\n \n \n \n Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nPublic Class Class1 \n Public Property [|$$Field1|] As Integer\nEnd Class \n\nPublic Class Class2 \n Public Shared Property DataSource As IEnumerable(Of Class1) \n Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = \n ( \n From data \n In DataSource \n Group By \n data.Field1\n Into Group1 = Group \n ).ToDictionary( \n Function(group) group.Field1,\n Function(group) group.Group1) \nEnd Class \n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Delete(New Span(caretPosition, 1))\n textBuffer.Insert(caretPosition, \"x\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"xield1\")\n End Using\n End Function\n\n \n \n \n Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nClass C\n Sub New(a As Action)\n End Sub\n\n Public ReadOnly Property Vm As C\n\n Public ReadOnly Property Crash As New C(Sub()\n Vm.Sav()\n End Sub)\n\n Public Function Sav$$() As Boolean\n Return False\n End Function\n\n Public Function Save() As Boolean\n Return False\n End Function\nEnd Class\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n ' Ensure the rename doesn't crash\n textBuffer.Insert(caretPosition, \"e\")\n session.Commit()\n End Using\n End Sub\n\n \n \n Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n partial class [|$$Goo|]\n {\n void Blah()\n {\n }\n }\n \n \n partial class Goo\n {\n void BlahBlah()\n {\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n partial class [|$$Test1|]\n {\n void Blah()\n {\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n }\n }\n\n class Test2\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Goo|]\n {\n void Blah()\n {\n }\n }\n\n class Test1\n {\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n enum [|$$Test1|]\n {\n One,\n Two,\n Three\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n interface [|$$Test1|]\n {\n void Blah();\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyUnsupportedFileRename(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n interface Test1\n {\n void [|$$Blah|]();\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n \n , host)\n\n ' Disable document changes to make sure file rename is not supported. \n ' Linked workspace files will report that applying changes to document\n ' info is not allowed; this is intended to mimic that behavior\n ' and make sure inline rename works as intended.\n workspace.CanApplyChangeDocument = False\n\n Dim session = StartSession(workspace)\n\n Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo)\n End Using\n End Sub\n\n \n \n Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost)\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \nclass [|$$Test1|]\n{\n}\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Delete(New Span(caretPosition, 1))\n textBuffer.Insert(caretPosition, \"t\")\n\n session.Commit()\n VerifyFileName(workspace, \"test1\")\n End Using\n End Sub\n\n \n \n Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$Test1|]\n {\n void Blah()\n {\n [|Test1|] f = new [|Test1|]();\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n textBuffer.Delete(New Span(caretPosition, \"Bar\".Length))\n\n Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False)\n Assert.False(committed)\n\n Await VerifyTagsAreCorrect(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class Test1\n {\n void Blah()\n {\n [|$$Test2|] t2 = new [|Test2|]();\n }\n }\n \n \n class Test2\n {\n }\n \n \n , host)\n\n Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = \"Test2.cs\")\n Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:=\"Test2\", renameTextPrefix:=\"Test2Changed\", renameFile:=True, fileToRename:=docToRename.Id)\n End Using\n End Function\n\n \n \n \n Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n \n \n \n , host)\n\n Await VerifyRenameOptionChangedSessionCommit(workspace, \"C\", \"D\")\n VerifyFileName(workspace, \"Test1\")\n End Using\n End Function\n\n \n \n Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n record [|$$Goo|](int a);\n class C\n {\n [|Goo|] g;\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n record [|$$Goo|](int a) { }\n class C\n {\n [|Goo|] g;\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n record [|$$Goo|](int a) { }\n class C\n {\n [|Goo|] g = new [|Goo|](1);\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class C\n {\n void M()\n {\n _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ;\n }\n\n public C [|$$Goo|] { get; set; }\n public C Other { get; set; }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n ' Type a bit in the file\n Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value\n Dim textBuffer = workspace.Documents.Single().GetTextBuffer()\n\n textBuffer.Insert(caretPosition, \"Bar\")\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"BarGoo\")\n End Using\n End Function\n\n \n \n Public Async Function RenameInComment(host As RenameTestHost) As Task\n Using workspace = CreateWorkspaceWithWaiter(\n \n \n \n class [|$$MyClass|]\n {\n /// \n /// Initializes ;\n /// \n MyClass() \n {\n }\n }\n \n \n , host)\n\n Dim session = StartSession(workspace)\n\n session.ApplyReplacementText(\"Example\", True)\n session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True)\n\n session.Commit()\n\n Await VerifyTagsAreCorrect(workspace, \"Example\")\n End Using\n End Function\n\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":432,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Test/Progression/IsCalledByGraphQueryTests.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Threading.Tasks\nImports Microsoft.CodeAnalysis.Test.Utilities\nImports Microsoft.VisualStudio.GraphModel\nImports Microsoft.VisualStudio.LanguageServices.Implementation.Progression\nImports Roslyn.Test.Utilities\n\nNamespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression\n \n Public Class IsCalledByGraphQueryTests\n \n Public Async Function IsCalledBySimpleTests() As Task\n Using testState = ProgressionTestState.Create(\n \n \n \n class A\n {\n public $$A() { }\n public virtual void Run() { }\n }\n\n class B : A\n {\n public B() { }\n override public void Run() { var x = new A(); x.Run(); }\n }\n\n class C\n {\n public C() { }\n public void Goo()\n {\n var x = new B();\n x.Run();\n }\n }\n \n \n )\n\n Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()\n Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New IsCalledByGraphQuery(), GraphContextDirection.Target)\n\n AssertSimplifiedGraphIs(\n outputContext.Graph,\n \n \n \n \n \n \n \n \n \n \n \n )\n End Using\n End Function\n End Class\nEnd Namespace\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Threading.Tasks\nImports Microsoft.CodeAnalysis.Test.Utilities\nImports Microsoft.VisualStudio.GraphModel\nImports Microsoft.VisualStudio.LanguageServices.Implementation.Progression\nImports Roslyn.Test.Utilities\n\nNamespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression\n \n Public Class IsCalledByGraphQueryTests\n \n Public Async Function IsCalledBySimpleTests() As Task\n Using testState = ProgressionTestState.Create(\n \n \n \n class A\n {\n public $$A() { }\n public virtual void Run() { }\n }\n\n class B : A\n {\n public B() { }\n override public void Run() { var x = new A(); x.Run(); }\n }\n\n class C\n {\n public C() { }\n public void Goo()\n {\n var x = new B();\n x.Run();\n }\n }\n \n \n )\n\n Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()\n Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New IsCalledByGraphQuery(), GraphContextDirection.Target)\n\n AssertSimplifiedGraphIs(\n outputContext.Graph,\n \n \n \n \n \n \n \n \n \n \n \n )\n End Using\n End Function\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":433,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Dependencies/Collections/Internal/xlf/Strings.ko.xlf"},"before_content":{"kind":"string","value":"\n\n \n \n \n Destination array is not long enough to copy all the items in the collection. Check array index and length.\n 대상 배열이 컬렉션의 모든 항목을 복사하기에 충분히 길지 않습니다. 배열 인덱스와 길이를 확인하세요.\n \n \n \n Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.\n IComparer.Compare() 메서드가 일관성 없는 결과를 반환하므로 정렬할 수 없습니다. 값이 자신과 같은지 비교하지 않거나 한 값이 다른 값과 반복해서 비교되어 다른 결과를 생성합니다. IComparer: '{0}'.\n \n \n \n Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.\n 해시 테이블 용량에 오버플로가 발생하여 음수가 되었습니다. 로드 비율, 용량 및 테이블의 현재 크기를 확인하십시오.\n \n \n \n The given key '{0}' was not present in the dictionary.\n 지정된 키 '{0}'이(가) 사전에 없습니다.\n \n \n \n Destination array was not long enough. Check the destination index, length, and the array's lower bounds.\n 대상 배열의 길이가 짧습니다. 대상 인덱스, 길이, 배열의 하한을 확인하세요.\n \n \n \n Source array was not long enough. Check the source index, length, and the array's lower bounds.\n 소스 배열의 길이가 짧습니다. 소스 인덱스, 길이, 배열의 하한을 확인하세요.\n \n \n \n The lower bound of target array must be zero.\n 대상 배열의 하한은 0이어야 합니다.\n \n \n \n Only single dimensional arrays are supported for the requested action.\n 요청한 동작에 대해 1차원 배열만 지원됩니다.\n \n \n \n The value \"{0}\" is not of type \"{1}\" and cannot be used in this generic collection.\n \"{0}\" 값은 \"{1}\" 형식이 아니므로 이 제네릭 컬렉션에 사용할 수 없습니다.\n \n \n \n Object is not a array with the same number of elements as the array to compare it to.\n 개체가 비교할 배열과 요소 수가 같은 배열이 아닙니다.\n \n \n \n Number was less than the array's lower bound in the first dimension.\n 숫자가 첫째 차원에서 배열의 하한보다 작습니다.\n \n \n \n Larger than collection size.\n 컬렉션 크기보다 큽니다.\n \n \n \n Count must be positive and count must refer to a location within the string/array/collection.\n 개수는 양수여야 하고 문자열/배열/컬렉션 내의 위치를 참조해야 합니다.\n \n \n \n Index was out of range. Must be non-negative and less than the size of the collection.\n 인덱스가 범위를 벗어났습니다. 인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다.\n \n \n \n Index must be within the bounds of the List.\n 인덱스는 목록의 범위 내에 있어야 합니다.\n \n \n \n Non-negative number required.\n 음수가 아닌 수가 필요합니다.\n \n \n \n capacity was less than the current size.\n 용량이 현재 크기보다 작습니다.\n \n \n \n An item with the same key has already been added. Key: {0}\n 동일한 키를 사용하는 항목이 이미 추가되었습니다. 키: {0}\n \n \n \n Target array type is not compatible with the type of items in the collection.\n 대상 배열 형식이 컬렉션의 항목 형식과 호환되지 않습니다.\n \n \n \n Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.\n 오프셋 및 길이가 배열의 범위를 벗어났거나 카운트가 인덱스부터 소스 컬렉션 끝까지의 요소 수보다 큽니다.\n \n \n \n Cannot find the old value\n Cannot find the old value\n \n \n \n Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.\n 비동시 컬렉션을 변경하는 작업에는 단독 액세스 권한이 있어야 합니다. 이 컬렉션에 대해 동시 업데이트가 수행되어 해당 상태가 손상되었습니다. 컬렉션의 상태가 더 이상 올바르지 않습니다.\n \n \n \n Collection was modified; enumeration operation may not execute.\n 컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.\n \n \n \n Enumeration has either not started or has already finished.\n 열거가 시작되지 않았거나 이미 완료되었습니다.\n \n \n \n Failed to compare two elements in the array.\n 배열의 두 요소를 비교하지 못했습니다.\n \n \n \n Collection was of a fixed size.\n 컬렉션이 고정 크기입니다.\n \n \n \n Mutating a key collection derived from a dictionary is not allowed.\n 사전에서 파생된 키 컬렉션은 변경할 수 없습니다.\n \n \n \n Mutating a value collection derived from a dictionary is not allowed.\n 사전에서 파생된 값 컬렉션은 변경할 수 없습니다.\n \n \n \n The specified arrays must have the same number of dimensions.\n 지정한 배열의 차수가 같아야 합니다.\n \n \n \n \n"},"after_content":{"kind":"string","value":"\n\n \n \n \n Destination array is not long enough to copy all the items in the collection. Check array index and length.\n 대상 배열이 컬렉션의 모든 항목을 복사하기에 충분히 길지 않습니다. 배열 인덱스와 길이를 확인하세요.\n \n \n \n Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.\n IComparer.Compare() 메서드가 일관성 없는 결과를 반환하므로 정렬할 수 없습니다. 값이 자신과 같은지 비교하지 않거나 한 값이 다른 값과 반복해서 비교되어 다른 결과를 생성합니다. IComparer: '{0}'.\n \n \n \n Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.\n 해시 테이블 용량에 오버플로가 발생하여 음수가 되었습니다. 로드 비율, 용량 및 테이블의 현재 크기를 확인하십시오.\n \n \n \n The given key '{0}' was not present in the dictionary.\n 지정된 키 '{0}'이(가) 사전에 없습니다.\n \n \n \n Destination array was not long enough. Check the destination index, length, and the array's lower bounds.\n 대상 배열의 길이가 짧습니다. 대상 인덱스, 길이, 배열의 하한을 확인하세요.\n \n \n \n Source array was not long enough. Check the source index, length, and the array's lower bounds.\n 소스 배열의 길이가 짧습니다. 소스 인덱스, 길이, 배열의 하한을 확인하세요.\n \n \n \n The lower bound of target array must be zero.\n 대상 배열의 하한은 0이어야 합니다.\n \n \n \n Only single dimensional arrays are supported for the requested action.\n 요청한 동작에 대해 1차원 배열만 지원됩니다.\n \n \n \n The value \"{0}\" is not of type \"{1}\" and cannot be used in this generic collection.\n \"{0}\" 값은 \"{1}\" 형식이 아니므로 이 제네릭 컬렉션에 사용할 수 없습니다.\n \n \n \n Object is not a array with the same number of elements as the array to compare it to.\n 개체가 비교할 배열과 요소 수가 같은 배열이 아닙니다.\n \n \n \n Number was less than the array's lower bound in the first dimension.\n 숫자가 첫째 차원에서 배열의 하한보다 작습니다.\n \n \n \n Larger than collection size.\n 컬렉션 크기보다 큽니다.\n \n \n \n Count must be positive and count must refer to a location within the string/array/collection.\n 개수는 양수여야 하고 문자열/배열/컬렉션 내의 위치를 참조해야 합니다.\n \n \n \n Index was out of range. Must be non-negative and less than the size of the collection.\n 인덱스가 범위를 벗어났습니다. 인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다.\n \n \n \n Index must be within the bounds of the List.\n 인덱스는 목록의 범위 내에 있어야 합니다.\n \n \n \n Non-negative number required.\n 음수가 아닌 수가 필요합니다.\n \n \n \n capacity was less than the current size.\n 용량이 현재 크기보다 작습니다.\n \n \n \n An item with the same key has already been added. Key: {0}\n 동일한 키를 사용하는 항목이 이미 추가되었습니다. 키: {0}\n \n \n \n Target array type is not compatible with the type of items in the collection.\n 대상 배열 형식이 컬렉션의 항목 형식과 호환되지 않습니다.\n \n \n \n Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.\n 오프셋 및 길이가 배열의 범위를 벗어났거나 카운트가 인덱스부터 소스 컬렉션 끝까지의 요소 수보다 큽니다.\n \n \n \n Cannot find the old value\n Cannot find the old value\n \n \n \n Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.\n 비동시 컬렉션을 변경하는 작업에는 단독 액세스 권한이 있어야 합니다. 이 컬렉션에 대해 동시 업데이트가 수행되어 해당 상태가 손상되었습니다. 컬렉션의 상태가 더 이상 올바르지 않습니다.\n \n \n \n Collection was modified; enumeration operation may not execute.\n 컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.\n \n \n \n Enumeration has either not started or has already finished.\n 열거가 시작되지 않았거나 이미 완료되었습니다.\n \n \n \n Failed to compare two elements in the array.\n 배열의 두 요소를 비교하지 못했습니다.\n \n \n \n Collection was of a fixed size.\n 컬렉션이 고정 크기입니다.\n \n \n \n Mutating a key collection derived from a dictionary is not allowed.\n 사전에서 파생된 키 컬렉션은 변경할 수 없습니다.\n \n \n \n Mutating a value collection derived from a dictionary is not allowed.\n 사전에서 파생된 값 컬렉션은 변경할 수 없습니다.\n \n \n \n The specified arrays must have the same number of dimensions.\n 지정한 배열의 차수가 같아야 합니다.\n \n \n \n \n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":434,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Tools/IdeCoreBenchmarks/FindReferencesBenchmarks.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing AnalyzerRunner;\nusing BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Diagnosers;\nusing Microsoft.Build.Locator;\nusing Microsoft.CodeAnalysis.FindSymbols;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.MSBuild;\nusing Microsoft.CodeAnalysis.Storage;\n\nnamespace IdeCoreBenchmarks\n{\n [MemoryDiagnoser]\n public class FindReferencesBenchmarks\n {\n [Benchmark]\n public async Task RunFindReferences()\n {\n try\n {\n // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK\n // installations on .NET Core. We use the one with the most recent version.\n var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First();\n\n MSBuildLocator.RegisterInstance(msBuildInstance);\n\n var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName);\n var solutionPath = Path.Combine(roslynRoot, @\"C:\\github\\roslyn\\Compilers.sln\");\n\n if (!File.Exists(solutionPath))\n throw new ArgumentException(\"Couldn't find Compilers.sln\");\n\n Console.Write(\"Found Compilers.sln: \" + Process.GetCurrentProcess().Id);\n\n var assemblies = MSBuildMefHostServices.DefaultAssemblies\n .Add(typeof(AnalyzerRunnerHelper).Assembly)\n .Add(typeof(FindReferencesBenchmarks).Assembly);\n var services = MefHostServices.Create(assemblies);\n\n var workspace = MSBuildWorkspace.Create(new Dictionary\n {\n // Use the latest language version to force the full set of available analyzers to run on the project.\n { \"LangVersion\", \"9.0\" },\n }, services);\n\n if (workspace == null)\n throw new ArgumentException(\"Couldn't create workspace\");\n\n workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options\n .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite)));\n\n Console.WriteLine(\"Opening roslyn. Attach to: \" + Process.GetCurrentProcess().Id);\n\n var start = DateTime.Now;\n var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result;\n Console.WriteLine(\"Finished opening roslyn: \" + (DateTime.Now - start));\n\n // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we\n // perform, including seeing how big the initial string table is.\n var storageService = workspace.Services.GetService();\n if (storageService == null)\n throw new ArgumentException(\"Couldn't get storage service\");\n\n using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None))\n {\n Console.WriteLine();\n }\n\n // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects\n // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the\n // same.\n var project = solution.Projects.First(p => p.AssemblyName == \"Microsoft.CodeAnalysis\");\n\n start = DateTime.Now;\n var compilation = await project.GetCompilationAsync();\n Console.WriteLine(\"Time to get first compilation: \" + (DateTime.Now - start));\n var type = compilation.GetTypeByMetadataName(\"Microsoft.CodeAnalysis.SyntaxToken\");\n if (type == null)\n throw new Exception(\"Couldn't find type\");\n\n Console.WriteLine(\"Starting find-refs\");\n start = DateTime.Now;\n var references = await SymbolFinder.FindReferencesAsync(type, solution);\n Console.WriteLine(\"Time to find-refs: \" + (DateTime.Now - start));\n var refList = references.ToList();\n Console.WriteLine($\"References count: {refList.Count}\");\n var locations = refList.SelectMany(r => r.Locations).ToList();\n Console.WriteLine($\"Locations count: {locations.Count}\");\n }\n catch (ReflectionTypeLoadException ex)\n {\n foreach (var ex2 in ex.LoaderExceptions)\n Console.WriteLine(ex2);\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing AnalyzerRunner;\nusing BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Diagnosers;\nusing Microsoft.Build.Locator;\nusing Microsoft.CodeAnalysis.FindSymbols;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.MSBuild;\nusing Microsoft.CodeAnalysis.Storage;\n\nnamespace IdeCoreBenchmarks\n{\n [MemoryDiagnoser]\n public class FindReferencesBenchmarks\n {\n [Benchmark]\n public async Task RunFindReferences()\n {\n try\n {\n // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK\n // installations on .NET Core. We use the one with the most recent version.\n var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First();\n\n MSBuildLocator.RegisterInstance(msBuildInstance);\n\n var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName);\n var solutionPath = Path.Combine(roslynRoot, @\"C:\\github\\roslyn\\Compilers.sln\");\n\n if (!File.Exists(solutionPath))\n throw new ArgumentException(\"Couldn't find Compilers.sln\");\n\n Console.Write(\"Found Compilers.sln: \" + Process.GetCurrentProcess().Id);\n\n var assemblies = MSBuildMefHostServices.DefaultAssemblies\n .Add(typeof(AnalyzerRunnerHelper).Assembly)\n .Add(typeof(FindReferencesBenchmarks).Assembly);\n var services = MefHostServices.Create(assemblies);\n\n var workspace = MSBuildWorkspace.Create(new Dictionary\n {\n // Use the latest language version to force the full set of available analyzers to run on the project.\n { \"LangVersion\", \"9.0\" },\n }, services);\n\n if (workspace == null)\n throw new ArgumentException(\"Couldn't create workspace\");\n\n workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options\n .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite)));\n\n Console.WriteLine(\"Opening roslyn. Attach to: \" + Process.GetCurrentProcess().Id);\n\n var start = DateTime.Now;\n var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result;\n Console.WriteLine(\"Finished opening roslyn: \" + (DateTime.Now - start));\n\n // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we\n // perform, including seeing how big the initial string table is.\n var storageService = workspace.Services.GetService();\n if (storageService == null)\n throw new ArgumentException(\"Couldn't get storage service\");\n\n using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None))\n {\n Console.WriteLine();\n }\n\n // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects\n // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the\n // same.\n var project = solution.Projects.First(p => p.AssemblyName == \"Microsoft.CodeAnalysis\");\n\n start = DateTime.Now;\n var compilation = await project.GetCompilationAsync();\n Console.WriteLine(\"Time to get first compilation: \" + (DateTime.Now - start));\n var type = compilation.GetTypeByMetadataName(\"Microsoft.CodeAnalysis.SyntaxToken\");\n if (type == null)\n throw new Exception(\"Couldn't find type\");\n\n Console.WriteLine(\"Starting find-refs\");\n start = DateTime.Now;\n var references = await SymbolFinder.FindReferencesAsync(type, solution);\n Console.WriteLine(\"Time to find-refs: \" + (DateTime.Now - start));\n var refList = references.ToList();\n Console.WriteLine($\"References count: {refList.Count}\");\n var locations = refList.SelectMany(r => r.Locations).ToList();\n Console.WriteLine($\"Locations count: {locations.Count}\");\n }\n catch (ReflectionTypeLoadException ex)\n {\n foreach (var ex2 in ex.LoaderExceptions)\n Console.WriteLine(ex2);\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":435,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Desktop.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\n#if !NETCOREAPP\n\nusing System;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Loads analyzer assemblies from their original locations in the file system.\n /// Assemblies will only be loaded from the locations specified when the loader\n /// is instantiated.\n /// \n /// \n /// This type is meant to be used in scenarios where it is OK for the analyzer\n /// assemblies to be locked on disk for the lifetime of the host; for example,\n /// csc.exe and vbc.exe. In scenarios where support for updating or deleting\n /// the analyzer on disk is required a different loader should be used.\n /// \n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n private int _hookedAssemblyResolve;\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0)\n {\n AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n }\n\n var pathToLoad = GetPathToLoad(fullPath);\n return Assembly.LoadFrom(pathToLoad);\n }\n\n private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n try\n {\n return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name));\n }\n catch\n {\n return null;\n }\n }\n }\n}\n\n#endif\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\n#if !NETCOREAPP\n\nusing System;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Loads analyzer assemblies from their original locations in the file system.\n /// Assemblies will only be loaded from the locations specified when the loader\n /// is instantiated.\n /// \n /// \n /// This type is meant to be used in scenarios where it is OK for the analyzer\n /// assemblies to be locked on disk for the lifetime of the host; for example,\n /// csc.exe and vbc.exe. In scenarios where support for updating or deleting\n /// the analyzer on disk is required a different loader should be used.\n /// \n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n private int _hookedAssemblyResolve;\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0)\n {\n AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n }\n\n var pathToLoad = GetPathToLoad(fullPath);\n return Assembly.LoadFrom(pathToLoad);\n }\n\n private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n try\n {\n return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name));\n }\n catch\n {\n return null;\n }\n }\n }\n}\n\n#endif\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":436,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/CodeModel/ICodeModelInstanceFactory.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel\n{\n internal interface ICodeModelInstanceFactory\n {\n /// \n /// Requests the project system to create a through the project system.\n /// \n /// \n /// This is sometimes necessary because it's possible to go from one to another,\n /// but the language service can't create that instance directly, as it doesn't know what the \n /// member should be. The expectation is the implementer of this will do what is necessary and call back into \n /// handing it the appropriate parent.\n EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath);\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel\n{\n internal interface ICodeModelInstanceFactory\n {\n /// \n /// Requests the project system to create a through the project system.\n /// \n /// \n /// This is sometimes necessary because it's possible to go from one to another,\n /// but the language service can't create that instance directly, as it doesn't know what the \n /// member should be. The expectation is the implementer of this will do what is necessary and call back into \n /// handing it the appropriate parent.\n EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":437,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56473,"string":"56,473"},"pr_title":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function"},"pr_description":{"kind":"string","value":"Fixes https://github.com/dotnet/roslyn/issues/53179"},"author":{"kind":"string","value":"jcouv"},"date_created":{"kind":"timestamp","value":"2021-09-17T03:29:26Z","string":"2021-09-17T03:29:26Z"},"date_merged":{"kind":"timestamp","value":"2021-09-17T21:32:30Z","string":"2021-09-17T21:32:30Z"},"previous_commit":{"kind":"string","value":"e3756cc7c7229e1509f27ab3de712c59f634c554"},"pr_commit":{"kind":"string","value":"a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d"},"query":{"kind":"string","value":"Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage.Accessor.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.SQLite.Interop;\nusing Microsoft.CodeAnalysis.SQLite.v2.Interop;\nusing Microsoft.CodeAnalysis.Storage;\nusing Roslyn.Utilities;\n\n#if DEBUG\nusing System.Diagnostics;\n#endif\n\nnamespace Microsoft.CodeAnalysis.SQLite.v2\n{\n using static SQLitePersistentStorageConstants;\n\n internal partial class SQLitePersistentStorage\n {\n /// \n /// Abstracts out access to specific tables in the DB. This allows us to share overall\n /// logic around cancellation/pooling/error-handling/etc, while still hitting different\n /// db tables.\n /// \n private abstract class Accessor\n {\n protected readonly SQLitePersistentStorage Storage;\n\n // Cache the statement strings we want to execute per accessor. This way we avoid\n // allocating these strings each time we execute a command. We also cache the prepared\n // statements (at the connection level) we make for each of these strings. That way we\n // only incur the parsing cost once. After that, we can use the same prepared statements\n // and just bind the appropriate values it needs into it.\n //\n // values like 0, 1, 2 in the name are the `?`s in the sql string that will need to be\n // bound to runtime values appropriately when executed.\n\n private readonly string _select_rowid_from_main_table_where_0;\n private readonly string _select_rowid_from_writecache_table_where_0;\n private readonly string _insert_or_replace_into_writecache_table_values_0_1_2;\n private readonly string _delete_from_writecache_table;\n private readonly string _insert_or_replace_into_main_table_select_star_from_writecache_table;\n\n public Accessor(SQLitePersistentStorage storage)\n {\n var main = Database.Main.GetName();\n var writeCache = Database.WriteCache.GetName();\n\n var dataTableName = this.Table switch\n {\n Table.Solution => SolutionDataTableName,\n Table.Project => ProjectDataTableName,\n Table.Document => DocumentDataTableName,\n _ => throw ExceptionUtilities.UnexpectedValue(this.Table),\n };\n\n Storage = storage;\n _select_rowid_from_main_table_where_0 = $@\"select rowid from {main}.{dataTableName} where \"\"{DataIdColumnName}\"\" = ?\";\n _select_rowid_from_writecache_table_where_0 = $@\"select rowid from {writeCache}.{dataTableName} where \"\"{DataIdColumnName}\"\" = ?\";\n _insert_or_replace_into_writecache_table_values_0_1_2 = $@\"insert or replace into {writeCache}.{dataTableName}(\"\"{DataIdColumnName}\"\",\"\"{ChecksumColumnName}\"\",\"\"{DataColumnName}\"\") values (?,?,?)\";\n _delete_from_writecache_table = $\"delete from {writeCache}.{dataTableName};\";\n _insert_or_replace_into_main_table_select_star_from_writecache_table = $\"insert or replace into {main}.{dataTableName} select * from {writeCache}.{dataTableName};\";\n }\n\n protected abstract Table Table { get; }\n\n /// \n /// Gets the internal sqlite db-id (effectively the row-id for the doc or proj table, or just the string-id\n /// for the solution table) for the provided caller key. This db-id will be looked up and returned if a\n /// mapping already exists for it in the db. Otherwise, a guaranteed unique id will be created for it and\n /// stored in the db for the future. This allows all associated data to be cheaply associated with the \n /// simple ID, avoiding lots of db bloat if we used the full in numerous places.\n /// \n /// Whether or not the caller owns the write lock and thus is ok with the DB id\n /// being generated and stored for this component key when it currently does not exist. If then failing to find the key will result in being returned.\n /// \n protected abstract bool TryGetDatabaseId(SqlConnection connection, TKey key, bool allowWrite, out TDatabaseId dataId);\n protected abstract void BindFirstParameter(SqlStatement statement, TDatabaseId dataId);\n protected abstract TWriteQueueKey GetWriteQueueKey(TKey key);\n protected abstract bool TryGetRowId(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId);\n\n [PerformanceSensitive(\"https://github.com/dotnet/roslyn/issues/36114\", AllowCaptures = false)]\n public Task ChecksumMatchesAsync(TKey key, Checksum checksum, CancellationToken cancellationToken)\n => Storage.PerformReadAsync(\n static t => t.self.ChecksumMatches(t.key, t.checksum, t.cancellationToken),\n (self: this, key, checksum, cancellationToken), cancellationToken);\n\n private bool ChecksumMatches(TKey key, Checksum checksum, CancellationToken cancellationToken)\n {\n var optional = ReadColumn(\n key,\n static (self, connection, database, rowId) => self.ReadChecksum(connection, database, rowId),\n this,\n cancellationToken);\n return optional.HasValue && checksum == optional.Value;\n }\n\n [PerformanceSensitive(\"https://github.com/dotnet/roslyn/issues/36114\", AllowCaptures = false)]\n public Task ReadStreamAsync(TKey key, Checksum? checksum, CancellationToken cancellationToken)\n => Storage.PerformReadAsync(\n static t => t.self.ReadStream(t.key, t.checksum, t.cancellationToken),\n (self: this, key, checksum, cancellationToken), cancellationToken);\n\n [PerformanceSensitive(\"https://github.com/dotnet/roslyn/issues/36114\", AllowCaptures = false)]\n private Stream? ReadStream(TKey key, Checksum? checksum, CancellationToken cancellationToken)\n {\n var optional = ReadColumn(\n key,\n static (t, connection, database, rowId) => t.self.ReadDataBlob(connection, database, rowId, t.checksum),\n (self: this, checksum),\n cancellationToken);\n\n Contract.ThrowIfTrue(optional.HasValue && optional.Value == null);\n return optional.HasValue ? optional.Value : null;\n }\n\n private Optional ReadColumn(\n TKey key,\n Func> readColumn,\n TData data,\n CancellationToken cancellationToken)\n {\n // We're reading. All current scenarios have this happening under the concurrent/read-only scheduler.\n // If this assert fires either a bug has been introduced, or there is a valid scenario for a writing\n // codepath to read a column and this assert should be adjusted.\n Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ConcurrentScheduler);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n if (!Storage._shutdownTokenSource.IsCancellationRequested)\n {\n using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection);\n\n // We're in the reading-only scheduler path, so we can't allow TryGetDatabaseId to write. Note that\n // this is ok, and actually provides the semantics we want. Specifically, we can be trying to read\n // data that either exists in the DB or not. If it doesn't exist in the DB, then it's fine to fail\n // to map from the key to a DB id (since there's nothing to lookup anyways). And if it does exist\n // in the db then finding the ID would succeed (without writing) and we could continue.\n if (TryGetDatabaseId(connection, key, allowWrite: false, out var dataId))\n {\n try\n {\n // First, try to see if there was a write to this key in our in-memory db.\n // If it wasn't in the in-memory write-cache. Check the full on-disk file.\n\n var optional = ReadColumnHelper(connection, Database.WriteCache, dataId);\n if (optional.HasValue)\n return optional;\n\n optional = ReadColumnHelper(connection, Database.Main, dataId);\n if (optional.HasValue)\n return optional;\n }\n catch (Exception ex)\n {\n StorageDatabaseLogger.LogException(ex);\n }\n }\n }\n\n return default;\n\n Optional ReadColumnHelper(SqlConnection connection, Database database, TDatabaseId dataId)\n {\n // Note: it's possible that someone may write to this row between when we get the row ID\n // above and now. That's fine. We'll just read the new bytes that have been written to\n // this location. Note that only the data for a row in our system can change, the ID will\n // always stay the same, and the data will always be valid for our ID. So there is no\n // safety issue here.\n return TryGetRowId(connection, database, dataId, out var writeCacheRowId)\n ? readColumn(data, connection, database, writeCacheRowId)\n : default;\n }\n }\n\n public Task WriteStreamAsync(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken)\n => Storage.PerformWriteAsync(\n static t => t.self.WriteStream(t.key, t.stream, t.checksum, t.cancellationToken),\n (self: this, key, stream, checksum, cancellationToken), cancellationToken);\n\n private bool WriteStream(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken)\n {\n // We're writing. This better always be under the exclusive scheduler.\n Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n if (!Storage._shutdownTokenSource.IsCancellationRequested)\n {\n using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection);\n\n // Determine the appropriate data-id to store this stream at. We already are running\n // with an exclusive write lock on the DB, so it's safe for us to write the data id to \n // the db on this connection if we need to.\n if (TryGetDatabaseId(connection, key, allowWrite: true, out var dataId))\n {\n checksum ??= Checksum.Null;\n Span checksumBytes = stackalloc byte[Checksum.HashSize];\n checksum.WriteTo(checksumBytes);\n\n var (dataBytes, dataLength, dataPooled) = GetBytes(stream);\n\n // Write the information into the in-memory write-cache. Later on a background task\n // will move it from the in-memory cache to the on-disk db in a bulk transaction.\n InsertOrReplaceBlobIntoWriteCache(\n connection, dataId,\n checksumBytes,\n new ReadOnlySpan(dataBytes, 0, dataLength));\n\n if (dataPooled)\n ReturnPooledBytes(dataBytes);\n\n return true;\n }\n }\n\n return false;\n }\n\n private Optional ReadDataBlob(\n SqlConnection connection, Database database, long rowId, Checksum? checksum)\n {\n // Have to run the blob reading in a transaction. This is necessary\n // for two reasons. First, blob reading outside a transaction is not\n // safe to do with the sqlite API. It may produce corrupt bits if\n // another thread is writing to the blob. Second, if a checksum was\n // passed in, we need to validate that the checksums match. This is\n // only safe if we are in a transaction and no-one else can race with\n // us.\n return connection.RunInTransaction(\n static t =>\n {\n // If we were passed a checksum, make sure it matches what we have\n // stored in the table already. If they don't match, don't read\n // out the data value at all.\n if (t.checksum != null &&\n !t.self.ChecksumsMatch_MustRunInTransaction(t.connection, t.database, t.rowId, t.checksum))\n {\n return default;\n }\n\n return t.connection.ReadDataBlob_MustRunInTransaction(t.database, t.self.Table, t.rowId);\n },\n (self: this, connection, database, checksum, rowId));\n }\n\n private Optional ReadChecksum(\n SqlConnection connection, Database database, long rowId)\n {\n // Have to run the checksum reading in a transaction. This is necessary as blob reading outside a\n // transaction is not safe to do with the sqlite API. It may produce corrupt bits if another thread is\n // writing to the blob.\n return connection.RunInTransaction(\n static t => t.connection.ReadChecksum_MustRunInTransaction(t.database, t.self.Table, t.rowId),\n (self: this, connection, database, rowId));\n }\n\n private bool ChecksumsMatch_MustRunInTransaction(SqlConnection connection, Database database, long rowId, Checksum checksum)\n {\n var storedChecksum = connection.ReadChecksum_MustRunInTransaction(database, Table, rowId);\n return storedChecksum.HasValue && checksum == storedChecksum.Value;\n }\n\n#pragma warning disable CA1822 // Mark members as static - instance members used in Debug\n protected bool GetAndVerifyRowId(SqlConnection connection, Database database, long dataId, out long rowId)\n#pragma warning restore CA1822 // Mark members as static\n {\n // For the Document and Project tables, our dataId is our rowId:\n //\n // https://sqlite.org/lang_createtable.html\n // if a rowid table has a primary key that consists of a single column and the\n // declared type of that column is \"INTEGER\" in any mixture of upper and lower\n // case, then the column becomes an alias for the rowid. Such a column is usually\n // referred to as an \"integer primary key\". A PRIMARY KEY column only becomes an\n // integer primary key if the declared type name is exactly \"INTEGER\"\n#if DEBUG\n // make sure that if we actually request the rowId from the database that it\n // is equal to our data id. Only do this in debug as this can be expensive\n // and we definitely do not want to do this in release.\n if (GetActualRowIdFromDatabase(connection, database, (TDatabaseId)(object)dataId, out rowId))\n {\n Debug.Assert(dataId == rowId);\n }\n#endif\n\n // Can just return out dataId as the rowId without actually having to hit the\n // database at all.\n rowId = dataId;\n return true;\n }\n\n protected bool GetActualRowIdFromDatabase(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId)\n {\n // See https://sqlite.org/autoinc.html\n // > In SQLite, table rows normally have a 64-bit signed integer ROWID which is\n // unique among all rows in the same table. (WITHOUT ROWID tables are the exception.)\n //\n // You can access the ROWID of an SQLite table using one of the special column names\n // ROWID, _ROWID_, or OID. Except if you declare an ordinary table column to use one\n // of those special names, then the use of that name will refer to the declared column\n // not to the internal ROWID.\n using var resettableStatement = connection.GetResettableStatement(database == Database.WriteCache\n ? _select_rowid_from_writecache_table_where_0\n : _select_rowid_from_main_table_where_0);\n\n var statement = resettableStatement.Statement;\n\n BindFirstParameter(statement, dataId);\n\n var stepResult = statement.Step();\n if (stepResult == Result.ROW)\n {\n rowId = statement.GetInt64At(columnIndex: 0);\n return true;\n }\n\n rowId = -1;\n return false;\n }\n\n private void InsertOrReplaceBlobIntoWriteCache(\n SqlConnection connection, TDatabaseId dataId,\n ReadOnlySpan checksumBytes,\n ReadOnlySpan dataBytes)\n {\n // We're writing. This better always be under the exclusive scheduler.\n Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler);\n\n using (var resettableStatement = connection.GetResettableStatement(_insert_or_replace_into_writecache_table_values_0_1_2))\n {\n var statement = resettableStatement.Statement;\n\n // Binding indices are 1 based.\n BindFirstParameter(statement, dataId);\n statement.BindBlobParameter(parameterIndex: 2, checksumBytes);\n statement.BindBlobParameter(parameterIndex: 3, dataBytes);\n\n statement.Step();\n }\n\n // Let the storage system know it should flush this information\n // to disk in the future.\n Storage.EnqueueFlushTask();\n }\n\n public void FlushInMemoryDataToDisk_MustRunInTransaction(SqlConnection connection)\n {\n if (!connection.IsInTransaction)\n {\n throw new InvalidOperationException(\"Must flush tables within a transaction to ensure consistency\");\n }\n\n // Efficient call to sqlite to just fully copy all data from one table to the\n // other. No need to actually do any reading/writing of the data ourselves.\n using (var statement = connection.GetResettableStatement(_insert_or_replace_into_main_table_select_star_from_writecache_table))\n {\n statement.Statement.Step();\n }\n\n // Now, just delete all the data from the write cache.\n using (var statement = connection.GetResettableStatement(_delete_from_writecache_table))\n {\n statement.Statement.Step();\n }\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.SQLite.Interop;\nusing Microsoft.CodeAnalysis.SQLite.v2.Interop;\nusing Microsoft.CodeAnalysis.Storage;\nusing Roslyn.Utilities;\n\n#if DEBUG\nusing System.Diagnostics;\n#endif\n\nnamespace Microsoft.CodeAnalysis.SQLite.v2\n{\n using static SQLitePersistentStorageConstants;\n\n internal partial class SQLitePersistentStorage\n {\n /// \n /// Abstracts out access to specific tables in the DB. This allows us to share overall\n /// logic around cancellation/pooling/error-handling/etc, while still hitting different\n /// db tables.\n /// \n private abstract class Accessor\n {\n protected readonly SQLitePersistentStorage Storage;\n\n // Cache the statement strings we want to execute per accessor. This way we avoid\n // allocating these strings each time we execute a command. We also cache the prepared\n // statements (at the connection level) we make for each of these strings. That way we\n // only incur the parsing cost once. After that, we can use the same prepared statements\n // and just bind the appropriate values it needs into it.\n //\n // values like 0, 1, 2 in the name are the `?`s in the sql string that will need to be\n // bound to runtime values appropriately when executed.\n\n private readonly string _select_rowid_from_main_table_where_0;\n private readonly string _select_rowid_from_writecache_table_where_0;\n private readonly string _insert_or_replace_into_writecache_table_values_0_1_2;\n private readonly string _delete_from_writecache_table;\n private readonly string _insert_or_replace_into_main_table_select_star_from_writecache_table;\n\n public Accessor(SQLitePersistentStorage storage)\n {\n var main = Database.Main.GetName();\n var writeCache = Database.WriteCache.GetName();\n\n var dataTableName = this.Table switch\n {\n Table.Solution => SolutionDataTableName,\n Table.Project => ProjectDataTableName,\n Table.Document => DocumentDataTableName,\n _ => throw ExceptionUtilities.UnexpectedValue(this.Table),\n };\n\n Storage = storage;\n _select_rowid_from_main_table_where_0 = $@\"select rowid from {main}.{dataTableName} where \"\"{DataIdColumnName}\"\" = ?\";\n _select_rowid_from_writecache_table_where_0 = $@\"select rowid from {writeCache}.{dataTableName} where \"\"{DataIdColumnName}\"\" = ?\";\n _insert_or_replace_into_writecache_table_values_0_1_2 = $@\"insert or replace into {writeCache}.{dataTableName}(\"\"{DataIdColumnName}\"\",\"\"{ChecksumColumnName}\"\",\"\"{DataColumnName}\"\") values (?,?,?)\";\n _delete_from_writecache_table = $\"delete from {writeCache}.{dataTableName};\";\n _insert_or_replace_into_main_table_select_star_from_writecache_table = $\"insert or replace into {main}.{dataTableName} select * from {writeCache}.{dataTableName};\";\n }\n\n protected abstract Table Table { get; }\n\n /// \n /// Gets the internal sqlite db-id (effectively the row-id for the doc or proj table, or just the string-id\n /// for the solution table) for the provided caller key. This db-id will be looked up and returned if a\n /// mapping already exists for it in the db. Otherwise, a guaranteed unique id will be created for it and\n /// stored in the db for the future. This allows all associated data to be cheaply associated with the \n /// simple ID, avoiding lots of db bloat if we used the full in numerous places.\n /// \n /// Whether or not the caller owns the write lock and thus is ok with the DB id\n /// being generated and stored for this component key when it currently does not exist. If then failing to find the key will result in being returned.\n /// \n protected abstract bool TryGetDatabaseId(SqlConnection connection, TKey key, bool allowWrite, out TDatabaseId dataId);\n protected abstract void BindFirstParameter(SqlStatement statement, TDatabaseId dataId);\n protected abstract TWriteQueueKey GetWriteQueueKey(TKey key);\n protected abstract bool TryGetRowId(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId);\n\n [PerformanceSensitive(\"https://github.com/dotnet/roslyn/issues/36114\", AllowCaptures = false)]\n public Task ChecksumMatchesAsync(TKey key, Checksum checksum, CancellationToken cancellationToken)\n => Storage.PerformReadAsync(\n static t => t.self.ChecksumMatches(t.key, t.checksum, t.cancellationToken),\n (self: this, key, checksum, cancellationToken), cancellationToken);\n\n private bool ChecksumMatches(TKey key, Checksum checksum, CancellationToken cancellationToken)\n {\n var optional = ReadColumn(\n key,\n static (self, connection, database, rowId) => self.ReadChecksum(connection, database, rowId),\n this,\n cancellationToken);\n return optional.HasValue && checksum == optional.Value;\n }\n\n [PerformanceSensitive(\"https://github.com/dotnet/roslyn/issues/36114\", AllowCaptures = false)]\n public Task ReadStreamAsync(TKey key, Checksum? checksum, CancellationToken cancellationToken)\n => Storage.PerformReadAsync(\n static t => t.self.ReadStream(t.key, t.checksum, t.cancellationToken),\n (self: this, key, checksum, cancellationToken), cancellationToken);\n\n [PerformanceSensitive(\"https://github.com/dotnet/roslyn/issues/36114\", AllowCaptures = false)]\n private Stream? ReadStream(TKey key, Checksum? checksum, CancellationToken cancellationToken)\n {\n var optional = ReadColumn(\n key,\n static (t, connection, database, rowId) => t.self.ReadDataBlob(connection, database, rowId, t.checksum),\n (self: this, checksum),\n cancellationToken);\n\n Contract.ThrowIfTrue(optional.HasValue && optional.Value == null);\n return optional.HasValue ? optional.Value : null;\n }\n\n private Optional ReadColumn(\n TKey key,\n Func> readColumn,\n TData data,\n CancellationToken cancellationToken)\n {\n // We're reading. All current scenarios have this happening under the concurrent/read-only scheduler.\n // If this assert fires either a bug has been introduced, or there is a valid scenario for a writing\n // codepath to read a column and this assert should be adjusted.\n Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ConcurrentScheduler);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n if (!Storage._shutdownTokenSource.IsCancellationRequested)\n {\n using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection);\n\n // We're in the reading-only scheduler path, so we can't allow TryGetDatabaseId to write. Note that\n // this is ok, and actually provides the semantics we want. Specifically, we can be trying to read\n // data that either exists in the DB or not. If it doesn't exist in the DB, then it's fine to fail\n // to map from the key to a DB id (since there's nothing to lookup anyways). And if it does exist\n // in the db then finding the ID would succeed (without writing) and we could continue.\n if (TryGetDatabaseId(connection, key, allowWrite: false, out var dataId))\n {\n try\n {\n // First, try to see if there was a write to this key in our in-memory db.\n // If it wasn't in the in-memory write-cache. Check the full on-disk file.\n\n var optional = ReadColumnHelper(connection, Database.WriteCache, dataId);\n if (optional.HasValue)\n return optional;\n\n optional = ReadColumnHelper(connection, Database.Main, dataId);\n if (optional.HasValue)\n return optional;\n }\n catch (Exception ex)\n {\n StorageDatabaseLogger.LogException(ex);\n }\n }\n }\n\n return default;\n\n Optional ReadColumnHelper(SqlConnection connection, Database database, TDatabaseId dataId)\n {\n // Note: it's possible that someone may write to this row between when we get the row ID\n // above and now. That's fine. We'll just read the new bytes that have been written to\n // this location. Note that only the data for a row in our system can change, the ID will\n // always stay the same, and the data will always be valid for our ID. So there is no\n // safety issue here.\n return TryGetRowId(connection, database, dataId, out var writeCacheRowId)\n ? readColumn(data, connection, database, writeCacheRowId)\n : default;\n }\n }\n\n public Task WriteStreamAsync(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken)\n => Storage.PerformWriteAsync(\n static t => t.self.WriteStream(t.key, t.stream, t.checksum, t.cancellationToken),\n (self: this, key, stream, checksum, cancellationToken), cancellationToken);\n\n private bool WriteStream(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken)\n {\n // We're writing. This better always be under the exclusive scheduler.\n Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n if (!Storage._shutdownTokenSource.IsCancellationRequested)\n {\n using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection);\n\n // Determine the appropriate data-id to store this stream at. We already are running\n // with an exclusive write lock on the DB, so it's safe for us to write the data id to \n // the db on this connection if we need to.\n if (TryGetDatabaseId(connection, key, allowWrite: true, out var dataId))\n {\n checksum ??= Checksum.Null;\n Span checksumBytes = stackalloc byte[Checksum.HashSize];\n checksum.WriteTo(checksumBytes);\n\n var (dataBytes, dataLength, dataPooled) = GetBytes(stream);\n\n // Write the information into the in-memory write-cache. Later on a background task\n // will move it from the in-memory cache to the on-disk db in a bulk transaction.\n InsertOrReplaceBlobIntoWriteCache(\n connection, dataId,\n checksumBytes,\n new ReadOnlySpan(dataBytes, 0, dataLength));\n\n if (dataPooled)\n ReturnPooledBytes(dataBytes);\n\n return true;\n }\n }\n\n return false;\n }\n\n private Optional ReadDataBlob(\n SqlConnection connection, Database database, long rowId, Checksum? checksum)\n {\n // Have to run the blob reading in a transaction. This is necessary\n // for two reasons. First, blob reading outside a transaction is not\n // safe to do with the sqlite API. It may produce corrupt bits if\n // another thread is writing to the blob. Second, if a checksum was\n // passed in, we need to validate that the checksums match. This is\n // only safe if we are in a transaction and no-one else can race with\n // us.\n return connection.RunInTransaction(\n static t =>\n {\n // If we were passed a checksum, make sure it matches what we have\n // stored in the table already. If they don't match, don't read\n // out the data value at all.\n if (t.checksum != null &&\n !t.self.ChecksumsMatch_MustRunInTransaction(t.connection, t.database, t.rowId, t.checksum))\n {\n return default;\n }\n\n return t.connection.ReadDataBlob_MustRunInTransaction(t.database, t.self.Table, t.rowId);\n },\n (self: this, connection, database, checksum, rowId));\n }\n\n private Optional ReadChecksum(\n SqlConnection connection, Database database, long rowId)\n {\n // Have to run the checksum reading in a transaction. This is necessary as blob reading outside a\n // transaction is not safe to do with the sqlite API. It may produce corrupt bits if another thread is\n // writing to the blob.\n return connection.RunInTransaction(\n static t => t.connection.ReadChecksum_MustRunInTransaction(t.database, t.self.Table, t.rowId),\n (self: this, connection, database, rowId));\n }\n\n private bool ChecksumsMatch_MustRunInTransaction(SqlConnection connection, Database database, long rowId, Checksum checksum)\n {\n var storedChecksum = connection.ReadChecksum_MustRunInTransaction(database, Table, rowId);\n return storedChecksum.HasValue && checksum == storedChecksum.Value;\n }\n\n#pragma warning disable CA1822 // Mark members as static - instance members used in Debug\n protected bool GetAndVerifyRowId(SqlConnection connection, Database database, long dataId, out long rowId)\n#pragma warning restore CA1822 // Mark members as static\n {\n // For the Document and Project tables, our dataId is our rowId:\n //\n // https://sqlite.org/lang_createtable.html\n // if a rowid table has a primary key that consists of a single column and the\n // declared type of that column is \"INTEGER\" in any mixture of upper and lower\n // case, then the column becomes an alias for the rowid. Such a column is usually\n // referred to as an \"integer primary key\". A PRIMARY KEY column only becomes an\n // integer primary key if the declared type name is exactly \"INTEGER\"\n#if DEBUG\n // make sure that if we actually request the rowId from the database that it\n // is equal to our data id. Only do this in debug as this can be expensive\n // and we definitely do not want to do this in release.\n if (GetActualRowIdFromDatabase(connection, database, (TDatabaseId)(object)dataId, out rowId))\n {\n Debug.Assert(dataId == rowId);\n }\n#endif\n\n // Can just return out dataId as the rowId without actually having to hit the\n // database at all.\n rowId = dataId;\n return true;\n }\n\n protected bool GetActualRowIdFromDatabase(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId)\n {\n // See https://sqlite.org/autoinc.html\n // > In SQLite, table rows normally have a 64-bit signed integer ROWID which is\n // unique among all rows in the same table. (WITHOUT ROWID tables are the exception.)\n //\n // You can access the ROWID of an SQLite table using one of the special column names\n // ROWID, _ROWID_, or OID. Except if you declare an ordinary table column to use one\n // of those special names, then the use of that name will refer to the declared column\n // not to the internal ROWID.\n using var resettableStatement = connection.GetResettableStatement(database == Database.WriteCache\n ? _select_rowid_from_writecache_table_where_0\n : _select_rowid_from_main_table_where_0);\n\n var statement = resettableStatement.Statement;\n\n BindFirstParameter(statement, dataId);\n\n var stepResult = statement.Step();\n if (stepResult == Result.ROW)\n {\n rowId = statement.GetInt64At(columnIndex: 0);\n return true;\n }\n\n rowId = -1;\n return false;\n }\n\n private void InsertOrReplaceBlobIntoWriteCache(\n SqlConnection connection, TDatabaseId dataId,\n ReadOnlySpan checksumBytes,\n ReadOnlySpan dataBytes)\n {\n // We're writing. This better always be under the exclusive scheduler.\n Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler);\n\n using (var resettableStatement = connection.GetResettableStatement(_insert_or_replace_into_writecache_table_values_0_1_2))\n {\n var statement = resettableStatement.Statement;\n\n // Binding indices are 1 based.\n BindFirstParameter(statement, dataId);\n statement.BindBlobParameter(parameterIndex: 2, checksumBytes);\n statement.BindBlobParameter(parameterIndex: 3, dataBytes);\n\n statement.Step();\n }\n\n // Let the storage system know it should flush this information\n // to disk in the future.\n Storage.EnqueueFlushTask();\n }\n\n public void FlushInMemoryDataToDisk_MustRunInTransaction(SqlConnection connection)\n {\n if (!connection.IsInTransaction)\n {\n throw new InvalidOperationException(\"Must flush tables within a transaction to ensure consistency\");\n }\n\n // Efficient call to sqlite to just fully copy all data from one table to the\n // other. No need to actually do any reading/writing of the data ourselves.\n using (var statement = connection.GetResettableStatement(_insert_or_replace_into_main_table_select_star_from_writecache_table))\n {\n statement.Statement.Step();\n }\n\n // Now, just delete all the data from the write cache.\n using (var statement = connection.GetResettableStatement(_delete_from_writecache_table))\n {\n statement.Statement.Step();\n }\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":438,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginGlyph.xaml.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Editor;\nusing Microsoft.CodeAnalysis.Editor.GoToDefinition;\nusing Microsoft.CodeAnalysis.Editor.Host;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.CodeAnalysis.FindUsages;\nusing Microsoft.CodeAnalysis.Internal.Log;\nusing Microsoft.CodeAnalysis.Shared.TestHooks;\nusing Microsoft.VisualStudio.Shell;\nusing Microsoft.VisualStudio.Text.Classification;\nusing Microsoft.VisualStudio.Text.Editor;\nusing Microsoft.VisualStudio.Utilities;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph\n{\n internal partial class InheritanceMarginGlyph\n {\n private readonly IThreadingContext _threadingContext;\n private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter;\n private readonly IUIThreadOperationExecutor _operationExecutor;\n private readonly Workspace _workspace;\n private readonly IWpfTextView _textView;\n private readonly IAsynchronousOperationListener _listener;\n\n public InheritanceMarginGlyph(\n IThreadingContext threadingContext,\n IStreamingFindUsagesPresenter streamingFindUsagesPresenter,\n ClassificationTypeMap classificationTypeMap,\n IClassificationFormatMap classificationFormatMap,\n IUIThreadOperationExecutor operationExecutor,\n InheritanceMarginTag tag,\n IWpfTextView textView,\n IAsynchronousOperationListener listener)\n {\n _threadingContext = threadingContext;\n _streamingFindUsagesPresenter = streamingFindUsagesPresenter;\n _workspace = tag.Workspace;\n _operationExecutor = operationExecutor;\n _textView = textView;\n _listener = listener;\n InitializeComponent();\n\n var viewModel = InheritanceMarginGlyphViewModel.Create(classificationTypeMap, classificationFormatMap, tag, textView.ZoomLevel);\n DataContext = viewModel;\n ContextMenu.DataContext = viewModel;\n ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource(\"ToolTipStyle\") };\n }\n\n private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e)\n {\n if (this.ContextMenu != null)\n {\n this.ContextMenu.IsOpen = true;\n e.Handled = true;\n }\n }\n\n private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e)\n {\n if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel })\n {\n Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction));\n\n var token = _listener.BeginAsyncOperation(nameof(TargetMenuItem_OnClick));\n TargetMenuItem_OnClickAsync(viewModel).CompletesAsyncOperation(token);\n }\n }\n\n private async Task TargetMenuItem_OnClickAsync(TargetMenuItemViewModel viewModel)\n {\n using var context = _operationExecutor.BeginExecute(\n title: EditorFeaturesResources.Navigating,\n defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent),\n allowCancellation: true,\n showProgress: false);\n\n var cancellationToken = context.UserCancellationToken;\n var rehydrated = await viewModel.DefinitionItem.TryRehydrateAsync(cancellationToken).ConfigureAwait(false);\n if (rehydrated == null)\n return;\n\n await _streamingFindUsagesPresenter.TryNavigateToOrPresentItemsAsync(\n _threadingContext,\n _workspace,\n string.Format(EditorFeaturesResources._0_declarations, viewModel.DisplayContent),\n ImmutableArray.Create(rehydrated),\n cancellationToken).ConfigureAwait(false);\n }\n\n private void ChangeBorderToHoveringColor()\n {\n SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey);\n SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey);\n }\n\n private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e)\n {\n ChangeBorderToHoveringColor();\n }\n\n private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e)\n {\n // If the context menu is open, then don't reset the color of the button because we need\n // the margin looks like being pressed.\n if (!ContextMenu.IsOpen)\n {\n ResetBorderToInitialColor();\n }\n }\n\n private void ContextMenu_OnClose(object sender, RoutedEventArgs e)\n {\n // If mouse is still hovering. Don't reset the color. The context menu might be closed because user clicks within the margin\n if (!IsMouseOver)\n {\n ResetBorderToInitialColor();\n }\n // Move the focus back to textView when the context menu is closed.\n // It ensures the focus won't be left at the margin\n ResetFocus();\n }\n\n private void ContextMenu_OnOpen(object sender, RoutedEventArgs e)\n {\n if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginGlyphViewModel inheritanceMarginViewModel }\n && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel))\n {\n // We have two kinds of context menu. e.g.\n // 1. [margin] -> Header\n // Target1\n // Target2\n // Target3\n //\n // 2. [margin] -> method Bar -> Header\n // -> Target1\n // -> Target2\n // -> method Foo -> Header\n // -> Target3\n // -> Target4\n // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1,\n // user is viewing the targets menu.\n Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction));\n }\n }\n\n private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e)\n {\n Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction));\n }\n\n private void ResetBorderToInitialColor()\n {\n this.Background = Brushes.Transparent;\n this.BorderBrush = Brushes.Transparent;\n }\n\n private void ResetFocus()\n {\n if (!_textView.HasAggregateFocus)\n {\n var visualElement = _textView.VisualElement;\n if (visualElement.Focusable)\n {\n Keyboard.Focus(visualElement);\n }\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Automation;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Editor.Host;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.CodeAnalysis.Internal.Log;\nusing Microsoft.CodeAnalysis.Shared.TestHooks;\nusing Microsoft.VisualStudio.Imaging;\nusing Microsoft.VisualStudio.PlatformUI;\nusing Microsoft.VisualStudio.Shell;\nusing Microsoft.VisualStudio.Text.Classification;\nusing Microsoft.VisualStudio.Text.Editor;\nusing Microsoft.VisualStudio.Utilities;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph\n{\n internal class InheritanceMarginGlyph : Button\n {\n private const string ToolTipStyleKey = \"ToolTipStyle\";\n\n private static readonly object s_toolTipPlaceholder = new();\n\n private readonly IThreadingContext _threadingContext;\n private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter;\n private readonly IUIThreadOperationExecutor _operationExecutor;\n private readonly Workspace _workspace;\n private readonly IWpfTextView _textView;\n private readonly IAsynchronousOperationListener _listener;\n\n public InheritanceMarginGlyph(\n IThreadingContext threadingContext,\n IStreamingFindUsagesPresenter streamingFindUsagesPresenter,\n ClassificationTypeMap classificationTypeMap,\n IClassificationFormatMap classificationFormatMap,\n IUIThreadOperationExecutor operationExecutor,\n InheritanceMarginTag tag,\n IWpfTextView textView,\n IAsynchronousOperationListener listener)\n {\n _threadingContext = threadingContext;\n _streamingFindUsagesPresenter = streamingFindUsagesPresenter;\n _workspace = tag.Workspace;\n _operationExecutor = operationExecutor;\n _textView = textView;\n _listener = listener;\n\n Background = Brushes.Transparent;\n BorderBrush = Brushes.Transparent;\n\n Click += InheritanceMargin_OnClick;\n MouseEnter += InheritanceMargin_OnMouseEnter;\n MouseLeave += InheritanceMargin_OnMouseLeave;\n\n Resources.Add(ToolTipStyleKey, new Style(typeof(ToolTip))\n {\n Setters =\n {\n new Setter(BackgroundProperty, new DynamicResourceExtension(EnvironmentColors.ToolTipBrushKey)),\n new Setter(BorderBrushProperty, new DynamicResourceExtension(EnvironmentColors.ToolTipBorderBrushKey)),\n new Setter(ForegroundProperty, new DynamicResourceExtension(EnvironmentColors.ToolTipTextBrushKey)),\n },\n });\n\n var viewModel = InheritanceMarginGlyphViewModel.Create(classificationTypeMap, classificationFormatMap, tag, textView.ZoomLevel);\n SetValue(AutomationProperties.NameProperty, viewModel.AutomationName);\n\n // Control template only shows the image\n var templateBorder = new FrameworkElementFactory(typeof(Border), \"Border\");\n templateBorder.SetValue(Border.BorderThicknessProperty, new Thickness(1));\n templateBorder.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(BackgroundProperty));\n templateBorder.SetValue(Border.BorderBrushProperty, new TemplateBindingExtension(BorderBrushProperty));\n\n var templateImage = new FrameworkElementFactory(typeof(CrispImage));\n templateImage.SetValue(CrispImage.MonikerProperty, viewModel.ImageMoniker);\n templateImage.SetValue(CrispImage.ScaleFactorProperty, viewModel.ScaleFactor);\n templateBorder.AppendChild(templateImage);\n\n Template = new ControlTemplate { VisualTree = templateBorder };\n DataContext = viewModel;\n\n // Add the context menu and tool tip as placeholders\n ContextMenu = new ContextMenu();\n ToolTip = s_toolTipPlaceholder;\n }\n\n protected override void OnToolTipOpening(ToolTipEventArgs e)\n {\n if (ToolTip == s_toolTipPlaceholder)\n {\n var viewModel = (InheritanceMarginGlyphViewModel)DataContext;\n ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource(ToolTipStyleKey) };\n }\n\n base.OnToolTipOpening(e);\n }\n\n protected override void OnContextMenuOpening(ContextMenuEventArgs e)\n {\n LazyInitializeContextMenu();\n base.OnContextMenuOpening(e);\n }\n\n private void LazyInitializeContextMenu()\n {\n if (ContextMenu is not InheritanceMarginContextMenu)\n {\n var viewModel = (InheritanceMarginGlyphViewModel)DataContext;\n\n ContextMenu = new InheritanceMarginContextMenu(_threadingContext, _streamingFindUsagesPresenter, _operationExecutor, _workspace, _textView, _listener);\n ContextMenu.DataContext = viewModel;\n ContextMenu.ItemsSource = viewModel.MenuItemViewModels;\n ContextMenu.Opened += ContextMenu_OnOpen;\n ContextMenu.Closed += ContextMenu_OnClose;\n }\n }\n\n private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e)\n {\n LazyInitializeContextMenu();\n ContextMenu.IsOpen = true;\n e.Handled = true;\n }\n\n private void ChangeBorderToHoveringColor()\n {\n SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey);\n SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey);\n }\n\n private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e)\n {\n ChangeBorderToHoveringColor();\n }\n\n private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e)\n {\n // If the context menu is open, then don't reset the color of the button because we need\n // the margin looks like being pressed.\n if (!ContextMenu.IsOpen)\n {\n ResetBorderToInitialColor();\n }\n }\n\n private void ContextMenu_OnClose(object sender, RoutedEventArgs e)\n {\n // If mouse is still hovering. Don't reset the color. The context menu might be closed because user clicks within the margin\n if (!IsMouseOver)\n {\n ResetBorderToInitialColor();\n }\n // Move the focus back to textView when the context menu is closed.\n // It ensures the focus won't be left at the margin\n ResetFocus();\n }\n\n private void ContextMenu_OnOpen(object sender, RoutedEventArgs e)\n {\n if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginGlyphViewModel inheritanceMarginViewModel }\n && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel))\n {\n // We have two kinds of context menu. e.g.\n // 1. [margin] -> Header\n // Target1\n // Target2\n // Target3\n //\n // 2. [margin] -> method Bar -> Header\n // -> Target1\n // -> Target2\n // -> method Foo -> Header\n // -> Target3\n // -> Target4\n // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1,\n // user is viewing the targets menu.\n Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction));\n }\n }\n\n private void ResetBorderToInitialColor()\n {\n this.Background = Brushes.Transparent;\n this.BorderBrush = Brushes.Transparent;\n }\n\n private void ResetFocus()\n {\n if (!_textView.HasAggregateFocus)\n {\n var visualElement = _textView.VisualElement;\n if (visualElement.Focusable)\n {\n Keyboard.Focus(visualElement);\n }\n }\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":439,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginGlyphViewModel.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Editor.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.VisualStudio.Imaging.Interop;\nusing Microsoft.VisualStudio.Text.Classification;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph\n{\n internal class InheritanceMarginGlyphViewModel\n {\n /// \n /// ImageMoniker used for the margin.\n /// \n public ImageMoniker ImageMoniker { get; }\n\n /// \n /// Tooltip for the margin.\n /// \n public TextBlock ToolTipTextBlock { get; }\n\n /// \n /// Text used for automation.\n /// \n public string AutomationName { get; }\n\n /// \n /// ViewModels for the context menu items.\n /// \n public ImmutableArray MenuItemViewModels { get; }\n\n /// \n /// Scale factor for the margin.\n /// \n public double ScaleFactor { get; }\n\n // Internal for testing purpose\n internal InheritanceMarginGlyphViewModel(\n ImageMoniker imageMoniker,\n TextBlock toolTipTextBlock,\n string automationName,\n double scaleFactor,\n ImmutableArray menuItemViewModels)\n {\n ImageMoniker = imageMoniker;\n ToolTipTextBlock = toolTipTextBlock;\n AutomationName = automationName;\n MenuItemViewModels = menuItemViewModels;\n ScaleFactor = scaleFactor;\n }\n\n public static InheritanceMarginGlyphViewModel Create(\n ClassificationTypeMap classificationTypeMap,\n IClassificationFormatMap classificationFormatMap,\n InheritanceMarginTag tag,\n double zoomLevel)\n {\n var members = tag.MembersOnLine;\n\n // ZoomLevel is 100 based. (e.g. 150%, 100%)\n // ScaleFactor is 1 based. (e.g. 1.5, 1)\n var scaleFactor = zoomLevel / 100;\n if (members.Length == 1)\n {\n var member = tag.MembersOnLine[0];\n\n // Here we want to show a classified text with loc text,\n // e.g. 'Bar' is inherited.\n // But the classified text are inlines, so can't directly use string.format to generate the string\n var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap);\n var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf(\"{0}\", StringComparison.Ordinal);\n var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder];\n var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + \"{0}\".Length)..];\n inlines.Insert(0, new Run(prefixString));\n inlines.Add(new Run(suffixString));\n var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap);\n toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight;\n\n var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText());\n var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems);\n return new InheritanceMarginGlyphViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels);\n }\n else\n {\n var textBlock = new TextBlock\n {\n Text = ServicesVSResources.Multiple_members_are_inherited\n };\n\n // Same automation name can't be set for control for accessibility purpose. So add the line number info.\n var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber);\n var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine);\n return new InheritanceMarginGlyphViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels);\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Editor.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.VisualStudio.Imaging.Interop;\nusing Microsoft.VisualStudio.Text.Classification;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph\n{\n internal class InheritanceMarginGlyphViewModel\n {\n private readonly ClassificationTypeMap _classificationTypeMap;\n private readonly IClassificationFormatMap _classificationFormatMap;\n private readonly InheritanceMarginTag _tag;\n private TextBlock? _lazyToolTipTextBlock;\n\n /// \n /// ImageMoniker used for the margin.\n /// \n public ImageMoniker ImageMoniker => _tag.Moniker;\n\n /// \n /// Tooltip for the margin.\n /// \n public TextBlock ToolTipTextBlock\n {\n get\n {\n if (_lazyToolTipTextBlock is null)\n {\n var members = _tag.MembersOnLine;\n if (members.Length == 1)\n {\n var member = _tag.MembersOnLine[0];\n\n // Here we want to show a classified text with loc text,\n // e.g. 'Bar' is inherited.\n // But the classified text are inlines, so can't directly use string.format to generate the string\n var inlines = member.DisplayTexts.ToInlines(_classificationFormatMap, _classificationTypeMap);\n var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf(\"{0}\", StringComparison.Ordinal);\n var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder];\n var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + \"{0}\".Length)..];\n inlines.Insert(0, new Run(prefixString));\n inlines.Add(new Run(suffixString));\n var toolTipTextBlock = inlines.ToTextBlock(_classificationFormatMap);\n toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight;\n\n _lazyToolTipTextBlock = toolTipTextBlock;\n }\n else\n {\n _lazyToolTipTextBlock = new TextBlock\n {\n Text = ServicesVSResources.Multiple_members_are_inherited\n };\n }\n }\n\n return _lazyToolTipTextBlock;\n }\n }\n\n /// \n /// Text used for automation.\n /// \n public string AutomationName { get; }\n\n /// \n /// ViewModels for the context menu items.\n /// \n public ImmutableArray MenuItemViewModels { get; }\n\n /// \n /// Scale factor for the margin.\n /// \n public double ScaleFactor { get; }\n\n private InheritanceMarginGlyphViewModel(\n InheritanceMarginTag tag,\n ClassificationTypeMap classificationTypeMap,\n IClassificationFormatMap classificationFormatMap,\n string automationName,\n double scaleFactor,\n ImmutableArray menuItemViewModels)\n {\n _classificationTypeMap = classificationTypeMap;\n _classificationFormatMap = classificationFormatMap;\n _tag = tag;\n AutomationName = automationName;\n MenuItemViewModels = menuItemViewModels;\n ScaleFactor = scaleFactor;\n }\n\n public static InheritanceMarginGlyphViewModel Create(\n ClassificationTypeMap classificationTypeMap,\n IClassificationFormatMap classificationFormatMap,\n InheritanceMarginTag tag,\n double zoomLevel)\n {\n var members = tag.MembersOnLine;\n\n // ZoomLevel is 100 based. (e.g. 150%, 100%)\n // ScaleFactor is 1 based. (e.g. 1.5, 1)\n var scaleFactor = zoomLevel / 100;\n if (members.Length == 1)\n {\n var member = tag.MembersOnLine[0];\n\n var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText());\n var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems);\n return new InheritanceMarginGlyphViewModel(tag, classificationTypeMap, classificationFormatMap, automationName, scaleFactor, menuItemViewModels);\n }\n else\n {\n // Same automation name can't be set for control for accessibility purpose. So add the line number info.\n var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber);\n var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine);\n return new InheritanceMarginGlyphViewModel(tag, classificationTypeMap, classificationFormatMap, automationName, scaleFactor, menuItemViewModels);\n }\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":440,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Test/InheritanceMargin/InheritanceMarginViewModelTests.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Collections.Immutable\nImports System.Text\nImports System.Threading\nImports System.Windows\nImports System.Windows.Controls\nImports System.Windows.Documents\nImports Microsoft.CodeAnalysis\nImports Microsoft.CodeAnalysis.Editor.Shared.Utilities\nImports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces\nImports Microsoft.CodeAnalysis.InheritanceMargin\nImports Microsoft.CodeAnalysis.Shared.Extensions\nImports Microsoft.CodeAnalysis.Test.Utilities\nImports Microsoft.VisualStudio.Imaging\nImports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin\nImports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph\nImports Microsoft.VisualStudio.Text.Classification\nImports Microsoft.VisualStudio.Threading\nImports Roslyn.Test.Utilities\n\nNamespace Microsoft.VisualStudio.LanguageServices.UnitTests.InheritanceMargin\n\n \n \n Public Class InheritanceMarginViewModelTests\n\n Private Shared s_defaultMargin As Thickness = New Thickness(4, 1, 4, 1)\n\n Private Shared s_indentMargin As Thickness = New Thickness(22, 1, 4, 1)\n\n Private Shared Async Function VerifyAsync(markup As String, languageName As String, expectedViewModels As Dictionary(Of Integer, InheritanceMarginGlyphViewModel)) As Task\n ' Add an lf before the document so that the line number starts\n ' with 1, which meets the line number in the editor (but in fact all things start from 0)\n Dim workspaceFile =\n \n CommonReferences=\"true\">\n <%= vbLf %>\n <%= markup.Replace(vbCrLf, vbLf) %>\n \n \n \n\n Dim cancellationToken As CancellationToken = CancellationToken.None\n Using workspace = TestWorkspace.Create(workspaceFile)\n Dim testDocument = workspace.Documents.Single()\n Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id)\n Dim service = document.GetRequiredLanguageService(Of IInheritanceMarginService)\n\n Dim classificationTypeMap = workspace.ExportProvider.GetExportedValue(Of ClassificationTypeMap)\n Dim classificationFormatMap = workspace.ExportProvider.GetExportedValue(Of IClassificationFormatMapService)\n\n ' For these tests, we need to be on UI thread, so don't call ConfigureAwait(False)\n Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(True)\n Dim inheritanceItems = Await service.GetInheritanceMemberItemsAsync(document, root.FullSpan, cancellationToken).ConfigureAwait(True)\n\n Dim acutalLineToTagDictionary = inheritanceItems.GroupBy(Function(item) item.LineNumber) _\n .ToDictionary(Function(grouping) grouping.Key,\n Function(grouping)\n Dim lineNumber = grouping.Key\n Dim items = grouping.Select(Function(g) g).ToImmutableArray()\n Return New InheritanceMarginTag(workspace, lineNumber, items)\n End Function)\n Assert.Equal(expectedViewModels.Count, acutalLineToTagDictionary.Count)\n\n For Each kvp In expectedViewModels\n Dim lineNumber = kvp.Key\n Dim expectedViewModel = kvp.Value\n Assert.True(acutalLineToTagDictionary.ContainsKey(lineNumber))\n\n Dim acutalTag = acutalLineToTagDictionary(lineNumber)\n ' Editor TestView zoom level is 100 based.\n Dim actualViewModel = InheritanceMarginGlyphViewModel.Create(\n classificationTypeMap, classificationFormatMap.GetClassificationFormatMap(\"tooltip\"), acutalTag, 100)\n\n VerifyTwoViewModelAreSame(expectedViewModel, actualViewModel)\n Next\n\n End Using\n End Function\n\n Private Shared Sub VerifyTwoViewModelAreSame(expected As InheritanceMarginGlyphViewModel, actual As InheritanceMarginGlyphViewModel)\n Assert.Equal(expected.ImageMoniker, actual.ImageMoniker)\n Dim actualTextGetFromTextBlock = actual.ToolTipTextBlock.Inlines _\n .OfType(Of Run).Select(Function(run) run.Text) _\n .Aggregate(Function(text1, text2) text1 + text2)\n ' When the text block is created, a unicode 'left to right' would be inserted between the space.\n ' Make sure it is removed.\n Dim leftToRightMarker = Char.ConvertFromUtf32(&H200E)\n Dim actualText = actualTextGetFromTextBlock.Replace(leftToRightMarker, String.Empty)\n Assert.Equal(expected.ToolTipTextBlock.Text, actualText)\n Assert.Equal(expected.AutomationName, actual.AutomationName)\n Assert.Equal(expected.MenuItemViewModels.Length, actual.MenuItemViewModels.Length)\n Assert.Equal(expected.ScaleFactor, actual.ScaleFactor)\n\n For i = 0 To expected.MenuItemViewModels.Length - 1\n Dim expectedMenuItem = expected.MenuItemViewModels(i)\n Dim actualMenuItem = actual.MenuItemViewModels(i)\n VerifyMenuItem(expectedMenuItem, actualMenuItem)\n Next\n\n End Sub\n\n Private Shared Sub VerifyMenuItem(expected As MenuItemViewModel, actual As MenuItemViewModel)\n Assert.Equal(expected.AutomationName, actual.AutomationName)\n Assert.Equal(expected.DisplayContent, actual.DisplayContent)\n Assert.Equal(expected.ImageMoniker, actual.ImageMoniker)\n\n Dim expectedTargetMenuItem = TryCast(expected, TargetMenuItemViewModel)\n Dim acutalTargetMenuItem = TryCast(actual, TargetMenuItemViewModel)\n If expectedTargetMenuItem IsNot Nothing AndAlso acutalTargetMenuItem IsNot Nothing Then\n Return\n End If\n\n Dim expectedMemberMenuItem = TryCast(expected, MemberMenuItemViewModel)\n Dim acutalMemberMenuItem = TryCast(actual, MemberMenuItemViewModel)\n If expectedMemberMenuItem IsNot Nothing AndAlso acutalMemberMenuItem IsNot Nothing Then\n Assert.Equal(expectedMemberMenuItem.Targets.Length, acutalMemberMenuItem.Targets.Length)\n For i = 0 To expectedMemberMenuItem.Targets.Length - 1\n VerifyMenuItem(expectedMemberMenuItem.Targets(i), acutalMemberMenuItem.Targets(i))\n Next\n\n Return\n End If\n\n ' At this stage, both of the items should be header\n Assert.True(TypeOf expected Is HeaderMenuItemViewModel)\n Assert.True(TypeOf actual Is HeaderMenuItemViewModel)\n End Sub\n\n Private Shared Function CreateTextBlock(text As String) As TextBlock\n Return New TextBlock With {\n .Text = text\n }\n End Function\n\n \n Public Function TestClassImplementsInterfaceRelationship() As Task\n Dim markup = \"\npublic interface IBar\n{\n}\npublic class Bar : IBar\n{\n}\"\n Dim tooltipTextForIBar = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar\")\n Dim targetForIBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types)).\n Add(New TargetMenuItemViewModel(\"Bar\", KnownMonikers.ClassPublic, \"Bar\", Nothing))\n\n Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, \"class Bar\")\n Dim targetForBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces)).\n Add(New TargetMenuItemViewModel(\"IBar\", KnownMonikers.InterfacePublic, \"IBar\", Nothing))\n\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From {\n {2, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implemented,\n CreateTextBlock(tooltipTextForIBar),\n tooltipTextForIBar,\n 1,\n targetForIBar)},\n {5, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implementing,\n CreateTextBlock(tooltipTextForBar),\n tooltipTextForBar,\n 1,\n targetForBar)}})\n End Function\n\n \n Public Function TestClassOverridesAbstractClassRelationship() As Task\n Dim markup = \"\npublic abstract class AbsBar\n{\n public abstract void Foo();\n}\n\npublic class Bar : AbsBar\n{\n public override void Foo();\n}\"\n\n Dim tooltipTextForAbsBar = String.Format(ServicesVSResources._0_is_inherited, \"class AbsBar\")\n Dim targetForAbsBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Derived_types, KnownMonikers.Overridden, ServicesVSResources.Derived_types)).\n Add(New TargetMenuItemViewModel(\"Bar\", KnownMonikers.ClassPublic, \"Bar\", Nothing))\n\n Dim tooltipTextForAbstractFoo = String.Format(ServicesVSResources._0_is_inherited, \"abstract void AbsBar.Foo()\")\n Dim targetForAbsFoo = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overriding_members, KnownMonikers.Overridden, ServicesVSResources.Overriding_members)).\n Add(New TargetMenuItemViewModel(\"Bar.Foo\", KnownMonikers.MethodPublic, \"Bar.Foo\", Nothing))\n\n Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, \"class Bar\")\n Dim targetForBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Base_Types, KnownMonikers.Overriding, ServicesVSResources.Base_Types)).\n Add(New TargetMenuItemViewModel(\"AbsBar\", KnownMonikers.ClassPublic, \"AbsBar\", Nothing))\n\n Dim tooltipTextForOverrideFoo = String.Format(ServicesVSResources._0_is_inherited, \"override void Bar.Foo()\")\n Dim targetForOverrideFoo = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overridden_members, KnownMonikers.Overriding, ServicesVSResources.Overridden_members)).\n Add(New TargetMenuItemViewModel(\"AbsBar.Foo\", KnownMonikers.MethodPublic, \"AbsBar.Foo\", Nothing))\n\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From {\n {2, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Overridden,\n CreateTextBlock(tooltipTextForAbsBar),\n tooltipTextForAbsBar,\n 1,\n targetForAbsBar)},\n {4, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Overridden,\n CreateTextBlock(tooltipTextForAbstractFoo),\n tooltipTextForAbstractFoo,\n 1,\n targetForAbsFoo)},\n {7, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Overriding,\n CreateTextBlock(tooltipTextForBar),\n tooltipTextForBar,\n 1,\n targetForBar)},\n {9, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Overriding,\n CreateTextBlock(tooltipTextForOverrideFoo),\n tooltipTextForOverrideFoo,\n 1,\n targetForOverrideFoo)}})\n End Function\n\n \n Public Function TestInterfaceImplementsInterfaceRelationship() As Task\n Dim markup = \"\npublic interface IBar1 { }\npublic interface IBar2 : IBar1 { }\npublic interface IBar3 : IBar2 { }\n\"\n Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar1\")\n Dim targetForIBar1 = ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types),\n New TargetMenuItemViewModel(\"IBar2\", KnownMonikers.InterfacePublic, \"IBar2\", Nothing),\n New TargetMenuItemViewModel(\"IBar3\", KnownMonikers.InterfacePublic, \"IBar3\", Nothing))\n\n Dim tooltipTextForIBar2 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar2\")\n Dim targetForIBar2 = ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces),\n New TargetMenuItemViewModel(\"IBar1\", KnownMonikers.InterfacePublic, \"IBar1\", Nothing),\n New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types),\n New TargetMenuItemViewModel(\"IBar3\", KnownMonikers.InterfacePublic, \"IBar3\", Nothing))\n\n Dim tooltipTextForIBar3 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar3\")\n Dim targetForIBar3 = ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces),\n New TargetMenuItemViewModel(\"IBar1\", KnownMonikers.InterfacePublic, \"IBar1\", Nothing),\n New TargetMenuItemViewModel(\"IBar2\", KnownMonikers.InterfacePublic, \"IBar2\", Nothing)).CastArray(Of MenuItemViewModel)\n\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From {\n {2, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implemented,\n CreateTextBlock(tooltipTextForIBar1),\n tooltipTextForIBar1,\n 1,\n targetForIBar1)},\n {3, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implementing,\n CreateTextBlock(tooltipTextForIBar2),\n tooltipTextForIBar2,\n 1,\n targetForIBar2)},\n {4, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implementing,\n CreateTextBlock(tooltipTextForIBar3),\n tooltipTextForIBar3,\n 1,\n targetForIBar3)}})\n End Function\n\n \n Public Function TestMutipleMemberOnSameline() As Task\n Dim markup = \"\nusing System;\ninterface IBar1\n{\n public event EventHandler e1, e2;\n}\n\npublic class BarSample : IBar1\n{\n public virtual event EventHandler e1, e2;\n}\"\n\n Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar1\")\n Dim targetForIBar1 = ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types),\n New TargetMenuItemViewModel(\"BarSample\", KnownMonikers.ClassPublic, \"BarSample\", Nothing))\n\n Dim tooltipTextForE1AndE2InInterface = ServicesVSResources.Multiple_members_are_inherited\n Dim targetForE1AndE2InInterface = ImmutableArray.Create(Of MenuItemViewModel)(\n New MemberMenuItemViewModel(\"event EventHandler IBar1.e1\", KnownMonikers.EventPublic, \"event EventHandler IBar1.e1\", ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members),\n New TargetMenuItemViewModel(\"BarSample.e1\", KnownMonikers.EventPublic, \"BarSample.e1\", Nothing))),\n New MemberMenuItemViewModel(\"event EventHandler IBar1.e2\", KnownMonikers.EventPublic, \"event EventHandler IBar1.e2\", ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members),\n New TargetMenuItemViewModel(\"BarSample.e2\", KnownMonikers.EventPublic, \"BarSample.e2\", Nothing))))\n\n Dim tooltipTextForBarSample = String.Format(ServicesVSResources._0_is_inherited, \"class BarSample\")\n Dim targetForBarSample = ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces),\n New TargetMenuItemViewModel(\"IBar1\", KnownMonikers.InterfaceInternal, \"IBar1\", Nothing))\n\n Dim tooltipTextForE1AndE2InBarSample = ServicesVSResources.Multiple_members_are_inherited\n Dim targetForE1AndE2InInBarSample = ImmutableArray.Create(Of MenuItemViewModel)(\n New MemberMenuItemViewModel(\"virtual event EventHandler BarSample.e1\", KnownMonikers.EventPublic, \"virtual event EventHandler BarSample.e1\", ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members),\n New TargetMenuItemViewModel(\"IBar1.e1\", KnownMonikers.EventPublic, \"IBar1.e1\", Nothing)).CastArray(Of MenuItemViewModel)),\n New MemberMenuItemViewModel(\"virtual event EventHandler BarSample.e2\", KnownMonikers.EventPublic, \"virtual event EventHandler BarSample.e2\", ImmutableArray.Create(Of MenuItemViewModel)(\n New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members),\n New TargetMenuItemViewModel(\"IBar1.e2\", KnownMonikers.EventPublic, \"IBar1.e2\", Nothing)).CastArray(Of MenuItemViewModel))) _\n .CastArray(Of MenuItemViewModel)\n\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From {\n {3, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implemented,\n CreateTextBlock(tooltipTextForIBar1),\n tooltipTextForIBar1,\n 1,\n targetForIBar1)},\n {5, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implemented,\n CreateTextBlock(tooltipTextForE1AndE2InInterface),\n String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 5),\n 1,\n targetForE1AndE2InInterface)},\n {8, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implementing,\n CreateTextBlock(tooltipTextForBarSample),\n tooltipTextForBarSample,\n 1,\n targetForBarSample)},\n {10, New InheritanceMarginGlyphViewModel(\n KnownMonikers.Implementing,\n CreateTextBlock(tooltipTextForE1AndE2InBarSample),\n String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 10),\n 1,\n targetForE1AndE2InInBarSample)}})\n End Function\n End Class\nEnd Namespace\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Collections.Immutable\nImports System.Threading\nImports System.Windows\nImports System.Windows.Documents\nImports Microsoft.CodeAnalysis\nImports Microsoft.CodeAnalysis.Editor.Shared.Utilities\nImports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces\nImports Microsoft.CodeAnalysis.InheritanceMargin\nImports Microsoft.CodeAnalysis.Shared.Extensions\nImports Microsoft.CodeAnalysis.Test.Utilities\nImports Microsoft.VisualStudio.Imaging\nImports Microsoft.VisualStudio.Imaging.Interop\nImports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin\nImports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph\nImports Microsoft.VisualStudio.Text.Classification\nImports Roslyn.Test.Utilities\n\nNamespace Microsoft.VisualStudio.LanguageServices.UnitTests.InheritanceMargin\n\n \n \n Public Class InheritanceMarginViewModelTests\n\n Private Shared s_defaultMargin As Thickness = New Thickness(4, 1, 4, 1)\n\n Private Shared s_indentMargin As Thickness = New Thickness(22, 1, 4, 1)\n\n Private Structure GlyphViewModelData\n Public ReadOnly Property ImageMoniker As ImageMoniker\n Public ReadOnly Property ToolTipText As String\n Public ReadOnly Property AutomationName As String\n Public ReadOnly Property ScaleFactor As Double\n Public ReadOnly Property MenuItems As MenuItemViewModelData()\n\n Public Sub New(imageMoniker As ImageMoniker, toolTipText As String, automationName As String, scaleFactor As Double, ParamArray menuItems() As MenuItemViewModelData)\n Me.ImageMoniker = imageMoniker\n Me.ToolTipText = toolTipText\n Me.AutomationName = automationName\n Me.ScaleFactor = scaleFactor\n Me.MenuItems = menuItems\n End Sub\n End Structure\n\n Private Structure MenuItemViewModelData\n Public ReadOnly Property AutomationName As String\n Public ReadOnly Property DisplayContent As String\n Public ReadOnly Property ImageMoniker As ImageMoniker\n Public ReadOnly Property ViewModelType As Type\n Public ReadOnly Property MenuItems As MenuItemViewModelData()\n\n Public Sub New(automationName As String, displayContent As String, imageMoniker As ImageMoniker, viewModelType As Type, ParamArray menuItems() As MenuItemViewModelData)\n Me.AutomationName = automationName\n Me.DisplayContent = displayContent\n Me.ImageMoniker = imageMoniker\n Me.ViewModelType = viewModelType\n Me.MenuItems = menuItems\n End Sub\n End Structure\n\n Private Shared Async Function VerifyAsync(markup As String, languageName As String, expectedViewModels As Dictionary(Of Integer, GlyphViewModelData)) As Task\n ' Add an lf before the document so that the line number starts\n ' with 1, which meets the line number in the editor (but in fact all things start from 0)\n Dim workspaceFile =\n \n CommonReferences=\"true\">\n <%= vbLf %>\n <%= markup.Replace(vbCrLf, vbLf) %>\n \n \n \n\n Dim cancellationToken As CancellationToken = CancellationToken.None\n Using workspace = TestWorkspace.Create(workspaceFile)\n Dim testDocument = workspace.Documents.Single()\n Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id)\n Dim service = document.GetRequiredLanguageService(Of IInheritanceMarginService)\n\n Dim classificationTypeMap = workspace.ExportProvider.GetExportedValue(Of ClassificationTypeMap)\n Dim classificationFormatMap = workspace.ExportProvider.GetExportedValue(Of IClassificationFormatMapService)\n\n ' For these tests, we need to be on UI thread, so don't call ConfigureAwait(False)\n Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(True)\n Dim inheritanceItems = Await service.GetInheritanceMemberItemsAsync(document, root.FullSpan, cancellationToken).ConfigureAwait(True)\n\n Dim acutalLineToTagDictionary = inheritanceItems.GroupBy(Function(item) item.LineNumber) _\n .ToDictionary(Function(grouping) grouping.Key,\n Function(grouping)\n Dim lineNumber = grouping.Key\n Dim items = grouping.Select(Function(g) g).ToImmutableArray()\n Return New InheritanceMarginTag(workspace, lineNumber, items)\n End Function)\n Assert.Equal(expectedViewModels.Count, acutalLineToTagDictionary.Count)\n\n For Each kvp In expectedViewModels\n Dim lineNumber = kvp.Key\n Dim expectedViewModel = kvp.Value\n Assert.True(acutalLineToTagDictionary.ContainsKey(lineNumber))\n\n Dim acutalTag = acutalLineToTagDictionary(lineNumber)\n ' Editor TestView zoom level is 100 based.\n Dim actualViewModel = InheritanceMarginGlyphViewModel.Create(\n classificationTypeMap, classificationFormatMap.GetClassificationFormatMap(\"tooltip\"), acutalTag, 100)\n\n VerifyTwoViewModelAreSame(expectedViewModel, actualViewModel)\n Next\n\n End Using\n End Function\n\n Private Shared Sub VerifyTwoViewModelAreSame(expected As GlyphViewModelData, actual As InheritanceMarginGlyphViewModel)\n Assert.Equal(expected.ImageMoniker, actual.ImageMoniker)\n Dim actualTextGetFromTextBlock = actual.ToolTipTextBlock.Inlines _\n .OfType(Of Run).Select(Function(run) run.Text) _\n .Aggregate(Function(text1, text2) text1 + text2)\n ' When the text block is created, a unicode 'left to right' would be inserted between the space.\n ' Make sure it is removed.\n Dim leftToRightMarker = Char.ConvertFromUtf32(&H200E)\n Dim actualText = actualTextGetFromTextBlock.Replace(leftToRightMarker, String.Empty)\n Assert.Equal(expected.ToolTipText, actualText)\n Assert.Equal(expected.AutomationName, actual.AutomationName)\n Assert.Equal(expected.MenuItems.Length, actual.MenuItemViewModels.Length)\n Assert.Equal(expected.ScaleFactor, actual.ScaleFactor)\n\n For i = 0 To expected.MenuItems.Length - 1\n Dim expectedMenuItem = expected.MenuItems(i)\n Dim actualMenuItem = actual.MenuItemViewModels(i)\n VerifyMenuItem(expectedMenuItem, actualMenuItem)\n Next\n\n End Sub\n\n Private Shared Sub VerifyMenuItem(expected As MenuItemViewModelData, actual As MenuItemViewModel)\n Assert.Equal(expected.AutomationName, actual.AutomationName)\n Assert.Equal(expected.DisplayContent, actual.DisplayContent)\n Assert.Equal(expected.ImageMoniker, actual.ImageMoniker)\n\n Assert.IsType(expected.ViewModelType, actual)\n\n If expected.ViewModelType = GetType(MemberMenuItemViewModel) Then\n Dim acutalMemberMenuItem = CType(actual, MemberMenuItemViewModel)\n Assert.Equal(expected.MenuItems.Length, acutalMemberMenuItem.Targets.Length)\n For i = 0 To expected.MenuItems.Length - 1\n VerifyMenuItem(expected.MenuItems(i), acutalMemberMenuItem.Targets(i))\n Next\n End If\n End Sub\n\n \n Public Function TestClassImplementsInterfaceRelationship() As Task\n Dim markup = \"\npublic interface IBar\n{\n}\npublic class Bar : IBar\n{\n}\"\n Dim tooltipTextForIBar = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar\")\n Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, \"class Bar\")\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From {\n {2, New GlyphViewModelData(\n KnownMonikers.Implemented,\n tooltipTextForIBar,\n tooltipTextForIBar,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"Bar\", \"Bar\", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))},\n {5, New GlyphViewModelData(\n KnownMonikers.Implementing,\n tooltipTextForBar,\n tooltipTextForBar,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Implemented_interfaces, ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar\", \"IBar\", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))}})\n End Function\n\n \n Public Function TestClassOverridesAbstractClassRelationship() As Task\n Dim markup = \"\npublic abstract class AbsBar\n{\n public abstract void Foo();\n}\n\npublic class Bar : AbsBar\n{\n public override void Foo();\n}\"\n\n Dim tooltipTextForAbsBar = String.Format(ServicesVSResources._0_is_inherited, \"class AbsBar\")\n Dim tooltipTextForAbstractFoo = String.Format(ServicesVSResources._0_is_inherited, \"abstract void AbsBar.Foo()\")\n Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, \"class Bar\")\n Dim tooltipTextForOverrideFoo = String.Format(ServicesVSResources._0_is_inherited, \"override void Bar.Foo()\")\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From {\n {2, New GlyphViewModelData(\n KnownMonikers.Overridden,\n tooltipTextForAbsBar,\n tooltipTextForAbsBar,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Derived_types, ServicesVSResources.Derived_types, KnownMonikers.Overridden, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"Bar\", \"Bar\", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))},\n {4, New GlyphViewModelData(\n KnownMonikers.Overridden,\n tooltipTextForAbstractFoo,\n tooltipTextForAbstractFoo,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Overriding_members, ServicesVSResources.Overriding_members, KnownMonikers.Overridden, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"Bar.Foo\", \"Bar.Foo\", KnownMonikers.MethodPublic, GetType(TargetMenuItemViewModel)))},\n {7, New GlyphViewModelData(\n KnownMonikers.Overriding,\n tooltipTextForBar,\n tooltipTextForBar,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Base_Types, ServicesVSResources.Base_Types, KnownMonikers.Overriding, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"AbsBar\", \"AbsBar\", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))},\n {9, New GlyphViewModelData(\n KnownMonikers.Overriding,\n tooltipTextForOverrideFoo,\n tooltipTextForOverrideFoo,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Overridden_members, ServicesVSResources.Overridden_members, KnownMonikers.Overriding, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"AbsBar.Foo\", \"AbsBar.Foo\", KnownMonikers.MethodPublic, GetType(TargetMenuItemViewModel)))}})\n End Function\n\n \n Public Function TestInterfaceImplementsInterfaceRelationship() As Task\n Dim markup = \"\npublic interface IBar1 { }\npublic interface IBar2 : IBar1 { }\npublic interface IBar3 : IBar2 { }\n\"\n Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar1\")\n Dim tooltipTextForIBar2 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar2\")\n Dim tooltipTextForIBar3 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar3\")\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From {\n {2, New GlyphViewModelData(\n KnownMonikers.Implemented,\n tooltipTextForIBar1,\n tooltipTextForIBar1,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar2\", \"IBar2\", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar3\", \"IBar3\", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))},\n {3, New GlyphViewModelData(\n KnownMonikers.Implementing,\n tooltipTextForIBar2,\n tooltipTextForIBar2,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Inherited_interfaces, ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar1\", \"IBar1\", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)),\n New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar3\", \"IBar3\", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))},\n {4, New GlyphViewModelData(\n KnownMonikers.Implementing,\n tooltipTextForIBar3,\n tooltipTextForIBar3,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Inherited_interfaces, ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar1\", \"IBar1\", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar2\", \"IBar2\", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))}})\n End Function\n\n \n Public Function TestMutipleMemberOnSameline() As Task\n Dim markup = \"\nusing System;\ninterface IBar1\n{\n public event EventHandler e1, e2;\n}\n\npublic class BarSample : IBar1\n{\n public virtual event EventHandler e1, e2;\n}\"\n\n Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, \"interface IBar1\")\n Dim tooltipTextForE1AndE2InInterface = ServicesVSResources.Multiple_members_are_inherited\n Dim tooltipTextForBarSample = String.Format(ServicesVSResources._0_is_inherited, \"class BarSample\")\n Dim tooltipTextForE1AndE2InBarSample = ServicesVSResources.Multiple_members_are_inherited\n Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From {\n {3, New GlyphViewModelData(\n KnownMonikers.Implemented,\n tooltipTextForIBar1,\n tooltipTextForIBar1,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"BarSample\", \"BarSample\", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))},\n {5, New GlyphViewModelData(\n KnownMonikers.Implemented,\n tooltipTextForE1AndE2InInterface,\n String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 5),\n 1,\n New MenuItemViewModelData(\"event EventHandler IBar1.e1\", \"event EventHandler IBar1.e1\", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel),\n New MenuItemViewModelData(ServicesVSResources.Implementing_members, ServicesVSResources.Implementing_members, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"BarSample.e1\", \"BarSample.e1\", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))),\n New MenuItemViewModelData(\"event EventHandler IBar1.e2\", \"event EventHandler IBar1.e2\", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel),\n New MenuItemViewModelData(ServicesVSResources.Implementing_members, ServicesVSResources.Implementing_members, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"BarSample.e2\", \"BarSample.e2\", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))))},\n {8, New GlyphViewModelData(\n KnownMonikers.Implementing,\n tooltipTextForBarSample,\n tooltipTextForBarSample,\n 1,\n New MenuItemViewModelData(ServicesVSResources.Implemented_interfaces, ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar1\", \"IBar1\", KnownMonikers.InterfaceInternal, GetType(TargetMenuItemViewModel)))},\n {10, New GlyphViewModelData(\n KnownMonikers.Implementing,\n tooltipTextForE1AndE2InBarSample,\n String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 10),\n 1,\n New MenuItemViewModelData(\"virtual event EventHandler BarSample.e1\", \"virtual event EventHandler BarSample.e1\", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel),\n New MenuItemViewModelData(ServicesVSResources.Implemented_members, ServicesVSResources.Implemented_members, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar1.e1\", \"IBar1.e1\", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))),\n New MenuItemViewModelData(\"virtual event EventHandler BarSample.e2\", \"virtual event EventHandler BarSample.e2\", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel),\n New MenuItemViewModelData(ServicesVSResources.Implemented_members, ServicesVSResources.Implemented_members, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)),\n New MenuItemViewModelData(\"IBar1.e2\", \"IBar1.e2\", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))))}})\n End Function\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":441,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Features/CSharp/Portable/Completion/KeywordRecommenders/IfKeywordRecommender.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders\n{\n internal class IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender\n {\n public IfKeywordRecommender()\n : base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true)\n {\n }\n\n protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)\n {\n return\n context.IsPreProcessorKeywordContext ||\n context.IsStatementContext ||\n context.IsGlobalStatementContext;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders\n{\n internal class IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender\n {\n public IfKeywordRecommender()\n : base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true)\n {\n }\n\n protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)\n {\n return\n context.IsPreProcessorKeywordContext ||\n context.IsStatementContext ||\n context.IsGlobalStatementContext;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":442,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/PEWriter/Miscellaneous.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing Roslyn.Utilities;\nusing EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;\n\nnamespace Microsoft.Cci\n{\n /// \n /// A container for static helper methods that are used for manipulating and computing iterators.\n /// \n internal static class IteratorHelper\n {\n /// \n /// True if the given enumerable is not null and contains at least one element.\n /// \n public static bool EnumerableIsNotEmpty([NotNullWhen(returnValue: true)] IEnumerable? enumerable)\n {\n if (enumerable == null)\n {\n return false;\n }\n\n var asIListT = enumerable as IList;\n if (asIListT != null)\n {\n return asIListT.Count != 0;\n }\n\n var asIList = enumerable as IList;\n if (asIList != null)\n {\n return asIList.Count != 0;\n }\n\n return enumerable.GetEnumerator().MoveNext();\n }\n\n /// \n /// True if the given enumerable is null or contains no elements\n /// \n public static bool EnumerableIsEmpty([NotNullWhen(returnValue: false)] IEnumerable? enumerable)\n {\n return !EnumerableIsNotEmpty(enumerable);\n }\n\n /// \n /// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0.\n /// \n public static uint EnumerableCount(IEnumerable? enumerable)\n {\n // ^ ensures result >= 0;\n if (enumerable == null)\n {\n return 0;\n }\n\n var asIListT = enumerable as IList;\n if (asIListT != null)\n {\n return (uint)asIListT.Count;\n }\n\n var asIList = enumerable as IList;\n if (asIList != null)\n {\n return (uint)asIList.Count;\n }\n\n uint result = 0;\n IEnumerator enumerator = enumerable.GetEnumerator();\n while (enumerator.MoveNext())\n {\n result++;\n }\n\n return result & 0x7FFFFFFF;\n }\n }\n\n /// \n /// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions.\n /// Each security attribute represents a serialized permission or permission set for a specified security action.\n /// The union of the security attributes with identical security action, define the permission set to which the security action applies.\n /// \n internal struct SecurityAttribute\n {\n public DeclarativeSecurityAction Action { get; }\n public ICustomAttribute Attribute { get; }\n\n public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute)\n {\n Action = action;\n Attribute = attribute;\n }\n }\n\n /// \n /// Information about how values of managed types should be marshalled to and from unmanaged types.\n /// \n internal interface IMarshallingInformation\n {\n /// \n /// or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string).\n /// \n object GetCustomMarshaller(EmitContext context);\n\n /// \n /// An argument string (cookie) passed to the custom marshaller at run time.\n /// \n string CustomMarshallerRuntimeArgument\n {\n get;\n }\n\n /// \n /// The unmanaged element type of the unmanaged array.\n /// -1 if it should be omitted from the marshal blob.\n /// \n System.Runtime.InteropServices.UnmanagedType ElementType\n {\n get;\n }\n\n /// \n /// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object.\n /// -1 if it should be omitted from the marshal blob.\n /// \n int IidParameterIndex\n {\n get;\n }\n\n /// \n /// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type\n /// is decided at runtime.\n /// \n System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; }\n\n /// \n /// The number of elements in the fixed size portion of the unmanaged array.\n /// -1 if it should be omitted from the marshal blob.\n /// \n int NumberOfElements\n {\n get;\n }\n\n /// \n /// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array.\n /// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way.\n /// \n short ParamIndex\n {\n get;\n }\n\n /// \n /// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype.\n /// (The element type of a safe array is VARIANT. The \"sub type\" specifies the value of all of the tag fields (vt) of the element values. )\n /// -1 if it should be omitted from the marshal blob.\n /// \n VarEnum SafeArrayElementSubtype\n {\n get;\n }\n\n /// \n /// A reference to the user defined type to which the variant values of all elements of the safe array must belong.\n /// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD.\n /// The \"user defined sub type\" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.)\n /// \n ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context);\n }\n\n /// \n /// Implemented by any entity that has a name.\n /// \n internal interface INamedEntity\n {\n /// \n /// The name of the entity.\n /// \n string? Name { get; }\n }\n\n /// \n /// The name of the entity depends on other metadata (tokens, signatures) originated from\n /// PeWriter.\n /// \n internal interface IContextualNamedEntity : INamedEntity\n {\n /// \n /// Method must be called before calling INamedEntity.Name.\n /// \n void AssociateWithMetadataWriter(MetadataWriter metadataWriter);\n }\n\n /// \n /// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition.\n /// Provides a way to determine the position where the entity appears in the parameter list.\n /// \n internal interface IParameterListEntry\n {\n /// \n /// The position in the parameter list where this instance can be found.\n /// \n ushort Index { get; }\n }\n\n /// \n /// Information that describes how a method from the underlying Platform is to be invoked.\n /// \n internal interface IPlatformInvokeInformation\n {\n /// \n /// Module providing the method/field.\n /// \n string? ModuleName { get; }\n\n /// \n /// Name of the method providing the implementation.\n /// \n string? EntryPointName { get; }\n\n /// \n /// Flags that determine marshalling behavior.\n /// \n MethodImportAttributes Flags { get; }\n }\n\n internal class ResourceSection\n {\n internal ResourceSection(byte[] sectionBytes, uint[] relocations)\n {\n RoslynDebug.Assert(sectionBytes != null);\n RoslynDebug.Assert(relocations != null);\n\n SectionBytes = sectionBytes;\n Relocations = relocations;\n }\n\n internal readonly byte[] SectionBytes;\n //This is the offset into SectionBytes that should be modified.\n //It should have the section's RVA added to it.\n internal readonly uint[] Relocations;\n }\n\n /// \n /// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file.\n /// See the Win32 UpdateResource method for more details.\n /// \n internal interface IWin32Resource\n {\n /// \n /// A string that identifies what type of resource this is. Only valid if this.TypeId &lt; 0.\n /// \n string TypeName\n {\n get;\n // ^ requires this.TypeId < 0;\n }\n\n /// \n /// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead.\n /// \n int TypeId\n {\n get;\n }\n\n /// \n /// The name of the resource. Only valid if this.Id &lt; 0.\n /// \n string Name\n {\n get;\n // ^ requires this.Id < 0; \n }\n\n /// \n /// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead.\n /// \n int Id { get; }\n\n /// \n /// The language for which this resource is appropriate.\n /// \n uint LanguageId { get; }\n\n /// \n /// The code page for which this resource is appropriate.\n /// \n uint CodePage { get; }\n\n /// \n /// The data of the resource.\n /// \n IEnumerable Data { get; }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing Roslyn.Utilities;\nusing EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;\n\nnamespace Microsoft.Cci\n{\n /// \n /// A container for static helper methods that are used for manipulating and computing iterators.\n /// \n internal static class IteratorHelper\n {\n /// \n /// True if the given enumerable is not null and contains at least one element.\n /// \n public static bool EnumerableIsNotEmpty([NotNullWhen(returnValue: true)] IEnumerable? enumerable)\n {\n if (enumerable == null)\n {\n return false;\n }\n\n var asIListT = enumerable as IList;\n if (asIListT != null)\n {\n return asIListT.Count != 0;\n }\n\n var asIList = enumerable as IList;\n if (asIList != null)\n {\n return asIList.Count != 0;\n }\n\n return enumerable.GetEnumerator().MoveNext();\n }\n\n /// \n /// True if the given enumerable is null or contains no elements\n /// \n public static bool EnumerableIsEmpty([NotNullWhen(returnValue: false)] IEnumerable? enumerable)\n {\n return !EnumerableIsNotEmpty(enumerable);\n }\n\n /// \n /// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0.\n /// \n public static uint EnumerableCount(IEnumerable? enumerable)\n {\n // ^ ensures result >= 0;\n if (enumerable == null)\n {\n return 0;\n }\n\n var asIListT = enumerable as IList;\n if (asIListT != null)\n {\n return (uint)asIListT.Count;\n }\n\n var asIList = enumerable as IList;\n if (asIList != null)\n {\n return (uint)asIList.Count;\n }\n\n uint result = 0;\n IEnumerator enumerator = enumerable.GetEnumerator();\n while (enumerator.MoveNext())\n {\n result++;\n }\n\n return result & 0x7FFFFFFF;\n }\n }\n\n /// \n /// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions.\n /// Each security attribute represents a serialized permission or permission set for a specified security action.\n /// The union of the security attributes with identical security action, define the permission set to which the security action applies.\n /// \n internal struct SecurityAttribute\n {\n public DeclarativeSecurityAction Action { get; }\n public ICustomAttribute Attribute { get; }\n\n public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute)\n {\n Action = action;\n Attribute = attribute;\n }\n }\n\n /// \n /// Information about how values of managed types should be marshalled to and from unmanaged types.\n /// \n internal interface IMarshallingInformation\n {\n /// \n /// or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string).\n /// \n object GetCustomMarshaller(EmitContext context);\n\n /// \n /// An argument string (cookie) passed to the custom marshaller at run time.\n /// \n string CustomMarshallerRuntimeArgument\n {\n get;\n }\n\n /// \n /// The unmanaged element type of the unmanaged array.\n /// -1 if it should be omitted from the marshal blob.\n /// \n System.Runtime.InteropServices.UnmanagedType ElementType\n {\n get;\n }\n\n /// \n /// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object.\n /// -1 if it should be omitted from the marshal blob.\n /// \n int IidParameterIndex\n {\n get;\n }\n\n /// \n /// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type\n /// is decided at runtime.\n /// \n System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; }\n\n /// \n /// The number of elements in the fixed size portion of the unmanaged array.\n /// -1 if it should be omitted from the marshal blob.\n /// \n int NumberOfElements\n {\n get;\n }\n\n /// \n /// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array.\n /// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way.\n /// \n short ParamIndex\n {\n get;\n }\n\n /// \n /// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype.\n /// (The element type of a safe array is VARIANT. The \"sub type\" specifies the value of all of the tag fields (vt) of the element values. )\n /// -1 if it should be omitted from the marshal blob.\n /// \n VarEnum SafeArrayElementSubtype\n {\n get;\n }\n\n /// \n /// A reference to the user defined type to which the variant values of all elements of the safe array must belong.\n /// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD.\n /// The \"user defined sub type\" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.)\n /// \n ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context);\n }\n\n /// \n /// Implemented by any entity that has a name.\n /// \n internal interface INamedEntity\n {\n /// \n /// The name of the entity.\n /// \n string? Name { get; }\n }\n\n /// \n /// The name of the entity depends on other metadata (tokens, signatures) originated from\n /// PeWriter.\n /// \n internal interface IContextualNamedEntity : INamedEntity\n {\n /// \n /// Method must be called before calling INamedEntity.Name.\n /// \n void AssociateWithMetadataWriter(MetadataWriter metadataWriter);\n }\n\n /// \n /// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition.\n /// Provides a way to determine the position where the entity appears in the parameter list.\n /// \n internal interface IParameterListEntry\n {\n /// \n /// The position in the parameter list where this instance can be found.\n /// \n ushort Index { get; }\n }\n\n /// \n /// Information that describes how a method from the underlying Platform is to be invoked.\n /// \n internal interface IPlatformInvokeInformation\n {\n /// \n /// Module providing the method/field.\n /// \n string? ModuleName { get; }\n\n /// \n /// Name of the method providing the implementation.\n /// \n string? EntryPointName { get; }\n\n /// \n /// Flags that determine marshalling behavior.\n /// \n MethodImportAttributes Flags { get; }\n }\n\n internal class ResourceSection\n {\n internal ResourceSection(byte[] sectionBytes, uint[] relocations)\n {\n RoslynDebug.Assert(sectionBytes != null);\n RoslynDebug.Assert(relocations != null);\n\n SectionBytes = sectionBytes;\n Relocations = relocations;\n }\n\n internal readonly byte[] SectionBytes;\n //This is the offset into SectionBytes that should be modified.\n //It should have the section's RVA added to it.\n internal readonly uint[] Relocations;\n }\n\n /// \n /// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file.\n /// See the Win32 UpdateResource method for more details.\n /// \n internal interface IWin32Resource\n {\n /// \n /// A string that identifies what type of resource this is. Only valid if this.TypeId &lt; 0.\n /// \n string TypeName\n {\n get;\n // ^ requires this.TypeId < 0;\n }\n\n /// \n /// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead.\n /// \n int TypeId\n {\n get;\n }\n\n /// \n /// The name of the resource. Only valid if this.Id &lt; 0.\n /// \n string Name\n {\n get;\n // ^ requires this.Id < 0; \n }\n\n /// \n /// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead.\n /// \n int Id { get; }\n\n /// \n /// The language for which this resource is appropriate.\n /// \n uint LanguageId { get; }\n\n /// \n /// The code page for which this resource is appropriate.\n /// \n uint CodePage { get; }\n\n /// \n /// The data of the resource.\n /// \n IEnumerable Data { get; }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":443,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/Core/CodeAnalysisTest/Collections/DebuggerAttributes.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n// NOTE: This code is derived from an implementation originally in dotnet/runtime:\n// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Diagnostics/DebuggerAttributes.cs\n//\n// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the\n// reference implementation.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.UnitTests.Collections\n{\n internal class DebuggerAttributeInfo\n {\n public object Instance { get; }\n public IEnumerable Properties { get; }\n\n public DebuggerAttributeInfo(object instance, IEnumerable properties)\n {\n Instance = instance;\n Properties = properties;\n }\n }\n\n internal static class DebuggerAttributes\n {\n internal static object? GetFieldValue(object obj, string fieldName)\n {\n var fieldInfo = GetField(obj, fieldName) ?? throw new InvalidOperationException();\n return fieldInfo.GetValue(obj);\n }\n\n internal static void InvokeDebuggerTypeProxyProperties(object obj)\n {\n DebuggerAttributeInfo info = ValidateDebuggerTypeProxyProperties(obj.GetType(), obj);\n foreach (PropertyInfo pi in info.Properties)\n {\n pi.GetValue(info.Instance, null);\n }\n }\n\n internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(object obj)\n {\n return ValidateDebuggerTypeProxyProperties(obj.GetType(), obj);\n }\n\n internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, object obj)\n {\n return ValidateDebuggerTypeProxyProperties(type, type.GenericTypeArguments, obj);\n }\n\n internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, Type[] genericTypeArguments, object obj)\n {\n Type proxyType = GetProxyType(type, genericTypeArguments);\n\n // Create an instance of the proxy type, and make sure we can access all of the instance properties\n // on the type without exception\n object proxyInstance = Activator.CreateInstance(proxyType, obj) ?? throw ExceptionUtilities.Unreachable;\n IEnumerable properties = GetDebuggerVisibleProperties(proxyType);\n return new DebuggerAttributeInfo(proxyInstance, properties);\n }\n\n public static DebuggerBrowsableState? GetDebuggerBrowsableState(MemberInfo info)\n {\n CustomAttributeData? debuggerBrowsableAttribute = info.CustomAttributes\n .SingleOrDefault(a => a.AttributeType == typeof(DebuggerBrowsableAttribute));\n // Enums in attribute constructors are boxed as ints, so cast to int? first.\n return (DebuggerBrowsableState?)(int?)debuggerBrowsableAttribute?.ConstructorArguments.Single().Value;\n }\n\n public static IEnumerable GetDebuggerVisibleFields(Type debuggerAttributeType)\n {\n // The debugger doesn't evaluate non-public members of type proxies.\n IEnumerable visibleFields = debuggerAttributeType.GetFields()\n .Where(fi => fi.IsPublic && GetDebuggerBrowsableState(fi) != DebuggerBrowsableState.Never);\n return visibleFields;\n }\n\n public static IEnumerable GetDebuggerVisibleProperties(Type debuggerAttributeType)\n {\n // The debugger doesn't evaluate non-public members of type proxies. GetGetMethod returns null if the getter is non-public.\n IEnumerable visibleProperties = debuggerAttributeType.GetProperties()\n .Where(pi => pi.GetGetMethod() != null && GetDebuggerBrowsableState(pi) != DebuggerBrowsableState.Never);\n return visibleProperties;\n }\n\n public static object? GetProxyObject(object obj) => Activator.CreateInstance(GetProxyType(obj), obj);\n\n public static Type GetProxyType(object obj) => GetProxyType(obj.GetType());\n\n public static Type GetProxyType(Type type) => GetProxyType(type, type.GenericTypeArguments);\n\n private static Type GetProxyType(Type type, Type[] genericTypeArguments)\n {\n // Get the DebuggerTypeProxyAttribute for obj\n var attrs =\n type.GetTypeInfo().CustomAttributes\n .Where(a => a.AttributeType == typeof(DebuggerTypeProxyAttribute))\n .ToArray();\n if (attrs.Length != 1)\n {\n throw new InvalidOperationException($\"Expected one DebuggerTypeProxyAttribute on {type}.\");\n }\n CustomAttributeData cad = attrs[0];\n\n Type? proxyType = cad.ConstructorArguments[0].ArgumentType == typeof(Type) ?\n (Type?)cad.ConstructorArguments[0].Value :\n Type.GetType((string)cad.ConstructorArguments[0].Value!);\n if (proxyType is null)\n throw new InvalidOperationException(\"Expected a non-null proxy type\");\n\n if (genericTypeArguments.Length > 0)\n {\n proxyType = proxyType.MakeGenericType(genericTypeArguments);\n }\n\n return proxyType;\n }\n\n internal static string ValidateDebuggerDisplayReferences(object obj)\n {\n // Get the DebuggerDisplayAttribute for obj\n var objType = obj.GetType();\n var attrs =\n objType.GetTypeInfo().CustomAttributes\n .Where(a => a.AttributeType == typeof(DebuggerDisplayAttribute))\n .ToArray();\n if (attrs.Length != 1)\n {\n throw new InvalidOperationException($\"Expected one DebuggerDisplayAttribute on {objType}.\");\n }\n var cad = attrs[0];\n\n // Get the text of the DebuggerDisplayAttribute\n string attrText = (string?)cad.ConstructorArguments[0].Value ?? throw new InvalidOperationException(\"Expected a non-null text\");\n\n var segments = attrText.Split(new[] { '{', '}' });\n\n if (segments.Length % 2 == 0)\n {\n throw new InvalidOperationException($\"The DebuggerDisplayAttribute for {objType} lacks a closing brace.\");\n }\n\n if (segments.Length == 1)\n {\n throw new InvalidOperationException($\"The DebuggerDisplayAttribute for {objType} doesn't reference any expressions.\");\n }\n\n var sb = new StringBuilder();\n\n for (int i = 0; i < segments.Length; i += 2)\n {\n string literal = segments[i];\n sb.Append(literal);\n\n if (i + 1 < segments.Length)\n {\n string reference = segments[i + 1];\n bool noQuotes = reference.EndsWith(\",nq\");\n\n reference = reference.Replace(\",nq\", string.Empty);\n\n // Evaluate the reference.\n if (!TryEvaluateReference(obj, reference, out object? member))\n {\n throw new InvalidOperationException($\"The DebuggerDisplayAttribute for {objType} contains the expression \\\"{reference}\\\".\");\n }\n\n string? memberString = GetDebuggerMemberString(member, noQuotes);\n\n sb.Append(memberString);\n }\n }\n\n return sb.ToString();\n }\n\n private static string? GetDebuggerMemberString(object? member, bool noQuotes)\n {\n string? memberString = \"null\";\n if (member != null)\n {\n memberString = member.ToString();\n if (member is string)\n {\n if (!noQuotes)\n {\n memberString = '\"' + memberString + '\"';\n }\n }\n else if (!IsPrimitiveType(member))\n {\n memberString = '{' + memberString + '}';\n }\n }\n\n return memberString;\n }\n\n private static bool IsPrimitiveType(object obj) =>\n obj is byte || obj is sbyte ||\n obj is short || obj is ushort ||\n obj is int || obj is uint ||\n obj is long || obj is ulong ||\n obj is float || obj is double;\n\n private static bool TryEvaluateReference(object obj, string reference, out object? member)\n {\n PropertyInfo? pi = GetProperty(obj, reference);\n if (pi != null)\n {\n member = pi.GetValue(obj);\n return true;\n }\n\n FieldInfo? fi = GetField(obj, reference);\n if (fi != null)\n {\n member = fi.GetValue(obj);\n return true;\n }\n\n member = null;\n return false;\n }\n\n private static FieldInfo? GetField(object obj, string fieldName)\n {\n for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType)\n {\n FieldInfo? fi = t.GetTypeInfo().GetDeclaredField(fieldName);\n if (fi != null)\n {\n return fi;\n }\n }\n return null;\n }\n\n private static PropertyInfo? GetProperty(object obj, string propertyName)\n {\n for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType)\n {\n PropertyInfo? pi = t.GetTypeInfo().GetDeclaredProperty(propertyName);\n if (pi != null)\n {\n return pi;\n }\n }\n return null;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n// NOTE: This code is derived from an implementation originally in dotnet/runtime:\n// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Diagnostics/DebuggerAttributes.cs\n//\n// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the\n// reference implementation.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.UnitTests.Collections\n{\n internal class DebuggerAttributeInfo\n {\n public object Instance { get; }\n public IEnumerable Properties { get; }\n\n public DebuggerAttributeInfo(object instance, IEnumerable properties)\n {\n Instance = instance;\n Properties = properties;\n }\n }\n\n internal static class DebuggerAttributes\n {\n internal static object? GetFieldValue(object obj, string fieldName)\n {\n var fieldInfo = GetField(obj, fieldName) ?? throw new InvalidOperationException();\n return fieldInfo.GetValue(obj);\n }\n\n internal static void InvokeDebuggerTypeProxyProperties(object obj)\n {\n DebuggerAttributeInfo info = ValidateDebuggerTypeProxyProperties(obj.GetType(), obj);\n foreach (PropertyInfo pi in info.Properties)\n {\n pi.GetValue(info.Instance, null);\n }\n }\n\n internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(object obj)\n {\n return ValidateDebuggerTypeProxyProperties(obj.GetType(), obj);\n }\n\n internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, object obj)\n {\n return ValidateDebuggerTypeProxyProperties(type, type.GenericTypeArguments, obj);\n }\n\n internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, Type[] genericTypeArguments, object obj)\n {\n Type proxyType = GetProxyType(type, genericTypeArguments);\n\n // Create an instance of the proxy type, and make sure we can access all of the instance properties\n // on the type without exception\n object proxyInstance = Activator.CreateInstance(proxyType, obj) ?? throw ExceptionUtilities.Unreachable;\n IEnumerable properties = GetDebuggerVisibleProperties(proxyType);\n return new DebuggerAttributeInfo(proxyInstance, properties);\n }\n\n public static DebuggerBrowsableState? GetDebuggerBrowsableState(MemberInfo info)\n {\n CustomAttributeData? debuggerBrowsableAttribute = info.CustomAttributes\n .SingleOrDefault(a => a.AttributeType == typeof(DebuggerBrowsableAttribute));\n // Enums in attribute constructors are boxed as ints, so cast to int? first.\n return (DebuggerBrowsableState?)(int?)debuggerBrowsableAttribute?.ConstructorArguments.Single().Value;\n }\n\n public static IEnumerable GetDebuggerVisibleFields(Type debuggerAttributeType)\n {\n // The debugger doesn't evaluate non-public members of type proxies.\n IEnumerable visibleFields = debuggerAttributeType.GetFields()\n .Where(fi => fi.IsPublic && GetDebuggerBrowsableState(fi) != DebuggerBrowsableState.Never);\n return visibleFields;\n }\n\n public static IEnumerable GetDebuggerVisibleProperties(Type debuggerAttributeType)\n {\n // The debugger doesn't evaluate non-public members of type proxies. GetGetMethod returns null if the getter is non-public.\n IEnumerable visibleProperties = debuggerAttributeType.GetProperties()\n .Where(pi => pi.GetGetMethod() != null && GetDebuggerBrowsableState(pi) != DebuggerBrowsableState.Never);\n return visibleProperties;\n }\n\n public static object? GetProxyObject(object obj) => Activator.CreateInstance(GetProxyType(obj), obj);\n\n public static Type GetProxyType(object obj) => GetProxyType(obj.GetType());\n\n public static Type GetProxyType(Type type) => GetProxyType(type, type.GenericTypeArguments);\n\n private static Type GetProxyType(Type type, Type[] genericTypeArguments)\n {\n // Get the DebuggerTypeProxyAttribute for obj\n var attrs =\n type.GetTypeInfo().CustomAttributes\n .Where(a => a.AttributeType == typeof(DebuggerTypeProxyAttribute))\n .ToArray();\n if (attrs.Length != 1)\n {\n throw new InvalidOperationException($\"Expected one DebuggerTypeProxyAttribute on {type}.\");\n }\n CustomAttributeData cad = attrs[0];\n\n Type? proxyType = cad.ConstructorArguments[0].ArgumentType == typeof(Type) ?\n (Type?)cad.ConstructorArguments[0].Value :\n Type.GetType((string)cad.ConstructorArguments[0].Value!);\n if (proxyType is null)\n throw new InvalidOperationException(\"Expected a non-null proxy type\");\n\n if (genericTypeArguments.Length > 0)\n {\n proxyType = proxyType.MakeGenericType(genericTypeArguments);\n }\n\n return proxyType;\n }\n\n internal static string ValidateDebuggerDisplayReferences(object obj)\n {\n // Get the DebuggerDisplayAttribute for obj\n var objType = obj.GetType();\n var attrs =\n objType.GetTypeInfo().CustomAttributes\n .Where(a => a.AttributeType == typeof(DebuggerDisplayAttribute))\n .ToArray();\n if (attrs.Length != 1)\n {\n throw new InvalidOperationException($\"Expected one DebuggerDisplayAttribute on {objType}.\");\n }\n var cad = attrs[0];\n\n // Get the text of the DebuggerDisplayAttribute\n string attrText = (string?)cad.ConstructorArguments[0].Value ?? throw new InvalidOperationException(\"Expected a non-null text\");\n\n var segments = attrText.Split(new[] { '{', '}' });\n\n if (segments.Length % 2 == 0)\n {\n throw new InvalidOperationException($\"The DebuggerDisplayAttribute for {objType} lacks a closing brace.\");\n }\n\n if (segments.Length == 1)\n {\n throw new InvalidOperationException($\"The DebuggerDisplayAttribute for {objType} doesn't reference any expressions.\");\n }\n\n var sb = new StringBuilder();\n\n for (int i = 0; i < segments.Length; i += 2)\n {\n string literal = segments[i];\n sb.Append(literal);\n\n if (i + 1 < segments.Length)\n {\n string reference = segments[i + 1];\n bool noQuotes = reference.EndsWith(\",nq\");\n\n reference = reference.Replace(\",nq\", string.Empty);\n\n // Evaluate the reference.\n if (!TryEvaluateReference(obj, reference, out object? member))\n {\n throw new InvalidOperationException($\"The DebuggerDisplayAttribute for {objType} contains the expression \\\"{reference}\\\".\");\n }\n\n string? memberString = GetDebuggerMemberString(member, noQuotes);\n\n sb.Append(memberString);\n }\n }\n\n return sb.ToString();\n }\n\n private static string? GetDebuggerMemberString(object? member, bool noQuotes)\n {\n string? memberString = \"null\";\n if (member != null)\n {\n memberString = member.ToString();\n if (member is string)\n {\n if (!noQuotes)\n {\n memberString = '\"' + memberString + '\"';\n }\n }\n else if (!IsPrimitiveType(member))\n {\n memberString = '{' + memberString + '}';\n }\n }\n\n return memberString;\n }\n\n private static bool IsPrimitiveType(object obj) =>\n obj is byte || obj is sbyte ||\n obj is short || obj is ushort ||\n obj is int || obj is uint ||\n obj is long || obj is ulong ||\n obj is float || obj is double;\n\n private static bool TryEvaluateReference(object obj, string reference, out object? member)\n {\n PropertyInfo? pi = GetProperty(obj, reference);\n if (pi != null)\n {\n member = pi.GetValue(obj);\n return true;\n }\n\n FieldInfo? fi = GetField(obj, reference);\n if (fi != null)\n {\n member = fi.GetValue(obj);\n return true;\n }\n\n member = null;\n return false;\n }\n\n private static FieldInfo? GetField(object obj, string fieldName)\n {\n for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType)\n {\n FieldInfo? fi = t.GetTypeInfo().GetDeclaredField(fieldName);\n if (fi != null)\n {\n return fi;\n }\n }\n return null;\n }\n\n private static PropertyInfo? GetProperty(object obj, string propertyName)\n {\n for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType)\n {\n PropertyInfo? pi = t.GetTypeInfo().GetDeclaredProperty(propertyName);\n if (pi != null)\n {\n return pi;\n }\n }\n return null;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":444,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Features/CSharp/Portable/ExtractMethod/CSharpSyntaxTriviaServiceFactory.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Composition;\nusing Microsoft.CodeAnalysis.ExtractMethod;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Host.Mef;\n\nnamespace Microsoft.CodeAnalysis.CSharp.ExtractMethod\n{\n [ExportLanguageServiceFactory(typeof(ISyntaxTriviaService), LanguageNames.CSharp), Shared]\n internal class CSharpSyntaxTriviaServiceFactory : ILanguageServiceFactory\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public CSharpSyntaxTriviaServiceFactory()\n {\n }\n\n public ILanguageService CreateLanguageService(HostLanguageServices provider)\n => CSharpSyntaxTriviaService.Instance;\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Composition;\nusing Microsoft.CodeAnalysis.ExtractMethod;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Host.Mef;\n\nnamespace Microsoft.CodeAnalysis.CSharp.ExtractMethod\n{\n [ExportLanguageServiceFactory(typeof(ISyntaxTriviaService), LanguageNames.CSharp), Shared]\n internal class CSharpSyntaxTriviaServiceFactory : ILanguageServiceFactory\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public CSharpSyntaxTriviaServiceFactory()\n {\n }\n\n public ILanguageService CreateLanguageService(HostLanguageServices provider)\n => CSharpSyntaxTriviaService.Instance;\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":445,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Impl/CodeModel/ProjectCodeModelFactory.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.ComponentModel.Composition;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CodeGeneration;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.Shared.TestHooks;\nusing Microsoft.CodeAnalysis.SolutionCrawler;\nusing Microsoft.VisualStudio.Shell;\nusing Microsoft.VisualStudio.Threading;\nusing Roslyn.Utilities;\nusing Task = System.Threading.Tasks.Task;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel\n{\n [Export(typeof(IProjectCodeModelFactory))]\n [Export(typeof(ProjectCodeModelFactory))]\n internal sealed class ProjectCodeModelFactory : ForegroundThreadAffinitizedObject, IProjectCodeModelFactory\n {\n private readonly ConcurrentDictionary _projectCodeModels = new ConcurrentDictionary();\n\n private readonly VisualStudioWorkspace _visualStudioWorkspace;\n private readonly IServiceProvider _serviceProvider;\n\n private readonly IThreadingContext _threadingContext;\n\n private readonly AsyncBatchingWorkQueue _documentsToFireEventsFor;\n\n [ImportingConstructor]\n [SuppressMessage(\"RoslynDiagnosticsReliability\", \"RS0033:Importing constructor should be [Obsolete]\", Justification = \"Used in test code: https://github.com/dotnet/roslyn/issues/42814\")]\n public ProjectCodeModelFactory(\n VisualStudioWorkspace visualStudioWorkspace,\n [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider,\n IThreadingContext threadingContext,\n IAsynchronousOperationListenerProvider listenerProvider)\n : base(threadingContext, assertIsForeground: false)\n {\n _visualStudioWorkspace = visualStudioWorkspace;\n _serviceProvider = serviceProvider;\n _threadingContext = threadingContext;\n\n Listener = listenerProvider.GetListener(FeatureAttribute.CodeModel);\n\n // Queue up notifications we hear about docs changing. that way we don't have to fire events multiple times\n // for the same documents. Once enough time has passed, take the documents that were changed and run\n // through them, firing their latest events.\n _documentsToFireEventsFor = new AsyncBatchingWorkQueue(\n InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan,\n ProcessNextDocumentBatchAsync,\n // We only care about unique doc-ids, so pass in this comparer to collapse streams of changes for a\n // single document down to one notification.\n EqualityComparer.Default,\n Listener,\n threadingContext.DisposalToken);\n\n _visualStudioWorkspace.WorkspaceChanged += OnWorkspaceChanged;\n }\n\n internal IAsynchronousOperationListener Listener { get; }\n\n private async ValueTask ProcessNextDocumentBatchAsync(\n ImmutableArray documentIds, CancellationToken cancellationToken)\n {\n // This logic preserves the previous behavior we had with IForegroundNotificationService.\n // Specifically, we don't run on the UI thread for more than 15ms at a time. And once we \n // have, we wait 50ms before continuing. These constants are just what we defined from\n // legacy, and otherwise have no special meaning.\n const int MaxTimeSlice = 15;\n var delayBetweenProcessing = TimeSpan.FromMilliseconds(50);\n\n Debug.Assert(!_threadingContext.JoinableTaskContext.IsOnMainThread, \"The following context switch is not expected to cause runtime overhead.\");\n await TaskScheduler.Default;\n\n // Ensure MEF services used by the code model are initially obtained on a background thread.\n // This code avoids allocations where possible.\n // https://github.com/dotnet/roslyn/issues/54159\n string? previousLanguage = null;\n foreach (var (_, projectState) in _visualStudioWorkspace.CurrentSolution.State.ProjectStates)\n {\n if (projectState.Language == previousLanguage)\n {\n // Avoid duplicate calls if the language did not change\n continue;\n }\n\n previousLanguage = projectState.Language;\n projectState.LanguageServices.GetService();\n projectState.LanguageServices.GetService();\n projectState.LanguageServices.GetService();\n }\n\n await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);\n\n var stopwatch = SharedStopwatch.StartNew();\n foreach (var documentId in documentIds)\n {\n FireEventsForDocument(documentId);\n\n // Keep firing events for this doc, as long as we haven't exceeded the max amount\n // of waiting time, and there's no user input that should take precedence.\n if (stopwatch.Elapsed.Ticks > MaxTimeSlice || IsInputPending())\n {\n await this.Listener.Delay(delayBetweenProcessing, cancellationToken).ConfigureAwait(true);\n stopwatch = SharedStopwatch.StartNew();\n }\n }\n\n return;\n\n void FireEventsForDocument(DocumentId documentId)\n {\n // If we've been asked to shutdown, don't bother reporting any more events.\n if (_threadingContext.DisposalToken.IsCancellationRequested)\n return;\n\n var projectCodeModel = this.TryGetProjectCodeModel(documentId.ProjectId);\n if (projectCodeModel == null)\n return;\n\n var filename = _visualStudioWorkspace.GetFilePath(documentId);\n if (filename == null)\n return;\n\n if (!projectCodeModel.TryGetCachedFileCodeModel(filename, out var fileCodeModelHandle))\n return;\n\n var codeModel = fileCodeModelHandle.Object;\n codeModel.FireEvents();\n return;\n }\n }\n\n private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)\n {\n // Events that can't change existing code model items. Can just ignore them.\n switch (e.Kind)\n {\n case WorkspaceChangeKind.SolutionAdded:\n case WorkspaceChangeKind.ProjectAdded:\n case WorkspaceChangeKind.DocumentAdded:\n case WorkspaceChangeKind.AdditionalDocumentAdded:\n case WorkspaceChangeKind.AdditionalDocumentRemoved:\n case WorkspaceChangeKind.AdditionalDocumentReloaded:\n case WorkspaceChangeKind.AdditionalDocumentChanged:\n case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:\n case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved:\n case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded:\n case WorkspaceChangeKind.AnalyzerConfigDocumentChanged:\n return;\n case WorkspaceChangeKind.DocumentRemoved:\n case WorkspaceChangeKind.DocumentChanged:\n // Fast path when we know we affected a document that could have had code model elements in it. No\n // need to do a solution diff in this case.\n _documentsToFireEventsFor.AddWork(e.DocumentId!);\n return;\n }\n\n // Other type of event that could indicate a doc change/removal. Have to actually analyze the change to\n // determine what we should do here.\n\n var changes = e.OldSolution.GetChanges(e.NewSolution);\n\n foreach (var project in changes.GetRemovedProjects())\n _documentsToFireEventsFor.AddWork(project.DocumentIds);\n\n foreach (var projectChange in changes.GetProjectChanges())\n {\n _documentsToFireEventsFor.AddWork(projectChange.GetRemovedDocuments());\n _documentsToFireEventsFor.AddWork(projectChange.GetChangedDocuments());\n }\n }\n\n public IProjectCodeModel CreateProjectCodeModel(ProjectId id, ICodeModelInstanceFactory codeModelInstanceFactory)\n {\n var projectCodeModel = new ProjectCodeModel(_threadingContext, id, codeModelInstanceFactory, _visualStudioWorkspace, _serviceProvider, this);\n if (!_projectCodeModels.TryAdd(id, projectCodeModel))\n {\n throw new InvalidOperationException($\"A {nameof(IProjectCodeModel)} has already been created for project with ID {id}\");\n }\n\n return projectCodeModel;\n }\n\n public ProjectCodeModel GetProjectCodeModel(ProjectId id)\n {\n if (!_projectCodeModels.TryGetValue(id, out var projectCodeModel))\n {\n throw new InvalidOperationException($\"No {nameof(ProjectCodeModel)} exists for project with ID {id}\");\n }\n\n return projectCodeModel;\n }\n\n public IEnumerable GetAllProjectCodeModels()\n => _projectCodeModels.Values;\n\n internal void OnProjectClosed(ProjectId projectId)\n => _projectCodeModels.TryRemove(projectId, out _);\n\n public ProjectCodeModel TryGetProjectCodeModel(ProjectId id)\n {\n _projectCodeModels.TryGetValue(id, out var projectCodeModel);\n return projectCodeModel;\n }\n\n public EnvDTE.FileCodeModel GetOrCreateFileCodeModel(ProjectId id, string filePath)\n => GetProjectCodeModel(id).GetOrCreateFileCodeModel(filePath).Handle;\n\n public void ScheduleDeferredCleanupTask(Action a)\n {\n _ = _threadingContext.RunWithShutdownBlockAsync(async cancellationToken =>\n {\n await _threadingContext.JoinableTaskFactory.StartOnIdle(\n () => a(cancellationToken),\n VsTaskRunContext.UIThreadNormalPriority);\n });\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.ComponentModel.Composition;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CodeGeneration;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.Shared.TestHooks;\nusing Microsoft.CodeAnalysis.SolutionCrawler;\nusing Microsoft.VisualStudio.Shell;\nusing Microsoft.VisualStudio.Threading;\nusing Roslyn.Utilities;\nusing Task = System.Threading.Tasks.Task;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel\n{\n [Export(typeof(IProjectCodeModelFactory))]\n [Export(typeof(ProjectCodeModelFactory))]\n internal sealed class ProjectCodeModelFactory : ForegroundThreadAffinitizedObject, IProjectCodeModelFactory\n {\n private readonly ConcurrentDictionary _projectCodeModels = new ConcurrentDictionary();\n\n private readonly VisualStudioWorkspace _visualStudioWorkspace;\n private readonly IServiceProvider _serviceProvider;\n\n private readonly IThreadingContext _threadingContext;\n\n private readonly AsyncBatchingWorkQueue _documentsToFireEventsFor;\n\n [ImportingConstructor]\n [SuppressMessage(\"RoslynDiagnosticsReliability\", \"RS0033:Importing constructor should be [Obsolete]\", Justification = \"Used in test code: https://github.com/dotnet/roslyn/issues/42814\")]\n public ProjectCodeModelFactory(\n VisualStudioWorkspace visualStudioWorkspace,\n [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider,\n IThreadingContext threadingContext,\n IAsynchronousOperationListenerProvider listenerProvider)\n : base(threadingContext, assertIsForeground: false)\n {\n _visualStudioWorkspace = visualStudioWorkspace;\n _serviceProvider = serviceProvider;\n _threadingContext = threadingContext;\n\n Listener = listenerProvider.GetListener(FeatureAttribute.CodeModel);\n\n // Queue up notifications we hear about docs changing. that way we don't have to fire events multiple times\n // for the same documents. Once enough time has passed, take the documents that were changed and run\n // through them, firing their latest events.\n _documentsToFireEventsFor = new AsyncBatchingWorkQueue(\n InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan,\n ProcessNextDocumentBatchAsync,\n // We only care about unique doc-ids, so pass in this comparer to collapse streams of changes for a\n // single document down to one notification.\n EqualityComparer.Default,\n Listener,\n threadingContext.DisposalToken);\n\n _visualStudioWorkspace.WorkspaceChanged += OnWorkspaceChanged;\n }\n\n internal IAsynchronousOperationListener Listener { get; }\n\n private async ValueTask ProcessNextDocumentBatchAsync(\n ImmutableArray documentIds, CancellationToken cancellationToken)\n {\n // This logic preserves the previous behavior we had with IForegroundNotificationService.\n // Specifically, we don't run on the UI thread for more than 15ms at a time. And once we \n // have, we wait 50ms before continuing. These constants are just what we defined from\n // legacy, and otherwise have no special meaning.\n const int MaxTimeSlice = 15;\n var delayBetweenProcessing = TimeSpan.FromMilliseconds(50);\n\n Debug.Assert(!_threadingContext.JoinableTaskContext.IsOnMainThread, \"The following context switch is not expected to cause runtime overhead.\");\n await TaskScheduler.Default;\n\n // Ensure MEF services used by the code model are initially obtained on a background thread.\n // This code avoids allocations where possible.\n // https://github.com/dotnet/roslyn/issues/54159\n string? previousLanguage = null;\n foreach (var (_, projectState) in _visualStudioWorkspace.CurrentSolution.State.ProjectStates)\n {\n if (projectState.Language == previousLanguage)\n {\n // Avoid duplicate calls if the language did not change\n continue;\n }\n\n previousLanguage = projectState.Language;\n projectState.LanguageServices.GetService();\n projectState.LanguageServices.GetService();\n projectState.LanguageServices.GetService();\n }\n\n await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);\n\n var stopwatch = SharedStopwatch.StartNew();\n foreach (var documentId in documentIds)\n {\n FireEventsForDocument(documentId);\n\n // Keep firing events for this doc, as long as we haven't exceeded the max amount\n // of waiting time, and there's no user input that should take precedence.\n if (stopwatch.Elapsed.Ticks > MaxTimeSlice || IsInputPending())\n {\n await this.Listener.Delay(delayBetweenProcessing, cancellationToken).ConfigureAwait(true);\n stopwatch = SharedStopwatch.StartNew();\n }\n }\n\n return;\n\n void FireEventsForDocument(DocumentId documentId)\n {\n // If we've been asked to shutdown, don't bother reporting any more events.\n if (_threadingContext.DisposalToken.IsCancellationRequested)\n return;\n\n var projectCodeModel = this.TryGetProjectCodeModel(documentId.ProjectId);\n if (projectCodeModel == null)\n return;\n\n var filename = _visualStudioWorkspace.GetFilePath(documentId);\n if (filename == null)\n return;\n\n if (!projectCodeModel.TryGetCachedFileCodeModel(filename, out var fileCodeModelHandle))\n return;\n\n var codeModel = fileCodeModelHandle.Object;\n codeModel.FireEvents();\n return;\n }\n }\n\n private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)\n {\n // Events that can't change existing code model items. Can just ignore them.\n switch (e.Kind)\n {\n case WorkspaceChangeKind.SolutionAdded:\n case WorkspaceChangeKind.ProjectAdded:\n case WorkspaceChangeKind.DocumentAdded:\n case WorkspaceChangeKind.AdditionalDocumentAdded:\n case WorkspaceChangeKind.AdditionalDocumentRemoved:\n case WorkspaceChangeKind.AdditionalDocumentReloaded:\n case WorkspaceChangeKind.AdditionalDocumentChanged:\n case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:\n case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved:\n case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded:\n case WorkspaceChangeKind.AnalyzerConfigDocumentChanged:\n return;\n case WorkspaceChangeKind.DocumentRemoved:\n case WorkspaceChangeKind.DocumentChanged:\n // Fast path when we know we affected a document that could have had code model elements in it. No\n // need to do a solution diff in this case.\n _documentsToFireEventsFor.AddWork(e.DocumentId!);\n return;\n }\n\n // Other type of event that could indicate a doc change/removal. Have to actually analyze the change to\n // determine what we should do here.\n\n var changes = e.OldSolution.GetChanges(e.NewSolution);\n\n foreach (var project in changes.GetRemovedProjects())\n _documentsToFireEventsFor.AddWork(project.DocumentIds);\n\n foreach (var projectChange in changes.GetProjectChanges())\n {\n _documentsToFireEventsFor.AddWork(projectChange.GetRemovedDocuments());\n _documentsToFireEventsFor.AddWork(projectChange.GetChangedDocuments());\n }\n }\n\n public IProjectCodeModel CreateProjectCodeModel(ProjectId id, ICodeModelInstanceFactory codeModelInstanceFactory)\n {\n var projectCodeModel = new ProjectCodeModel(_threadingContext, id, codeModelInstanceFactory, _visualStudioWorkspace, _serviceProvider, this);\n if (!_projectCodeModels.TryAdd(id, projectCodeModel))\n {\n throw new InvalidOperationException($\"A {nameof(IProjectCodeModel)} has already been created for project with ID {id}\");\n }\n\n return projectCodeModel;\n }\n\n public ProjectCodeModel GetProjectCodeModel(ProjectId id)\n {\n if (!_projectCodeModels.TryGetValue(id, out var projectCodeModel))\n {\n throw new InvalidOperationException($\"No {nameof(ProjectCodeModel)} exists for project with ID {id}\");\n }\n\n return projectCodeModel;\n }\n\n public IEnumerable GetAllProjectCodeModels()\n => _projectCodeModels.Values;\n\n internal void OnProjectClosed(ProjectId projectId)\n => _projectCodeModels.TryRemove(projectId, out _);\n\n public ProjectCodeModel TryGetProjectCodeModel(ProjectId id)\n {\n _projectCodeModels.TryGetValue(id, out var projectCodeModel);\n return projectCodeModel;\n }\n\n public EnvDTE.FileCodeModel GetOrCreateFileCodeModel(ProjectId id, string filePath)\n => GetProjectCodeModel(id).GetOrCreateFileCodeModel(filePath).Handle;\n\n public void ScheduleDeferredCleanupTask(Action a)\n {\n _ = _threadingContext.RunWithShutdownBlockAsync(async cancellationToken =>\n {\n await _threadingContext.JoinableTaskFactory.StartOnIdle(\n () => a(cancellationToken),\n VsTaskRunContext.UIThreadNormalPriority);\n });\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":446,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/Completion/CompletionRules.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Immutable;\n\nnamespace Microsoft.CodeAnalysis.Completion\n{\n /// \n /// Presentation and behavior rules for completion.\n /// \n public sealed class CompletionRules\n {\n /// \n /// True if the completion list should be dismissed if the user's typing causes it to filter\n /// and display no items.\n /// \n public bool DismissIfEmpty { get; }\n\n /// \n /// True if the list should be dismissed when the user deletes the last character in the span.\n /// \n public bool DismissIfLastCharacterDeleted { get; }\n\n /// \n /// The default set of typed characters that cause the selected item to be committed.\n /// Individual s can override this.\n /// \n public ImmutableArray DefaultCommitCharacters { get; }\n\n /// \n /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.\n /// Individual s can override this.\n /// \n public EnterKeyRule DefaultEnterKeyRule { get; }\n\n /// \n /// The rule determining how snippets work.\n /// \n public SnippetsRule SnippetsRule { get; }\n\n private CompletionRules(\n bool dismissIfEmpty,\n bool dismissIfLastCharacterDeleted,\n ImmutableArray defaultCommitCharacters,\n EnterKeyRule defaultEnterKeyRule,\n SnippetsRule snippetsRule)\n {\n DismissIfEmpty = dismissIfEmpty;\n DismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted;\n DefaultCommitCharacters = defaultCommitCharacters.NullToEmpty();\n DefaultEnterKeyRule = defaultEnterKeyRule;\n SnippetsRule = snippetsRule;\n }\n\n /// \n /// Creates a new instance.\n /// \n /// True if the completion list should be dismissed if the user's typing causes it to filter and display no items.\n /// True if the list should be dismissed when the user deletes the last character in the span.\n /// The default set of typed characters that cause the selected item to be committed.\n /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.\n public static CompletionRules Create(\n bool dismissIfEmpty,\n bool dismissIfLastCharacterDeleted,\n ImmutableArray defaultCommitCharacters,\n EnterKeyRule defaultEnterKeyRule)\n {\n return Create(dismissIfEmpty, dismissIfLastCharacterDeleted, defaultCommitCharacters,\n defaultEnterKeyRule, SnippetsRule.Default);\n }\n\n /// \n /// Creates a new instance.\n /// \n /// True if the completion list should be dismissed if the user's typing causes it to filter and display no items.\n /// True if the list should be dismissed when the user deletes the last character in the span.\n /// The default set of typed characters that cause the selected item to be committed.\n /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.\n /// The rule that controls snippets behavior.\n public static CompletionRules Create(\n bool dismissIfEmpty = false,\n bool dismissIfLastCharacterDeleted = false,\n ImmutableArray defaultCommitCharacters = default,\n EnterKeyRule defaultEnterKeyRule = EnterKeyRule.Default,\n SnippetsRule snippetsRule = SnippetsRule.Default)\n {\n return new CompletionRules(\n dismissIfEmpty: dismissIfEmpty,\n dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted,\n defaultCommitCharacters: defaultCommitCharacters,\n defaultEnterKeyRule: defaultEnterKeyRule,\n snippetsRule: snippetsRule);\n }\n\n private CompletionRules With(\n Optional dismissIfEmpty = default,\n Optional dismissIfLastCharacterDeleted = default,\n Optional> defaultCommitCharacters = default,\n Optional defaultEnterKeyRule = default,\n Optional snippetsRule = default)\n {\n var newDismissIfEmpty = dismissIfEmpty.HasValue ? dismissIfEmpty.Value : DismissIfEmpty;\n var newDismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted.HasValue ? dismissIfLastCharacterDeleted.Value : DismissIfLastCharacterDeleted;\n var newDefaultCommitCharacters = defaultCommitCharacters.HasValue ? defaultCommitCharacters.Value : DefaultCommitCharacters;\n var newDefaultEnterKeyRule = defaultEnterKeyRule.HasValue ? defaultEnterKeyRule.Value : DefaultEnterKeyRule;\n var newSnippetsRule = snippetsRule.HasValue ? snippetsRule.Value : SnippetsRule;\n\n if (newDismissIfEmpty == DismissIfEmpty &&\n newDismissIfLastCharacterDeleted == DismissIfLastCharacterDeleted &&\n newDefaultCommitCharacters == DefaultCommitCharacters &&\n newDefaultEnterKeyRule == DefaultEnterKeyRule &&\n newSnippetsRule == SnippetsRule)\n {\n return this;\n }\n else\n {\n return Create(\n newDismissIfEmpty,\n newDismissIfLastCharacterDeleted,\n newDefaultCommitCharacters,\n newDefaultEnterKeyRule,\n newSnippetsRule);\n }\n }\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDismissIfEmpty(bool dismissIfEmpty)\n => With(dismissIfEmpty: dismissIfEmpty);\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDismissIfLastCharacterDeleted(bool dismissIfLastCharacterDeleted)\n => With(dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted);\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDefaultCommitCharacters(ImmutableArray defaultCommitCharacters)\n => With(defaultCommitCharacters: defaultCommitCharacters);\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDefaultEnterKeyRule(EnterKeyRule defaultEnterKeyRule)\n => With(defaultEnterKeyRule: defaultEnterKeyRule);\n\n /// \n /// Creates a copy of the this with the property changed.\n /// \n public CompletionRules WithSnippetsRule(SnippetsRule snippetsRule)\n => With(snippetsRule: snippetsRule);\n\n private static readonly ImmutableArray s_defaultCommitKeys = ImmutableArray.Create(\n ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':',\n ';', '+', '-', '*', '/', '%', '&', '|', '^', '!',\n '~', '=', '<', '>', '?', '@', '#', '\\'', '\\\"', '\\\\');\n\n /// \n /// The default if none is otherwise specified.\n /// \n public static readonly CompletionRules Default = new(\n dismissIfEmpty: false,\n dismissIfLastCharacterDeleted: false,\n defaultCommitCharacters: s_defaultCommitKeys,\n defaultEnterKeyRule: EnterKeyRule.Default,\n snippetsRule: SnippetsRule.Default);\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Immutable;\n\nnamespace Microsoft.CodeAnalysis.Completion\n{\n /// \n /// Presentation and behavior rules for completion.\n /// \n public sealed class CompletionRules\n {\n /// \n /// True if the completion list should be dismissed if the user's typing causes it to filter\n /// and display no items.\n /// \n public bool DismissIfEmpty { get; }\n\n /// \n /// True if the list should be dismissed when the user deletes the last character in the span.\n /// \n public bool DismissIfLastCharacterDeleted { get; }\n\n /// \n /// The default set of typed characters that cause the selected item to be committed.\n /// Individual s can override this.\n /// \n public ImmutableArray DefaultCommitCharacters { get; }\n\n /// \n /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.\n /// Individual s can override this.\n /// \n public EnterKeyRule DefaultEnterKeyRule { get; }\n\n /// \n /// The rule determining how snippets work.\n /// \n public SnippetsRule SnippetsRule { get; }\n\n private CompletionRules(\n bool dismissIfEmpty,\n bool dismissIfLastCharacterDeleted,\n ImmutableArray defaultCommitCharacters,\n EnterKeyRule defaultEnterKeyRule,\n SnippetsRule snippetsRule)\n {\n DismissIfEmpty = dismissIfEmpty;\n DismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted;\n DefaultCommitCharacters = defaultCommitCharacters.NullToEmpty();\n DefaultEnterKeyRule = defaultEnterKeyRule;\n SnippetsRule = snippetsRule;\n }\n\n /// \n /// Creates a new instance.\n /// \n /// True if the completion list should be dismissed if the user's typing causes it to filter and display no items.\n /// True if the list should be dismissed when the user deletes the last character in the span.\n /// The default set of typed characters that cause the selected item to be committed.\n /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.\n public static CompletionRules Create(\n bool dismissIfEmpty,\n bool dismissIfLastCharacterDeleted,\n ImmutableArray defaultCommitCharacters,\n EnterKeyRule defaultEnterKeyRule)\n {\n return Create(dismissIfEmpty, dismissIfLastCharacterDeleted, defaultCommitCharacters,\n defaultEnterKeyRule, SnippetsRule.Default);\n }\n\n /// \n /// Creates a new instance.\n /// \n /// True if the completion list should be dismissed if the user's typing causes it to filter and display no items.\n /// True if the list should be dismissed when the user deletes the last character in the span.\n /// The default set of typed characters that cause the selected item to be committed.\n /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.\n /// The rule that controls snippets behavior.\n public static CompletionRules Create(\n bool dismissIfEmpty = false,\n bool dismissIfLastCharacterDeleted = false,\n ImmutableArray defaultCommitCharacters = default,\n EnterKeyRule defaultEnterKeyRule = EnterKeyRule.Default,\n SnippetsRule snippetsRule = SnippetsRule.Default)\n {\n return new CompletionRules(\n dismissIfEmpty: dismissIfEmpty,\n dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted,\n defaultCommitCharacters: defaultCommitCharacters,\n defaultEnterKeyRule: defaultEnterKeyRule,\n snippetsRule: snippetsRule);\n }\n\n private CompletionRules With(\n Optional dismissIfEmpty = default,\n Optional dismissIfLastCharacterDeleted = default,\n Optional> defaultCommitCharacters = default,\n Optional defaultEnterKeyRule = default,\n Optional snippetsRule = default)\n {\n var newDismissIfEmpty = dismissIfEmpty.HasValue ? dismissIfEmpty.Value : DismissIfEmpty;\n var newDismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted.HasValue ? dismissIfLastCharacterDeleted.Value : DismissIfLastCharacterDeleted;\n var newDefaultCommitCharacters = defaultCommitCharacters.HasValue ? defaultCommitCharacters.Value : DefaultCommitCharacters;\n var newDefaultEnterKeyRule = defaultEnterKeyRule.HasValue ? defaultEnterKeyRule.Value : DefaultEnterKeyRule;\n var newSnippetsRule = snippetsRule.HasValue ? snippetsRule.Value : SnippetsRule;\n\n if (newDismissIfEmpty == DismissIfEmpty &&\n newDismissIfLastCharacterDeleted == DismissIfLastCharacterDeleted &&\n newDefaultCommitCharacters == DefaultCommitCharacters &&\n newDefaultEnterKeyRule == DefaultEnterKeyRule &&\n newSnippetsRule == SnippetsRule)\n {\n return this;\n }\n else\n {\n return Create(\n newDismissIfEmpty,\n newDismissIfLastCharacterDeleted,\n newDefaultCommitCharacters,\n newDefaultEnterKeyRule,\n newSnippetsRule);\n }\n }\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDismissIfEmpty(bool dismissIfEmpty)\n => With(dismissIfEmpty: dismissIfEmpty);\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDismissIfLastCharacterDeleted(bool dismissIfLastCharacterDeleted)\n => With(dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted);\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDefaultCommitCharacters(ImmutableArray defaultCommitCharacters)\n => With(defaultCommitCharacters: defaultCommitCharacters);\n\n /// \n /// Creates a copy of this with the property changed.\n /// \n public CompletionRules WithDefaultEnterKeyRule(EnterKeyRule defaultEnterKeyRule)\n => With(defaultEnterKeyRule: defaultEnterKeyRule);\n\n /// \n /// Creates a copy of the this with the property changed.\n /// \n public CompletionRules WithSnippetsRule(SnippetsRule snippetsRule)\n => With(snippetsRule: snippetsRule);\n\n private static readonly ImmutableArray s_defaultCommitKeys = ImmutableArray.Create(\n ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':',\n ';', '+', '-', '*', '/', '%', '&', '|', '^', '!',\n '~', '=', '<', '>', '?', '@', '#', '\\'', '\\\"', '\\\\');\n\n /// \n /// The default if none is otherwise specified.\n /// \n public static readonly CompletionRules Default = new(\n dismissIfEmpty: false,\n dismissIfLastCharacterDeleted: false,\n defaultCommitCharacters: s_defaultCommitKeys,\n defaultEnterKeyRule: EnterKeyRule.Default,\n snippetsRule: SnippetsRule.Default);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":447,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/IncrementalParsingTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Linq;\nusing Microsoft.CodeAnalysis.CSharp.Test.Utilities;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.CSharp.UnitTests\n{\n public class IncrementalParsingTests : TestBase\n {\n private CSharpParseOptions GetOptions(string[] defines)\n {\n return new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3, preprocessorSymbols: defines);\n }\n\n private SyntaxTree Parse(string text, params string[] defines)\n {\n var options = this.GetOptions(defines);\n var itext = SourceText.From(text);\n return SyntaxFactory.ParseSyntaxTree(itext, options);\n }\n\n private SyntaxTree Parse6(string text)\n {\n var options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6);\n var itext = SourceText.From(text);\n return SyntaxFactory.ParseSyntaxTree(itext, options);\n }\n\n [Fact]\n public void TestChangeClassNameWithNonMatchingMethod()\n {\n var text = \"class goo { void m() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeClassNameToNotMatchConstructor()\n {\n var text = \"class goo { goo() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken,\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.VoidKeyword);\n }\n\n private static void TestDiffsInOrder(ImmutableArray diffs, params SyntaxKind[] kinds)\n {\n Assert.InRange(diffs.Length, 0, kinds.Length);\n\n int diffI = 0;\n foreach (var kind in kinds)\n {\n if (diffI < diffs.Length && diffs[diffI].IsKind(kind))\n {\n diffI++;\n }\n }\n\n // all diffs must be consumed.\n Assert.Equal(diffI, diffs.Length);\n }\n\n [Fact]\n public void TestChangeClassNameToMatchConstructor()\n {\n var text = \"class goo { bar() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken,\n SyntaxKind.ConstructorDeclaration);\n }\n\n [Fact]\n public void TestChangeClassNameToNotMatchDestructor()\n {\n var text = \"class goo { ~goo() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeClassNameToMatchDestructor()\n {\n var text = \"class goo { ~bar() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeFromClassToInterface()\n {\n var interfaceKeyword = SyntaxFactory.ParseToken(\"interface\"); // prime the memoizer\n\n var text = \"class goo { public void m() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"class\", \"interface\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.InterfaceDeclaration,\n SyntaxKind.InterfaceKeyword);\n }\n\n [Fact]\n public void TestChangeFromClassToStruct()\n {\n var interfaceKeyword = SyntaxFactory.ParseToken(\"struct\"); // prime the memoizer\n\n var text = \"class goo { public void m() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"class\", \"struct\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.StructDeclaration,\n SyntaxKind.StructKeyword);\n }\n\n [Fact]\n public void TestChangeMethodName()\n {\n var text = \"class c { void goo(a x, b y) { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeIfCondition()\n {\n var text = @\"\n#if GOO\nclass goo { void M() { } }\n#endif\n\";\n var oldTree = this.Parse(text, \"GOO\", \"BAR\");\n var newTree = oldTree.WithReplaceFirst(\"GOO\", \"BAR\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword,\n SyntaxKind.EndOfFileToken);\n }\n\n [Fact]\n public void TestChangeDefine()\n {\n var text = @\"\n#define GOO\n#if GOO||BAR\nclass goo { void M() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"GOO\", \"BAR\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword,\n SyntaxKind.EndOfFileToken);\n }\n\n [Fact]\n public void TestChangeDefineAndIfElse()\n {\n var text = @\"\n#define GOO\n#if GOO\nclass C { void M() { } }\n#else\nclass C { void N() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"GOO\", \"BAR\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword,\n SyntaxKind.IdentifierToken,\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.IdentifierToken,\n SyntaxKind.ParameterList,\n SyntaxKind.Block,\n SyntaxKind.EndOfFileToken);\n }\n\n [Fact]\n public void TestAddLineDirective()\n {\n var text = @\"\nclass C { void M() { } }\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithInsertAt(0, \"#line 100\\r\\n\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword);\n }\n\n [Fact]\n public void TestRemoveLineDirective()\n {\n var text = @\"\n#line 10\nclass C { void M() { } }\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithRemoveFirst(\"#line 10\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword);\n }\n\n [Fact]\n public void TestRemoveEndRegionDirective()\n {\n var text = @\"\n#if true\nclass A { void a() { } }\n#region\nclass B { void b() { } }\n#endregion\nclass C { void c() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(4, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind());\n Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, oldDirectives[2].Kind());\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[3].Kind());\n\n var newTree = oldTree.WithRemoveFirst(\"#endregion\");\n var errors = newTree.GetCompilationUnitRoot().Errors();\n Assert.Equal(2, errors.Length);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code);\n var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(3, newDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind());\n Assert.Equal(SyntaxKind.BadDirectiveTrivia, newDirectives[2].Kind());\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration, // class declaration on edge before change\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.Block,\n SyntaxKind.ClassDeclaration, // class declaration on edge after change\n SyntaxKind.ClassKeyword, // edge of change and directives different\n SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive)\n }\n\n [Fact]\n public void TestAddEndRegionDirective()\n {\n var text = @\"\n#if true\nclass A { void a() { } }\n#region\nclass B { void b() { } }\nclass C { void c() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n var errors = oldTree.GetCompilationUnitRoot().Errors();\n Assert.Equal(2, errors.Length);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code);\n var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(3, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind());\n Assert.Equal(SyntaxKind.BadDirectiveTrivia, oldDirectives[2].Kind());\n\n var newTree = oldTree.WithInsertBefore(\"class C\", \"#endregion\\r\\n\");\n errors = newTree.GetCompilationUnitRoot().Errors();\n Assert.Equal(0, errors.Length);\n var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(4, newDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind());\n Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, newDirectives[2].Kind());\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, newDirectives[3].Kind());\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration, // class declaration on edge before change\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.Block,\n SyntaxKind.ClassDeclaration, // class declaration on edge after change\n SyntaxKind.ClassKeyword, // edge of change and directives different\n SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive)\n }\n\n [Fact]\n public void TestGlobalStatementToStatementChange()\n {\n var text = @\";a * b\";\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script);\n var newTree = oldTree.WithInsertAt(0, \"{ \");\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.GlobalStatement,\n SyntaxKind.Block,\n SyntaxKind.OpenBraceToken,\n SyntaxKind.EmptyStatement,\n SyntaxKind.LocalDeclarationStatement,\n SyntaxKind.VariableDeclaration,\n SyntaxKind.PointerType,\n SyntaxKind.IdentifierName,\n SyntaxKind.VariableDeclarator,\n SyntaxKind.SemicolonToken, // missing\n SyntaxKind.CloseBraceToken); // missing\n }\n\n [Fact]\n public void TestStatementToGlobalStatementChange()\n {\n var text = @\"{; a * b; }\";\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script);\n var newTree = oldTree.WithRemoveAt(0, 1);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.GlobalStatement,\n SyntaxKind.EmptyStatement,\n SyntaxKind.GlobalStatement,\n SyntaxKind.ExpressionStatement,\n SyntaxKind.MultiplyExpression,\n SyntaxKind.IdentifierName,\n SyntaxKind.IdentifierName,\n SyntaxKind.SemicolonToken);\n }\n\n #region \"Regression\"\n\n#if false\n [Fact]\n public void DevDiv3599()\n {\n var text =\n@\"class B {\n#if false\n#endif\n}\n\";\n var newText =\n@\"class B\n{\n private class E\n {\n }\n#if false\n#endif\n}\n\";\n var oldTree = this.Parse(text);\n Assert.Equal(text, oldTree.GetCompilationUnitRoot().ToFullString());\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Count);\n var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(2, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind);\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind);\n\n var newTree = oldTree.WithChange(SourceText.From(newText),\n new TextChangeRange(new TextSpan(7, 0), 16),\n new TextChangeRange(new TextSpan(8, 0), 13),\n new TextChangeRange(new TextSpan(9, 0), 7)); //this is the tricky one - it occurs before the trailing trivia of the closing brace\n //this is the line that fails without the fix to DevDiv #3599 - there's extra text because of a blender error\n Assert.Equal(newText, newTree.GetCompilationUnitRoot().ToFullString());\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Count);\n var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(2, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind);\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n Assert.Equal(8, diffs.Count);\n Assert.Equal(SyntaxKind.CompilationUnit, // Everything - different because a descendant is different\n Assert.Equal(SyntaxKind.ClassDeclaration, // class B - different because a descendant is different\n //class keyword is reused\n Assert.Equal(SyntaxKind.IdentifierToken, // B - different because there a change immediately afterward\n //open brace is reused\n Assert.Equal(SyntaxKind.ClassDeclaration, // class E - different because it's inserted\n Assert.Equal(SyntaxKind.PrivateKeyword, // private - different because it's inserted\n Assert.Equal(SyntaxKind.IdentifierToken, // E - different because it's inserted\n Assert.Equal(SyntaxKind.OpenBraceToken, // { - different because it's inserted\n Assert.Equal(SyntaxKind.CloseBraceToken, // } - different because it's inserted\n //close brace is reused\n //eof is reused\n }\n#endif\n\n [Fact]\n public void Bug892212()\n {\n // prove that this incremental change can occur without exception!\n var text = \"/\";\n var startTree = SyntaxFactory.ParseSyntaxTree(text);\n var newTree = startTree.WithInsertAt(1, \"/\");\n var fullText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(\"//\", fullText);\n }\n\n#if false\n [WorkItem(896260, \"Personal\")]\n [Fact]//(Skip = \"Bug\")]\n public void RemovePartialFromClassWithIncorrectSpan()\n {\n var test = @\"partial class C{}\";\n var resultString = \"class C{}\";\n var startTree = SyntaxTree.Parse(test);\n var finalString = startTree.GetCompilationUnitRoot().ToString();\n var incrementalChange = new TextChange(startTree.Text, SourceText.From(resultString), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) }); // NOTE: The string length here is a bit too short for the change\n var newTree = startTree.WithChange(incrementalChange);\n var output = newTree.GetCompilationUnitRoot().ToString();\n Assert.Equal(output, resultString);\n }\n#endif\n\n#if false // can no longer specify an incorrect range\n [Fact]\n public void Bug896260()\n {\n var test = @\"partial class C{}\";\n var startTree = SyntaxTree.ParseText(test);\n var finalString = startTree.GetCompilationUnitRoot().ToString();\n\n Exception e = null;\n try\n {\n // NOTE: The string length here is a bit too short for the change\n var newTree = startTree.WithChange(SourceText.From(\"class C{}\"), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) });\n }\n catch (Exception x)\n {\n e = x;\n }\n\n Assert.NotNull(e);\n }\n#endif\n\n [Fact]\n public void Bug896262()\n {\n var text = SourceText.From(@\"partial class C{}\");\n var startTree = SyntaxFactory.ParseSyntaxTree(text);\n var finalString = startTree.GetCompilationUnitRoot().ToFullString();\n\n var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), \"\"));\n var newTree = startTree.WithChangedText(newText);\n var finalText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(newText.ToString(), finalText);\n }\n\n [WorkItem(536457, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536457\")]\n [Fact]\n public void RemovePartialFromClassWithCorrectSpan()\n {\n var text = SourceText.From(@\"partial class C{}\");\n var startTree = SyntaxFactory.ParseSyntaxTree(text);\n var finalString = startTree.GetCompilationUnitRoot().ToFullString();\n\n var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), \"\"));\n var newTree = startTree.WithChangedText(newText);\n var output = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(newText.ToString(), output);\n }\n\n [WorkItem(536519, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536519\")]\n [Fact]\n public void AddTopLevelMemberErrorDifference()\n {\n SourceText oldText = SourceText.From(@\"\nusing System;\n\npublic d\");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, 'e', out incrementalTree, out parsedTree);\n\n // The bug is that the errors are currently different\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536520, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536520\")]\n [Fact]\n public void AddIncompleteStatementErrorDifference()\n {\n SourceText oldText = SourceText.From(@\"\npublic class Test\n{\n static int Main()\n {\n \");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, 'r', out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536523, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536523\")]\n [Fact]\n public void DifferentNumberOfErrorsForNonCompletedBlock()\n {\n SourceText oldText = SourceText.From(@\"\npublic class Test\n{\n static int Main()\n {\n return 1;\n \");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, '}', out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536649, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536649\")]\n [Fact]\n public void AddingCharacterOnErrorWithExtern()\n {\n SourceText oldText = SourceText.From(@\"\nclass C\n{ \n\tpublic extern C();\n\tstatic int Main ()\n\t\");\n char newCharacter = '{';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536650, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536650\")]\n [Fact]\n public void ErrorWithExtraModifiers()\n {\n SourceText oldText = SourceText.From(@\"\nclass MyClass {\n\tinternal internal const in\");\n char newCharacter = 't';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536651, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536651\")]\n [Fact]\n public void CommentsCauseDifferentErrorStrings()\n {\n SourceText oldText = SourceText.From(@\"\nclass A\n{\n static public int Main ()\n {\n double d = new double(1); /\");\n char newCharacter = '/';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536652, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536652\")]\n [Fact]\n public void ErrorModifierOnClass()\n {\n SourceText oldText = SourceText.From(@\"\nprotected class My\");\n char newCharacter = 'C';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536653, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536653\")]\n [Fact]\n public void ErrorPartialClassWithNoBody()\n {\n SourceText oldText = SourceText.From(@\"\npublic partial clas\");\n char newCharacter = 's';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536654, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536654\")]\n [Fact]\n public void ErrorConstKeywordInMethodName()\n {\n SourceText oldText = SourceText.From(@\"\tclass A\n\t{\n\t\tprotected virtual void Finalize const () { }\n\t}\n\n\tclass B\");\n char newCharacter = ' ';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536655, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536655\")]\n [Fact]\n public void ErrorWithOperatorDeclaration()\n {\n SourceText oldText = SourceText.From(@\"public class TestClass\n{\n public static TestClass operator ++\");\n char newCharacter = '(';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536661, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536661\")]\n [Fact]\n public void ErrorWithNestedTypeInNew()\n {\n SourceText oldText = SourceText.From(@\"using System;\n\nclass Test {\n\tstatic public int Main(String[] args) {\n\t\tAbstractBase b = new AbstractBase.\");\n char newCharacter = 'I';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536662, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536662\")]\n [Fact]\n public void ErrorWithInvalidMethodName()\n {\n SourceText oldText = SourceText.From(@\"public class MyClass {\t\n\tint -goo(\");\n char newCharacter = ')';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536524, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536524\")]\n [Fact]\n public void AddingAFieldInIncompleteClass()\n {\n SourceText oldText = SourceText.From(@\"\npublic class Test\n{\n \");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, 'C', out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(903526, \"DevDiv/Personal\")]\n [Fact]\n public void AddingTryBlockToMethodOneCharAtTime()\n {\n SourceText startingText = SourceText.From(@\"\npublic class Test\n{\n void Goo() {} // Point\n}\");\n\n SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText);\n\n // Insert a try/catch block inside the method, one char at a time\n foreach (char c in \"try{}catch{}\")\n {\n syntaxTree = syntaxTree.WithInsertBefore(\"} // Point\", c.ToString());\n }\n\n Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [WorkItem(903526, \"DevDiv/Personal\")]\n [Fact]\n public void AddingIfBlockToMethodOneCharAtTime()\n {\n SourceText startingText = SourceText.From(@\"\npublic class Test\n{\n void Goo() {} // Point\n}\");\n\n SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText);\n\n foreach (char c in \"if(true){}else{}\")\n {\n syntaxTree = syntaxTree.WithInsertBefore(\"} // Point\", c.ToString());\n }\n\n Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [Fact]\n public void AddingWhileBlockToMethodOneCharAtTime()\n {\n SourceText startingText = SourceText.From(@\"\npublic class Test\n{\n void Goo() {} // Point\n}\");\n\n SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText);\n\n foreach (char c in \"while(true){}\")\n {\n syntaxTree = syntaxTree.WithInsertBefore(\"} // Point\", c.ToString());\n }\n\n Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [WorkItem(536563, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536563\")]\n [Fact]\n public void CommentOutClassKeyword()\n {\n SourceText oldText = SourceText.From(@\"class MyClass \n{\n\tprivate enum E {zero, one, two, three};\n\tpublic const E test = E.two;\n\tpublic static int Main() \n\t{\n\t\treturn 1;\n\t}\n}\");\n int locationOfChange = 0, widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536565, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536565\")]\n [Fact]\n public void CommentOutOpeningCurlyOnPrivateDeclaration()\n {\n SourceText oldText = SourceText.From(@\"\nprivate class B{ public class MyClass \n{\n\n\tprivate enum E {zero, one, two, three};\n\tpublic const E test = E.two;\n\n\tpublic static int Main() \n\t{\n\t\treturn 1;\n\t}\n}}\");\n int locationOfChange = 42, widthOfChange = 1;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536567, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536567\")]\n [Fact]\n public void CommentOutBracesOnMethodDeclaration()\n {\n SourceText oldText = SourceText.From(@\"\nprivate class B{ private class MyClass \n{\n\n\tprivate enum E {zero, one, two, three};\n\tpublic const E test = E.two;\n\n\tpublic int Main() \n\t{\n\t\treturn 1;\n\t}\n}}\");\n int locationOfChange = 139, widthOfChange = 2;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536568, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536568\")]\n [Fact]\n public void CommentOutEventKeyword()\n {\n SourceText oldText = SourceText.From(@\"interface IGoo\n{\n\tevent EventHandler E { add { } remove { } }\n}\n\nclass Test \n{\n\tpublic static int Main()\n\t{\n\t\treturn 1;\n\t}\n}\");\n int locationOfChange = 20, widthOfChange = 6;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536571, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536571\")]\n [Fact]\n public void CommentOutEventAccessor()\n {\n SourceText oldText = SourceText.From(@\"interface IGoo\n{\n\tevent EventHandler E { add { } remove { } }\n}\n\nclass Test \n{\n\tpublic static int Main()\n\t{\n\t\treturn 1;\n\t}\n}\");\n int locationOfChange = 43, widthOfChange = 3;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536573, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536573\")]\n [Fact]\n public void CommentOutDotInUsingAlias()\n {\n SourceText oldText = SourceText.From(@\"using System.Runtime.CompilerServices;\n[assembly:InternalsVisibleTo(a)]\nclass A\n{\n\tpublic int x = 0;\n\tstatic int Main()\n\t{\t\n\t\treturn 0;\n\t}\n}\n\");\n int locationOfChange = 12, widthOfChange = 1;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536577, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536577\")]\n [Fact]\n public void CommentOutThisInIndexer()\n {\n SourceText oldText = SourceText.From(@\"class A\n{\n\t\tint MyInter.this[int i] {\n\t\tget {\n\t\t\treturn intI + 1;\n\t\t}\n\t\tset {\n\t\t\tintI = value + 1;\n\t\t}\n\t}\n\n}\n\");\n int locationOfChange = 26, widthOfChange = 4;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536578, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536578\")]\n [Fact]\n public void CommentOutReturnStatementInProperty()\n {\n SourceText oldText = SourceText.From(@\"public class MyClass {\n\tint this[] {\n\t\tget {\n\t\t\treturn intI;\n\t\t}\n\t\tset {\n\t\t\tintI = value;\n\t\t}\n\t}\n}\n\");\n int locationOfChange = 51, widthOfChange = 7;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(905311, \"DevDiv/Personal\")]\n [Fact]\n public void AddSemicolonInForLoop()\n {\n SourceText oldText = SourceText.From(@\"public class MyClass {\n void goo()\n {\n for (int i = 0\n }\n}\n\");\n int locationOfInsert = oldText.ToString().IndexOf('0') + 1;\n SyntaxTree oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // The bug was that this would simply assert\n SyntaxTree newTree = oldTree.WithInsertAt(locationOfInsert, \";\");\n }\n\n [WorkItem(536635, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536635\")]\n [Fact]\n public void AddSemicolonAfterStartOfVerbatimString()\n {\n var oldText = @\"class A\n{\nstring s = @\n}\n\";\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n var newTree = oldTree.WithInsertAt(oldText.IndexOf('@'), \";\");\n }\n\n [WorkItem(536717, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536717\")]\n [Fact]\n public void AddReturnWithTriviaAtStart()\n {\n string oldText = @\"0;\n }\n}\";\n string diffText = \"return \";\n\n // Get the Original parse tree\n SyntaxTree origTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // Get the tree after incremental parse after applying the change\n SyntaxTree incrTree = origTree.WithInsertAt(0, diffText);\n\n string newText = diffText + oldText;\n\n // Get the full parse tree with the applied change\n SyntaxTree fullTree = SyntaxFactory.ParseSyntaxTree(newText);\n\n CompareIncToFullParseErrors(incrTree, fullTree);\n }\n\n [WorkItem(536728, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536728\")]\n [Fact]\n public void CommentClassWithGTandGTEOperator()\n {\n // the token in question is now converted to skipped text so this check is no longer applicable\n#if false\n SourceText oldText = SourceText.From(@\"class Test\n{\n static bool Test()\n {\n if (b21 >>= b22)\n {\n }\n }\n}\n\");\n int locationOfChange = 0, widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"class\" to \"/*class*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify if the >>= operator in the incremental parse tree is actually 2 separate tokens (> and >=)\n Assert.Equal(SyntaxKind.GreaterThanToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind);\n Assert.Equal(SyntaxKind.GreaterThanEqualsToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind);\n\n // The full parse tree should also have the above tree structure for the >>= operator\n Assert.Equal(SyntaxKind.GreaterThanToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind);\n Assert.Equal(SyntaxKind.GreaterThanEqualsToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind);\n\n // Serialize the parse trees and compare the incremental parse tree against the full parse tree\n // Assert.Equal( parsedTree.GetCompilationUnitRoot().ToXml().ToString(), incrementalTree.GetCompilationUnitRoot().ToXml().ToString());\n Assert.True(parsedTree.GetCompilationUnitRoot().IsEquivalentTo(incrementalTree.GetCompilationUnitRoot()));\n#endif\n }\n\n [WorkItem(536730, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536730\")]\n [Fact]\n public void CodeWithDollarSign()\n {\n SourceText oldText = SourceText.From(@\"class filesystem{\n\tpo$i$;\n}\");\n int locationOfChange = 0, widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"class\" to \"/*class*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify when you roundtrip the text from the full parse with change should match the text from the incremental parse with change\n // The bug is that the \"$\" sign was being swallowed on the incremental parse\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString());\n }\n\n [WorkItem(536731, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536731\")]\n [Fact]\n public void CommentCodeInGOTOStatement()\n {\n SourceText oldText = SourceText.From(@\"class CSTR020mod{ public static void CSTR020() { ON ERROR GOTO ErrorTrap; } }\");\n int locationOfChange = oldText.ToString().IndexOf(\"ON\", StringComparison.Ordinal), widthOfChange = 2;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"ON\" to \"/*ON*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536734, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536734\")]\n [Fact]\n public void CommentConstInConstDeclError()\n {\n SourceText oldText = SourceText.From(@\"class A\n{\n const byte X4var As Byte = 55;\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf(\"const\", StringComparison.Ordinal), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"const\" to \"/*const*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536738, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738\")]\n [Fact]\n public void CommentClassWithDelegateDecl()\n {\n SourceText oldText = SourceText.From(@\"public class DynClassDrived\n{\n protected delegate void ProtectedDel(dynamic d);\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf(\"class\", StringComparison.Ordinal), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // This function will update \"class\" to \"/*class*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536738, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738\")]\n [Fact]\n public void CommentCloseBraceInPropertyDecl()\n {\n SourceText oldText = SourceText.From(@\"public class MemberClass\n{\n public MyStruct[] Property_MyStructArr { get; set; }\n public MyEnum[] Property_MyEnumArr { set; private get; }\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update the first closing brace in property declaration Property_MyStructArr \"}\" to \"/*}*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [Fact]\n public void CommentCloseBraceInInitOnlyPropertyDecl()\n {\n SourceText oldText = SourceText.From(@\"public class MemberClass\n{\n public MyStruct[] Property_MyStructArr { get; init; }\n public MyEnum[] Property_MyEnumArr { init; private get; }\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5;\n\n // This function will update the first closing brace in property declaration Property_MyStructArr \"}\" to \"/*}*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536739, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536739\")]\n [Fact]\n public void CommentFixedInIllegalArrayDecl()\n {\n SourceText oldText = SourceText.From(@\"class Test\n{\n unsafe struct A\n {\n public fixed byte Array[dy[\"\"Test\"\"]];\n }\n}\");\n int locationOfChange = oldText.ToString().IndexOf(\"fixed\", StringComparison.Ordinal), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"fixed\" to \"/*fixed*/\" in oldText above\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536788, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536788\")]\n [Fact]\n public void CommentGlobalUsedAsAlias()\n {\n SourceText oldText = SourceText.From(\n@\"using @global=System.Int32;\nclass Test\n{\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf(\"@global\", StringComparison.Ordinal), widthOfChange = 7;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"@global\" to \"/*@global*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify if the fully parsed tree and the incrementally parse tree have the same number of children\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count);\n\n // Verify if the children of the trees are of the same kind\n for (int i = 0; i < parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; i++)\n {\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind());\n }\n }\n\n [WorkItem(536789, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536789\")]\n [Fact]\n public void CommentUsingStmtGlobalUsedAsAlias()\n {\n SourceText oldText = SourceText.From(\n@\"using @global=System.Int32;\nclass Test\n{\n static int Main()\n {\n return (@global) 0;\n }\n}\n\");\n string txtToCmnt = @\"using @global=System.Int32;\";\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"using @global=System.Int32;\" to \"/*using @global=System.Int32;*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536790, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536790\")]\n [Fact]\n public void CmntMainInCodeWithGlobalQualifierInUnsafe()\n {\n SourceText oldText = SourceText.From(\n@\"class Test\n{\n unsafe static int Main() \n {\n global::System.Int32* p = stackalloc global::System.Int32[5];\n }\n}\n\");\n string txtToCmnt = @\"Main\";\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"Main\" to \"/*Main*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536842, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536842\"), WorkItem(543452, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543452\")]\n [Fact]\n public void DelegateDeclInvalidCastException()\n {\n SourceText oldText = SourceText.From(\n@\" public delegate void MyDelegate01(dynamic d, int n);\n [System.CLSCompliant(false)]\n\");\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n // The bug is that when you do the incremental parse with the change an InvalidCastException is thrown at runtime.\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree text and the fully parsed tree text matches\n Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536843, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536843\")]\n [Fact]\n public void KeyExistsArgumentException()\n {\n SourceText oldText = SourceText.From(\n@\" public abstract class AbstractCompiler : ICompiler\n {\n protected virtual IDictionary GetOptions()\n {\n foreach (string parameter in parameters.Split(' '))\n {\n if (true)\n {\n\n string[] parts = parameter.Remove(0, 1).Split(':');\n string key = parts[0].ToLower();\n\n if (true)\n {\n }\n if (true)\n {\n\n }\n else if (false)\n {\n\n }\n\n }\n\n }\n\n }\n\n protected virtual TargetType GetTargetType(IDictionary options)\n {\n }\n\n }\n\");\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n // The bug is that when you do the incremental parse with the change an ArgumentException is thrown at runtime.\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree text and the fully parsed tree text matches\n Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536849, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536849\")]\n [Fact]\n public void QueryExprWithKeywordsAsVariablesAndIncompleteJoin()\n {\n SourceText oldText = SourceText.From(\n@\"class Test { \n static void Main()\n { \n var q = \n\tfrom string @params in ( @foreach/9)\n\tjoin\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536865, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536865\")]\n [Fact]\n public void IncompleteGenericTypeParamVarDecl()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n public static int Main()\n {\n C' character to the end of oldText\n CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536866, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536866\")]\n [Fact]\n public void IncompleteArglistMethodInvocation()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n public static void Run()\n {\n testvar.Test(__arglist(10l, 1\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '2' character to the end of oldText\n CharByCharIncrementalParse(oldText, '2', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536867, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536867\")]\n [Fact]\n public void IncompleteErrorExtensionMethodDecl()\n {\n SourceText oldText = SourceText.From(\n@\"public static class Extensions\n{\n public static this Goo(int i, this string str)\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n // The bug is that the Incremental Parser throws a NullReferenceException\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree text and the fully parsed tree text matches\n Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536868, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536868\")]\n [Fact]\n public void IncompleteErrorLambdaExpr()\n {\n SourceText oldText = SourceText.From(\n@\"public class Program\n{\n public static int Main()\n { \n D[] a2 = new [] {(int x)=\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '>' character to the end of oldText\n CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536871, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536871\")]\n [Fact]\n public void IncompleteCodeFollowingXmlDocStyleComment()\n {\n SourceText oldText = SourceText.From(\n@\"class C \n{\n /// =>\n \");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 's' character to the end of oldText\n CharByCharIncrementalParse(oldText, 's', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536897, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536897\")]\n [Fact]\n public void IncompleteNamespaceFollowingExternError()\n {\n SourceText oldText = SourceText.From(\n@\"using C1 = extern;\nnamespace N\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '1' character to the end of oldText\n CharByCharIncrementalParse(oldText, '1', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536898, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536898\")]\n [Fact]\n public void IncompleteConditionWithJaggedArrayAccess()\n {\n SourceText oldText = SourceText.From(\n@\"class A\n{\n public static int Main()\n {\n if (arr[2][3l] =\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '=' character to the end of oldText\n CharByCharIncrementalParse(oldText, '=', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536899, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536899\")]\n [Fact]\n public void TrailingCommentFollowingAttributesInsideMethod()\n {\n SourceText oldText = SourceText.From(\n@\"public class goo \n{\n public static int Goo\n {\n [method:A][goo:A]/\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // This function will add the '/' character to the end of oldText\n CharByCharIncrementalParse(oldText, '/', out incrementalTree, out parsedTree);\n\n // Verify that the first child node of the root is equivalent between incremental tree and full parse tree\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString());\n }\n\n [WorkItem(536901, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536901\")]\n [Fact]\n public void SpecialAttribNameWithDoubleAtToken()\n {\n SourceText oldText = SourceText.From(\n@\"[@@X\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ']' character to the end of oldText\n CharByCharIncrementalParse(oldText, ']', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536903, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536903\")]\n [Fact]\n public void AssertForAttributeWithGenericType()\n {\n SourceText oldText = SourceText.From(\n@\"[Goo:imeta where T\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ':' character to the end of oldText\n // The bug is that an assert is thrown when you perform the incremental parse with the change\n CharByCharIncrementalParse(oldText, ':', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536904, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536904\")]\n [Fact]\n public void ArithmeticExprWithLongConstant()\n {\n SourceText oldText = SourceText.From(\n@\"public class arith0018 \n{\n public static void Main()\n {\n long l1 = 1l/0\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 'l' character to the end of oldText\n CharByCharIncrementalParse(oldText, 'l', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536913, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536913\")]\n [Fact]\n public void AddClassKeywordWithAnonymousMethodThrowsIndexOutOfRangeException()\n {\n SourceText oldText = SourceText.From(\n@\"Production\n{\n private readonly T epsilon=default(T);\n\n public Production(T epsilon, Function, object> action, V variable, SomeType someType)\n {\n ((VoidDelegate)delegate\n {\n someType.Iterate(delegate(object o)\n {\n System.Console.WriteLine(((BoolDelegate)delegate { return object.Equals(o, this.epsilon); })());\n });\n })();\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"class \" text to the start of oldText\n // The bug is that the incremental parser was throwing an IndexOutofRangeException\n TokenByTokenBottomUp(oldText, \"class \", out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree roundtrip text is the same as parsedTree roundtrip text\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536914, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536914\")]\n [Fact]\n public void AddClassKeywordWithParamsModifierInAnonymousMethod()\n {\n SourceText oldText = SourceText.From(\n@\"Test\n{\n static int Goo()\n {\n Dele f = delegate(params int[] a) { return 1;};\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"class \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"class \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536916, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536916\")]\n [Fact]\n public void AddEqualTokenBeforeLongConst()\n {\n SourceText oldText = SourceText.From(\n@\"3l;\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"=\" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"= \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536917, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536917\")]\n [Fact]\n public void AddEqualTokenBeforeHugeConst()\n {\n SourceText oldText = SourceText.From(\n@\"18446744073709551616;\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"=\" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"=\", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536616, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536616\")]\n [Fact]\n public void AddEndTagToXmlDocComment()\n {\n SourceText oldText = SourceText.From(\n@\"class c1\n{\n/// \n/// <\n\");\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n TokenByTokenBottomUp(oldText, \"/\", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537888, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537888\")]\n [Fact]\n public void AddClassKeywordToCodeWithConstructorAndProperty()\n {\n SourceText oldText = SourceText.From(\n@\"IntVector\n{\n public IntVector(int length)\n {\n }\n\n public int Length\n {\n get\n {\n return 1;\n }\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"class \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"class \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537890, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537890\")]\n [Fact]\n public void AddCurlyBracesToIncompleteCode()\n {\n SourceText oldText = SourceText.From(\n@\"\t\tint[][] arr;\n\n\t\tif (arr[1][1] == 0)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn 1;\n\t}\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"{ \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"{ \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537891, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537891\")]\n [Fact]\n public void AddOpenParenToIncompleteMethodDeclBeforeDestructor()\n {\n SourceText oldText = SourceText.From(\n@\"string s) {}\n~Widget() {}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"(\" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"(\", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(538977, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538977\")]\n [Fact]\n public void AddTokenToIncompleteQueryExpr()\n {\n SourceText oldText = SourceText.From(\n@\"equals abstract select new { };\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"i \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"i \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536986, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536986\")]\n [Fact]\n public void IncompleteGenericInterfaceImplementation()\n {\n SourceText oldText = SourceText.From(\n@\"class GenInt : IGenX, IGenY \n{\n\tstring IGenX.m\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '(' character to the end of oldText\n CharByCharIncrementalParse(oldText, '(', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536988, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536988\")]\n [Fact]\n public void IncompleteIndexerDecl()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test \n{\n\tint this[ params int [] args, i\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 'n' character to the end of oldText\n CharByCharIncrementalParse(oldText, 'n', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536990, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536990\")]\n [Fact]\n public void IncompleteGenericVarDeclWithUnderscore()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n public static int Main()\n {\n cT ct = _class.TestT' character to the end of oldText\n CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536991, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536991\")]\n [Fact]\n public void IncompleteUnsafeArrayInit()\n {\n SourceText oldText = SourceText.From(\n@\"unsafe class Test \n{\n\tunsafe void*[] A = {(void*\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ')' character to the end of oldText\n CharByCharIncrementalParse(oldText, ')', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537012, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537012\")]\n [Fact]\n public void RemoveClassIdentifierTokenWithDelegDecl()\n {\n SourceText oldText = SourceText.From(\n@\"class Test\n{\n static int Goo()\n {\n\n Dele f = delegate(params int[] a) { return 1;};\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"Test\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"Test\" token from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537889, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537889\")]\n [Fact]\n public void RemoveBracesInExtensionIndexer()\n {\n SourceText oldText = SourceText.From(\n@\"public static class Extensions\n{\n public static int this(this int x)[int index1] { get { return 9; } }\n\n public static int Main()\n {\n return 0;\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \")[\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \")[\" token from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537892, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537892\")]\n [Fact]\n public void RemoveParensInMethodDeclContainingPartialKeyword()\n {\n SourceText oldText = SourceText.From(\n@\"static int Main()\n{\n partial\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"()\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"()\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537020, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537020\")]\n [Fact]\n public void IncompleteGlobalQualifierExplInterfaceImpl()\n {\n SourceText oldText = SourceText.From(\n@\"class Test : N1.I1\n{\n int global::N1.\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 'I' character to the end of oldText\n CharByCharIncrementalParse(oldText, 'I', out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537033, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537033\")]\n [Fact]\n public void RemoveParensInGetEnumeratorWithPropertyAccess()\n {\n SourceText oldText = SourceText.From(\n@\"public class QueueProducerConsumer\n{\n public IEnumerator GetEnumerator()\n {\n while (true)\n {\n if (!value.HasValue)\n {\n }\n }\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"()\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"()\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537053, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537053\")]\n [Fact]\n public void RemoveReturnTypeOnProperty()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n\tpublic int Prop\n\t{\n\t\tset\n\t\t{\n\t\t\tD d = delegate\n\t\t\t{\n\t\t\t\tValidator(value);\n\t\t\t};\n\t\t}\n\t}\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"int\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"int\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(538975, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538975\")]\n [Fact]\n public void RemoveTypeOnArrayInParameterWithMethodDeclError()\n {\n SourceText oldText = SourceText.From(\n@\"public class A\n{\n public void static Main(string[] args)\n {\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"string\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"string\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537054, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537054\")]\n [Fact]\n public void RemoveReturnTypeOnGenericMethodWithTypeParamConstraint()\n {\n SourceText oldText = SourceText.From(\n@\"class Test\n{\n public static int M() where U : IDisposable, new()\n {\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"int\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"int\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537084, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537084\")]\n [Fact]\n public void RemoveNamespaceQualifierFromTypeInIfCondition()\n {\n SourceText oldText = SourceText.From(\n@\"public class Driver \n{\n\tpublic void AddValidations()\n\t{\n\t\tif (typeof(K) is System.ValueType)\n\t\t{\n\n\t\t}\n\t}\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"System\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"System\" text from oldText\n // The bug is that \"Debug.Assert\" was thrown by the Incremental Parser with this change\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537092, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537092\")]\n [Fact]\n public void RemoveMethodNameWithLambdaExprInMethodBody()\n {\n SourceText oldText = SourceText.From(\n@\"class C\n{\n static int Main()\n {\n M((x, y) => new Pair());\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"Main\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"Main\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(538978, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538978\")]\n [Fact]\n public void RemoveInitializerOnDeclStatementWithErrors()\n {\n SourceText oldText = SourceText.From(\n@\"x public static string S = null;\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"null\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"null\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537116, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537116\")]\n [Fact]\n public void CmntEndIfInMethodDecl()\n {\n SourceText oldText = SourceText.From(\n@\"class Referenced\n{\n\n#if PUBLIC\n\t\tpublic\n#else\n\t\tinternal\n#endif\n\t\t\tstatic RecordNotFound Method(){}\n}\n//\");\n\n string txtToCmnt = @\"internal\n#endif\n\t\t\tstatic RecordNotFound Method(){}\";\n\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will comment out the txtToCmnt in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537125, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537125\")]\n [Fact]\n public void CmntAnonTypeInQueryExpr()\n {\n SourceText oldText = SourceText.From(\n@\"public class QueryExpressionTest\n{\n public static int Main()\n {\n\n var query7 = from a in b join delegate in c on d equals delegate select new { e, delegate };\n var query13 = from delegate in f join g in h on delegate equals i select delegate;\n }\n}\");\n\n string txtToCmnt = @\"select new { e, delegate }\";\n\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will comment out the txtToCmnt in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537180, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537180\")]\n [Fact]\n public void CmntParamsInExtProperty()\n {\n SourceText oldText = SourceText.From(\n@\"public static class Extensions\n{\n public static int Goo2(this int x ) { set { var1 = value; } }\n}\");\n\n string txtToCmnt = @\"(this int x )\";\n\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will comment out the txtToCmnt in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537533\")]\n [Fact]\n public void MultiCommentInserts()\n {\n var str = @\"using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n static void Main(string[] args)\n {\n // abc\n // 123\n // def\n if (true) { } else { }\n }\n}\";\n\n var text = SourceText.From(str);\n var tree = SyntaxFactory.ParseSyntaxTree(text);\n\n var text2 = text.WithChanges(\n new TextChange(new TextSpan(str.IndexOf(\" abc\", StringComparison.Ordinal), 0), \"//\"),\n new TextChange(new TextSpan(str.IndexOf(\" 123\", StringComparison.Ordinal), 0), \"//\"),\n new TextChange(new TextSpan(str.IndexOf(\" def\", StringComparison.Ordinal), 0), \"//\"));\n\n var parsedTree = SyntaxFactory.ParseSyntaxTree(text2);\n var reparsedTree = tree.WithChangedText(text2);\n\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), reparsedTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(542236, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542236\")]\n [Fact]\n public void InsertOpenBraceBeforeCodes()\n {\n SourceText oldText = SourceText.From(@\"\n\t\tthis.I = i;\n\t};\n}\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // first make certain this text round trips\n Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString());\n var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), \"{\"));\n var reparsedTree = startTree.WithChangedText(newText);\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(6676, \"https://github.com/dotnet/roslyn/issues/6676\")]\n [Fact]\n public void InsertExpressionStatementWithoutSemicolonBefore()\n {\n SourceText oldText = SourceText.From(@\"System.Console.WriteLine(true)\n\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script);\n\n startTree.GetDiagnostics().Verify();\n\n var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @\"System.Console.WriteLine(false)\n\"));\n\n AssertEx.AreEqual(@\"System.Console.WriteLine(false)\nSystem.Console.WriteLine(true)\n\",\nnewText.ToString());\n\n var reparsedTree = startTree.WithChangedText(newText);\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script);\n\n parsedTree.GetDiagnostics().Verify(\n // (1,32): error CS1002: ; expected\n // System.Console.WriteLine(false)\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(1, 32));\n\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(6676, \"https://github.com/dotnet/roslyn/issues/6676\")]\n [Fact]\n public void InsertExpressionStatementWithoutSemicolonAfter()\n {\n SourceText oldText = SourceText.From(@\"System.Console.WriteLine(true)\n\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script);\n\n startTree.GetDiagnostics().Verify();\n\n var newText = oldText.WithInsertAt(\n oldText.Length,\n @\"System.Console.WriteLine(false)\n\");\n\n AssertEx.Equal(@\"System.Console.WriteLine(true)\nSystem.Console.WriteLine(false)\n\", newText.ToString());\n\n var reparsedTree = startTree.WithChangedText(newText);\n\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script);\n parsedTree.GetDiagnostics().Verify(\n // (1,31): error CS1002: ; expected\n // System.Console.WriteLine(true)\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(1, 31));\n\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(6676, \"https://github.com/dotnet/roslyn/issues/6676\")]\n [Fact]\n public void MakeEmbeddedExpressionStatementWithoutSemicolon()\n {\n SourceText oldText = SourceText.From(@\"System.Console.WriteLine(true)\n\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script);\n\n startTree.GetDiagnostics().Verify();\n\n var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @\"if (false)\n\"));\n\n AssertEx.Equal(@\"if (false)\nSystem.Console.WriteLine(true)\n\", newText.ToString());\n\n var reparsedTree = startTree.WithChangedText(newText);\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script);\n\n parsedTree.GetDiagnostics().Verify(\n // (2,31): error CS1002: ; expected\n // System.Console.WriteLine(true)\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(2, 31));\n\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(531404, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531404\")]\n [Fact]\n public void AppendDisabledText()\n {\n var text =\n@\"class SmallDictionary\n{\n public void Add(int key, int value)\n {\n int hash = key + value;\n#if DEBUG\";\n var originalTree = this.Parse(text);\n var changedTree = originalTree.WithInsertAt(text.Length, \"\\r\\n hash++;\");\n var parsedTree = this.Parse(changedTree.GetCompilationUnitRoot().ToFullString());\n\n Assert.Equal(\n parsedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan,\n changedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan);\n }\n\n [Fact, WorkItem(531614, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531614\")]\n public void IncrementalParseStopAtEscapeBackSlash()\n {\n var text1 = @\"using System;\n\nclass Program\n{\n static void Main()\n {\n\";\n\n var text2 = @\" Console.WriteLine(\"\"\\'\\0\\a\\b\\\";\n\n var comp = CSharpTestBase.CreateCompilation(SyntaxFactory.ParseSyntaxTree(String.Empty));\n\n var oldTree = comp.SyntaxTrees.First();\n var oldIText = oldTree.GetText();\n var span = new TextSpan(oldIText.Length, 0);\n var change = new TextChange(span, text1);\n\n var newIText = oldIText.WithChanges(change);\n var newTree = oldTree.WithChangedText(newIText);\n\n var fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options);\n var fullText = fullTree.GetCompilationUnitRoot().ToFullString();\n var incText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(fullText.Length, incText.Length);\n Assert.Equal(fullText, incText);\n // \n oldTree = newTree;\n oldIText = oldTree.GetText();\n span = new TextSpan(oldIText.Length, 0);\n change = new TextChange(span, text2);\n\n newIText = oldIText.WithChanges(change);\n newTree = oldTree.WithChangedText(newIText);\n\n fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options);\n fullText = fullTree.GetCompilationUnitRoot().ToFullString();\n incText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(fullText.Length, incText.Length);\n Assert.Equal(fullText, incText);\n }\n\n [Fact, WorkItem(552741, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741\")]\n public void IncrementalParseTopDownCommentOutLines()\n {\n var text = @\"// Query Expression syntax \n// \n// from, join, on, equals, into, let, orderby, ascending, descending, group, by\n// @-with contextual keywords parseable as a type or identifier in a query expression\n// Various combinations\n// \n// \n\n//\n\n// \n\nusing System;\nusing System.Linq;\n\npublic class from { }\npublic class join { }\npublic class on { }\npublic class equals { }\npublic class into { }\npublic class let { }\npublic class orderby : let { }\npublic class ascending : orderby, descending { }\npublic interface descending { }\npublic class group { }\npublic class by { }\n\npublic class QueryExpressionTest\n{\n public static int Main()\n {\n var array02a = new[] { new join(), new join(), new join() } as object[];\n var array02b = new[] { new join(), new join(), new join() } as object[];\n var query02 = from i in array02a join j in array02b on (@from)i equals (@from)j select new { i, j };\n\n var array03a = new[] { new on(), new on(), new on() } as object[];\n var array03b = new[] { new on(), new on(), new on() } as object[];\n var query03 = from @on i in array03a join j in array03b on i equals (@on)j select new { i, j };\n\n var array04a = new[] { new equals(), new equals(), new equals() } as object[];\n\n return 0;\n }\n}\n\";\n\n var currTree = SyntaxFactory.ParseSyntaxTree(text);\n var currIText = currTree.GetText();\n\n var items = text.Split('\\n');\n int currLen = 0;\n foreach (var item in items)\n {\n var span = new TextSpan(currLen, 0);\n var change = new TextChange(span, \"// \");\n currLen += item.Length + 3;\n\n currIText = currIText.WithChanges(change);\n currTree = currTree.WithChangedText(currIText);\n\n var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString());\n\n int incCount = currTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count;\n int fullCount = fullTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count;\n\n WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n }\n\n [Fact, WorkItem(552741, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741\")]\n public void IncrementalParseStatementAfterQuery()\n {\n var text = @\"\nusing System.Linq;\n \nclass equals\n{\n static void Main(string[] args)\n {\n equals[] a;\n var q = from x in args select x;\n a = new[] { new equals() };\n }\n}\n\";\n\n var currTree = SyntaxFactory.ParseSyntaxTree(text);\n var currIText = currTree.GetText();\n\n // Insert \"// \" before the \"x\" in \"select x\"; the next statement becomes part of the query.\n var span = new TextSpan(text.LastIndexOf('x'), 0);\n var change = new TextChange(span, \"// \");\n\n currIText = currIText.WithChanges(change);\n currTree = currTree.WithChangedText(currIText);\n\n var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString());\n\n WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact, WorkItem(529260, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260\")]\n public void DoNotReuseAnnotatedNodes()\n {\n var text = @\"\nclass C { }\nclass D { }\n\";\n\n Func extractGreenClassC = tree =>\n tree.GetCompilationUnitRoot().Members.First().Green;\n\n // Check reuse after a trivial change in an unannotated tree.\n {\n var oldTree = SyntaxFactory.ParseSyntaxTree(text);\n var newTree = oldTree.WithInsertAt(text.Length, \" \");\n\n // Class declaration is reused.\n Assert.Same(extractGreenClassC(oldTree), extractGreenClassC(newTree));\n }\n\n // Check reuse after a trivial change in an annotated tree.\n {\n var tempTree = SyntaxFactory.ParseSyntaxTree(text);\n var tempRoot = tempTree.GetRoot();\n var tempToken = tempRoot.DescendantTokens().First(t => t.Kind() == SyntaxKind.IdentifierToken);\n var oldRoot = tempRoot.ReplaceToken(tempToken, tempToken.WithAdditionalAnnotations(new SyntaxAnnotation()));\n Assert.True(oldRoot.ContainsAnnotations, \"Should contain annotations.\");\n Assert.Equal(text, oldRoot.ToFullString());\n\n var oldTree = SyntaxFactory.SyntaxTree(oldRoot, options: tempTree.Options, path: tempTree.FilePath);\n var newTree = oldTree.WithInsertAt(text.Length, \" \");\n\n\n var oldClassC = extractGreenClassC(oldTree);\n var newClassC = extractGreenClassC(newTree);\n\n Assert.True(oldClassC.ContainsAnnotations, \"Should contain annotations\");\n Assert.False(newClassC.ContainsAnnotations, \"Annotations should have been removed.\");\n\n // Class declaration is not reused...\n Assert.NotSame(oldClassC, newClassC);\n // ...even though the text is the same.\n Assert.Equal(oldClassC.ToFullString(), newClassC.ToFullString());\n\n\n var oldToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)oldClassC).Identifier;\n var newToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)newClassC).Identifier;\n\n Assert.True(oldToken.ContainsAnnotations, \"Should contain annotations\");\n Assert.False(newToken.ContainsAnnotations, \"Annotations should have been removed.\");\n\n // Token is not reused...\n Assert.NotSame(oldToken, newToken);\n // ...even though the text is the same.\n Assert.Equal(oldToken.ToFullString(), newToken.ToFullString());\n }\n }\n\n [Fact]\n [WorkItem(658496, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658496\")]\n public void DontReuseLambdaParameterAsMethodParameter()\n {\n var items = new string[]\n {\n \"a b.c*/ d => {e(f =>\",\n \"/*\",\n };\n\n var oldText = SourceText.From(items[0]);\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // f is a simple lambda parameter\n\n var change = new TextChange(new TextSpan(0, 0), items[1]); // Prepend\n var newText = oldText.WithChanges(change); // f is a method decl parameter\n\n var incrTree = oldTree.WithChangedText(newText);\n var fullTree = SyntaxFactory.ParseSyntaxTree(newText);\n\n Assert.Equal(\n fullTree.GetDiagnostics().Select(d => d.ToString()),\n incrTree.GetDiagnostics().Select(d => d.ToString()));\n\n WalkTreeAndVerify(incrTree.GetRoot(), fullTree.GetRoot());\n }\n\n\n [Fact]\n public void TestRescanInterpolatedString()\n {\n var interfaceKeyword = SyntaxFactory.ParseToken(\"interface\"); // prime the memoizer\n\n var text = @\"class goo { public void m() { string s = $\"\"{1} world\"\" ; } }\";\n var oldTree = this.Parse6(text);\n var newTree = oldTree.WithReplaceFirst(@\"world\"\" \", @\"world\"\" \");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [Fact]\n public void Goo()\n {\n var oldText = SourceText.From(@\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nclass Program\n{\n static void Main(string[] args)\n {\n\n }\n\n protected abstract int Stuff { get; }\n}\n\nclass G: Program\n{\n protected override int Stuff\n {\n get\n {\n throw new NotImplementedException();\n }\n }\n}\");\n var newText = SourceText.From(@\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nclass Program\n{\n static void Main(string[] args)\n {\n\n }\n\n protected abstract int Stuff { get; }\n}\n\nclass G: Program\n{\n protected override int Stuff =>\n {\n get\n {\n throw new NotImplementedException();\n }\n }\n}\n\");\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n var newTree = oldTree.WithChangedText(newText);\n WalkTreeAndVerify(newTree.GetCompilationUnitRoot(), SyntaxFactory.ParseSyntaxTree(newText).GetCompilationUnitRoot());\n }\n\n [WorkItem(23272, \"https://github.com/dotnet/roslyn/issues/23272\")]\n [Fact]\n public void AddAccessibilityToNullableArray()\n {\n var source =\n@\"class A { }\nclass B\n{\n A[]? F;\n}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\" A[]?\"), 0);\n var change = new TextChange(span, \"p\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n [WorkItem(37663, \"https://github.com/dotnet/roslyn/issues/37663\")]\n public void AssemblyAttributeBeforeNamespace()\n {\n var src = @\"\nusing System;\nusing System.Linq;\n\n[assembly:]\nnamespace N\n{ }\";\n var tree = SyntaxFactory.ParseSyntaxTree(src);\n var text = tree.GetText();\n var span = new TextSpan(src.IndexOf(\":\"), 1);\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddBracketInUsingDirective()\n {\n var source =\n@\"using System;\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\";\"), 0);\n var change = new TextChange(span, \"[\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddAttributeAfterUsingDirective()\n {\n var source =\n@\"using System;\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\";\") + 1, 0);\n var change = new TextChange(span, \"[Obsolete]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddTrailingModifierInUsingDirective()\n {\n var source =\n@\"using System;\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\";\") + 1, 0);\n var change = new TextChange(span, \"public\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddTrailingModifierInUsingDirective_2()\n {\n var source =\n@\"using System;publi\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"publi\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"c\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void Statement_EditAttributeList_01()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr]\n void local1() { };\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"Attr\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"1, Attr2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void Statement_EditAttributeList_02()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n Method1();\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"Attr1\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \", Attr2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void Statement_AddAttributeList()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n void local1() { };\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"[Attr1]\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" [Attr2]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditStatementWithAttributes_01()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n void local1() { Method(); };\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"Method(\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"Arg\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditStatementWithAttributes_02()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n Method1();\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"Method\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 1);\n var change = new TextChange(span, \"2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"[Attr] () => { }\")]\n [InlineData(\"[Attr] x => x\")]\n [InlineData(\"([Attr] x) => x\")]\n [InlineData(\"([Attr] int x) => x\")]\n public void Lambda_EditAttributeList(string lambdaExpression)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"Attr\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"1, Attr2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"() => { }\", \"() => { }\")]\n [InlineData(\"x => x\", \"x => x\")]\n [InlineData(\"(x) => x\", \"x) => x\")]\n [InlineData(\"(int x) => x\", \"int x) => x\")]\n public void Lambda_AddFirstAttributeList(string lambdaExpression, string substring)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(substring), 0);\n var change = new TextChange(span, \"[Attr]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"[Attr1] () => { }\")]\n [InlineData(\"[Attr1] x => x\")]\n [InlineData(\"([Attr1] x) => x\")]\n [InlineData(\"([Attr1] int x) => x\")]\n public void Lambda_AddSecondAttributeList(string lambdaExpression)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"[Attr1]\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" [Attr2]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"[Attr] () => { }\")]\n [InlineData(\"[Attr] x => x\")]\n [InlineData(\"([Attr] x) => x\")]\n [InlineData(\"([Attr] int x) => x\")]\n public void Lambda_RemoveAttributeList(string lambdaExpression)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"[Attr] \";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditGlobalStatementWithAttributes_01()\n {\n var source = @\"\n[Attr]\nx.y();\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"x.y\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \".z\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditGlobalStatementWithAttributes_02()\n {\n var source = @\"\n[Attr]\nif (b) { }\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"if (b) { }\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" if (c) { }\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditGlobalStatementWithAttributes_03()\n {\n var source = @\"\n[Attr]\nif (b) { }\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"if (b) { }\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" else (c) { }\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditNestedStatementWithAttributes_01()\n {\n var source = \"{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(start: 0, length: 1); // delete first character\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditNestedStatementWithAttributes_02()\n {\n var source = \"{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(start: 0, length: 0);\n var change = new TextChange(span, \"{ \");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditNestedStatementWithAttributes_03()\n {\n var source = \"class C { void M() { Goo[Goo] [Goo]if(Goo) { } } }\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"Goo[Goo]\";\n var span = new TextSpan(start: source.IndexOf(substring), length: 3); // Goo[Goo] -> [Goo]\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n #endregion\n\n #region Helper functions\n private void WalkTreeAndVerify(SyntaxNodeOrToken incNode, SyntaxNodeOrToken fullNode)\n {\n var incChildren = incNode.ChildNodesAndTokens();\n var fullChildren = fullNode.ChildNodesAndTokens();\n Assert.Equal(incChildren.Count, fullChildren.Count);\n\n for (int i = 0; i < incChildren.Count; i++)\n {\n var incChild = incChildren[i];\n var fullChild = fullChildren[i];\n\n WalkTreeAndVerify(incChild, fullChild);\n }\n }\n\n private static void CommentOutText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var newText = oldText.WithChanges(\n new TextChange[] {\n new TextChange(new TextSpan(locationOfChange, 0), \"/*\"),\n new TextChange(new TextSpan(locationOfChange + widthOfChange, 0), \"*/\")\n });\n var tree = SyntaxFactory.ParseSyntaxTree(oldText);\n incrementalTree = tree.WithChangedText(newText);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private static void RemoveText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var newText = oldText.WithChanges(new TextChange(new TextSpan(locationOfChange, widthOfChange), \"\"));\n var tree = SyntaxFactory.ParseSyntaxTree(oldText);\n incrementalTree = tree.WithChangedText(newText);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private void CompareIncToFullParseErrors(SyntaxTree incrementalTree, SyntaxTree parsedTree)\n {\n var pd = parsedTree.GetDiagnostics();\n var id = incrementalTree.GetDiagnostics();\n Assert.Equal(pd.Count(), id.Count());\n for (int i = 0; i < id.Count(); i++)\n {\n Assert.Equal(pd.ElementAt(i).Inspect(), id.ElementAt(i).Inspect());\n }\n\n ParentChecker.CheckParents(parsedTree.GetCompilationUnitRoot(), parsedTree);\n ParentChecker.CheckParents(incrementalTree.GetCompilationUnitRoot(), incrementalTree);\n }\n\n private static void CharByCharIncrementalParse(SourceText oldText, char newChar, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // first make certain this text round trips\n Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString());\n var newText = oldText.WithChanges(new TextChange(new TextSpan(oldText.Length, 0), newChar.ToString()));\n incrementalTree = startTree.WithChangedText(newText);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private static void TokenByTokenBottomUp(SourceText oldText, string token, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText);\n SourceText newText = SourceText.From(token + oldText.ToString());\n incrementalTree = startTree.WithInsertAt(0, token);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private static void CompareTreeEquivalence(SyntaxNodeOrToken parsedTreeNode, SyntaxNodeOrToken incrementalTreeNode)\n {\n Assert.Equal(parsedTreeNode.Kind(), incrementalTreeNode.Kind());\n\n Assert.Equal(parsedTreeNode.ChildNodesAndTokens().Count, incrementalTreeNode.ChildNodesAndTokens().Count);\n\n for (int i = 0; i < parsedTreeNode.ChildNodesAndTokens().Count; i++)\n {\n CompareTreeEquivalence(parsedTreeNode.ChildNodesAndTokens()[i], incrementalTreeNode.ChildNodesAndTokens()[i]);\n }\n }\n\n #endregion\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Immutable;\nusing System.Linq;\nusing Microsoft.CodeAnalysis.CSharp.Test.Utilities;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.CSharp.UnitTests\n{\n public class IncrementalParsingTests : TestBase\n {\n private CSharpParseOptions GetOptions(string[] defines)\n {\n return new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3, preprocessorSymbols: defines);\n }\n\n private SyntaxTree Parse(string text, params string[] defines)\n {\n var options = this.GetOptions(defines);\n var itext = SourceText.From(text);\n return SyntaxFactory.ParseSyntaxTree(itext, options);\n }\n\n private SyntaxTree Parse6(string text)\n {\n var options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6);\n var itext = SourceText.From(text);\n return SyntaxFactory.ParseSyntaxTree(itext, options);\n }\n\n [Fact]\n public void TestChangeClassNameWithNonMatchingMethod()\n {\n var text = \"class goo { void m() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeClassNameToNotMatchConstructor()\n {\n var text = \"class goo { goo() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken,\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.VoidKeyword);\n }\n\n private static void TestDiffsInOrder(ImmutableArray diffs, params SyntaxKind[] kinds)\n {\n Assert.InRange(diffs.Length, 0, kinds.Length);\n\n int diffI = 0;\n foreach (var kind in kinds)\n {\n if (diffI < diffs.Length && diffs[diffI].IsKind(kind))\n {\n diffI++;\n }\n }\n\n // all diffs must be consumed.\n Assert.Equal(diffI, diffs.Length);\n }\n\n [Fact]\n public void TestChangeClassNameToMatchConstructor()\n {\n var text = \"class goo { bar() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken,\n SyntaxKind.ConstructorDeclaration);\n }\n\n [Fact]\n public void TestChangeClassNameToNotMatchDestructor()\n {\n var text = \"class goo { ~goo() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeClassNameToMatchDestructor()\n {\n var text = \"class goo { ~bar() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeFromClassToInterface()\n {\n var interfaceKeyword = SyntaxFactory.ParseToken(\"interface\"); // prime the memoizer\n\n var text = \"class goo { public void m() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"class\", \"interface\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.InterfaceDeclaration,\n SyntaxKind.InterfaceKeyword);\n }\n\n [Fact]\n public void TestChangeFromClassToStruct()\n {\n var interfaceKeyword = SyntaxFactory.ParseToken(\"struct\"); // prime the memoizer\n\n var text = \"class goo { public void m() { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"class\", \"struct\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.StructDeclaration,\n SyntaxKind.StructKeyword);\n }\n\n [Fact]\n public void TestChangeMethodName()\n {\n var text = \"class c { void goo(a x, b y) { } }\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"goo\", \"bar\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.IdentifierToken);\n }\n\n [Fact]\n public void TestChangeIfCondition()\n {\n var text = @\"\n#if GOO\nclass goo { void M() { } }\n#endif\n\";\n var oldTree = this.Parse(text, \"GOO\", \"BAR\");\n var newTree = oldTree.WithReplaceFirst(\"GOO\", \"BAR\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword,\n SyntaxKind.EndOfFileToken);\n }\n\n [Fact]\n public void TestChangeDefine()\n {\n var text = @\"\n#define GOO\n#if GOO||BAR\nclass goo { void M() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"GOO\", \"BAR\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword,\n SyntaxKind.EndOfFileToken);\n }\n\n [Fact]\n public void TestChangeDefineAndIfElse()\n {\n var text = @\"\n#define GOO\n#if GOO\nclass C { void M() { } }\n#else\nclass C { void N() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithReplaceFirst(\"GOO\", \"BAR\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword,\n SyntaxKind.IdentifierToken,\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.IdentifierToken,\n SyntaxKind.ParameterList,\n SyntaxKind.Block,\n SyntaxKind.EndOfFileToken);\n }\n\n [Fact]\n public void TestAddLineDirective()\n {\n var text = @\"\nclass C { void M() { } }\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithInsertAt(0, \"#line 100\\r\\n\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword);\n }\n\n [Fact]\n public void TestRemoveLineDirective()\n {\n var text = @\"\n#line 10\nclass C { void M() { } }\n\";\n var oldTree = this.Parse(text);\n var newTree = oldTree.WithRemoveFirst(\"#line 10\");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration,\n SyntaxKind.ClassKeyword);\n }\n\n [Fact]\n public void TestRemoveEndRegionDirective()\n {\n var text = @\"\n#if true\nclass A { void a() { } }\n#region\nclass B { void b() { } }\n#endregion\nclass C { void c() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(4, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind());\n Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, oldDirectives[2].Kind());\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[3].Kind());\n\n var newTree = oldTree.WithRemoveFirst(\"#endregion\");\n var errors = newTree.GetCompilationUnitRoot().Errors();\n Assert.Equal(2, errors.Length);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code);\n var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(3, newDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind());\n Assert.Equal(SyntaxKind.BadDirectiveTrivia, newDirectives[2].Kind());\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration, // class declaration on edge before change\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.Block,\n SyntaxKind.ClassDeclaration, // class declaration on edge after change\n SyntaxKind.ClassKeyword, // edge of change and directives different\n SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive)\n }\n\n [Fact]\n public void TestAddEndRegionDirective()\n {\n var text = @\"\n#if true\nclass A { void a() { } }\n#region\nclass B { void b() { } }\nclass C { void c() { } }\n#endif\n\";\n var oldTree = this.Parse(text);\n var errors = oldTree.GetCompilationUnitRoot().Errors();\n Assert.Equal(2, errors.Length);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code);\n Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code);\n var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(3, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind());\n Assert.Equal(SyntaxKind.BadDirectiveTrivia, oldDirectives[2].Kind());\n\n var newTree = oldTree.WithInsertBefore(\"class C\", \"#endregion\\r\\n\");\n errors = newTree.GetCompilationUnitRoot().Errors();\n Assert.Equal(0, errors.Length);\n var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(4, newDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind());\n Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind());\n Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, newDirectives[2].Kind());\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, newDirectives[3].Kind());\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.ClassDeclaration, // class declaration on edge before change\n SyntaxKind.MethodDeclaration,\n SyntaxKind.PredefinedType,\n SyntaxKind.Block,\n SyntaxKind.ClassDeclaration, // class declaration on edge after change\n SyntaxKind.ClassKeyword, // edge of change and directives different\n SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive)\n }\n\n [Fact]\n public void TestGlobalStatementToStatementChange()\n {\n var text = @\";a * b\";\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script);\n var newTree = oldTree.WithInsertAt(0, \"{ \");\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.GlobalStatement,\n SyntaxKind.Block,\n SyntaxKind.OpenBraceToken,\n SyntaxKind.EmptyStatement,\n SyntaxKind.LocalDeclarationStatement,\n SyntaxKind.VariableDeclaration,\n SyntaxKind.PointerType,\n SyntaxKind.IdentifierName,\n SyntaxKind.VariableDeclarator,\n SyntaxKind.SemicolonToken, // missing\n SyntaxKind.CloseBraceToken); // missing\n }\n\n [Fact]\n public void TestStatementToGlobalStatementChange()\n {\n var text = @\"{; a * b; }\";\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script);\n var newTree = oldTree.WithRemoveAt(0, 1);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n TestDiffsInOrder(diffs,\n SyntaxKind.CompilationUnit,\n SyntaxKind.GlobalStatement,\n SyntaxKind.EmptyStatement,\n SyntaxKind.GlobalStatement,\n SyntaxKind.ExpressionStatement,\n SyntaxKind.MultiplyExpression,\n SyntaxKind.IdentifierName,\n SyntaxKind.IdentifierName,\n SyntaxKind.SemicolonToken);\n }\n\n #region \"Regression\"\n\n#if false\n [Fact]\n public void DevDiv3599()\n {\n var text =\n@\"class B {\n#if false\n#endif\n}\n\";\n var newText =\n@\"class B\n{\n private class E\n {\n }\n#if false\n#endif\n}\n\";\n var oldTree = this.Parse(text);\n Assert.Equal(text, oldTree.GetCompilationUnitRoot().ToFullString());\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Count);\n var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(2, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind);\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind);\n\n var newTree = oldTree.WithChange(SourceText.From(newText),\n new TextChangeRange(new TextSpan(7, 0), 16),\n new TextChangeRange(new TextSpan(8, 0), 13),\n new TextChangeRange(new TextSpan(9, 0), 7)); //this is the tricky one - it occurs before the trailing trivia of the closing brace\n //this is the line that fails without the fix to DevDiv #3599 - there's extra text because of a blender error\n Assert.Equal(newText, newTree.GetCompilationUnitRoot().ToFullString());\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Count);\n var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives();\n Assert.Equal(2, oldDirectives.Count);\n Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind);\n Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind);\n\n var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree);\n Assert.Equal(8, diffs.Count);\n Assert.Equal(SyntaxKind.CompilationUnit, // Everything - different because a descendant is different\n Assert.Equal(SyntaxKind.ClassDeclaration, // class B - different because a descendant is different\n //class keyword is reused\n Assert.Equal(SyntaxKind.IdentifierToken, // B - different because there a change immediately afterward\n //open brace is reused\n Assert.Equal(SyntaxKind.ClassDeclaration, // class E - different because it's inserted\n Assert.Equal(SyntaxKind.PrivateKeyword, // private - different because it's inserted\n Assert.Equal(SyntaxKind.IdentifierToken, // E - different because it's inserted\n Assert.Equal(SyntaxKind.OpenBraceToken, // { - different because it's inserted\n Assert.Equal(SyntaxKind.CloseBraceToken, // } - different because it's inserted\n //close brace is reused\n //eof is reused\n }\n#endif\n\n [Fact]\n public void Bug892212()\n {\n // prove that this incremental change can occur without exception!\n var text = \"/\";\n var startTree = SyntaxFactory.ParseSyntaxTree(text);\n var newTree = startTree.WithInsertAt(1, \"/\");\n var fullText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(\"//\", fullText);\n }\n\n#if false\n [WorkItem(896260, \"Personal\")]\n [Fact]//(Skip = \"Bug\")]\n public void RemovePartialFromClassWithIncorrectSpan()\n {\n var test = @\"partial class C{}\";\n var resultString = \"class C{}\";\n var startTree = SyntaxTree.Parse(test);\n var finalString = startTree.GetCompilationUnitRoot().ToString();\n var incrementalChange = new TextChange(startTree.Text, SourceText.From(resultString), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) }); // NOTE: The string length here is a bit too short for the change\n var newTree = startTree.WithChange(incrementalChange);\n var output = newTree.GetCompilationUnitRoot().ToString();\n Assert.Equal(output, resultString);\n }\n#endif\n\n#if false // can no longer specify an incorrect range\n [Fact]\n public void Bug896260()\n {\n var test = @\"partial class C{}\";\n var startTree = SyntaxTree.ParseText(test);\n var finalString = startTree.GetCompilationUnitRoot().ToString();\n\n Exception e = null;\n try\n {\n // NOTE: The string length here is a bit too short for the change\n var newTree = startTree.WithChange(SourceText.From(\"class C{}\"), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) });\n }\n catch (Exception x)\n {\n e = x;\n }\n\n Assert.NotNull(e);\n }\n#endif\n\n [Fact]\n public void Bug896262()\n {\n var text = SourceText.From(@\"partial class C{}\");\n var startTree = SyntaxFactory.ParseSyntaxTree(text);\n var finalString = startTree.GetCompilationUnitRoot().ToFullString();\n\n var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), \"\"));\n var newTree = startTree.WithChangedText(newText);\n var finalText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(newText.ToString(), finalText);\n }\n\n [WorkItem(536457, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536457\")]\n [Fact]\n public void RemovePartialFromClassWithCorrectSpan()\n {\n var text = SourceText.From(@\"partial class C{}\");\n var startTree = SyntaxFactory.ParseSyntaxTree(text);\n var finalString = startTree.GetCompilationUnitRoot().ToFullString();\n\n var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), \"\"));\n var newTree = startTree.WithChangedText(newText);\n var output = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(newText.ToString(), output);\n }\n\n [WorkItem(536519, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536519\")]\n [Fact]\n public void AddTopLevelMemberErrorDifference()\n {\n SourceText oldText = SourceText.From(@\"\nusing System;\n\npublic d\");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, 'e', out incrementalTree, out parsedTree);\n\n // The bug is that the errors are currently different\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536520, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536520\")]\n [Fact]\n public void AddIncompleteStatementErrorDifference()\n {\n SourceText oldText = SourceText.From(@\"\npublic class Test\n{\n static int Main()\n {\n \");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, 'r', out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536523, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536523\")]\n [Fact]\n public void DifferentNumberOfErrorsForNonCompletedBlock()\n {\n SourceText oldText = SourceText.From(@\"\npublic class Test\n{\n static int Main()\n {\n return 1;\n \");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, '}', out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536649, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536649\")]\n [Fact]\n public void AddingCharacterOnErrorWithExtern()\n {\n SourceText oldText = SourceText.From(@\"\nclass C\n{ \n\tpublic extern C();\n\tstatic int Main ()\n\t\");\n char newCharacter = '{';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536650, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536650\")]\n [Fact]\n public void ErrorWithExtraModifiers()\n {\n SourceText oldText = SourceText.From(@\"\nclass MyClass {\n\tinternal internal const in\");\n char newCharacter = 't';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536651, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536651\")]\n [Fact]\n public void CommentsCauseDifferentErrorStrings()\n {\n SourceText oldText = SourceText.From(@\"\nclass A\n{\n static public int Main ()\n {\n double d = new double(1); /\");\n char newCharacter = '/';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536652, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536652\")]\n [Fact]\n public void ErrorModifierOnClass()\n {\n SourceText oldText = SourceText.From(@\"\nprotected class My\");\n char newCharacter = 'C';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536653, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536653\")]\n [Fact]\n public void ErrorPartialClassWithNoBody()\n {\n SourceText oldText = SourceText.From(@\"\npublic partial clas\");\n char newCharacter = 's';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536654, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536654\")]\n [Fact]\n public void ErrorConstKeywordInMethodName()\n {\n SourceText oldText = SourceText.From(@\"\tclass A\n\t{\n\t\tprotected virtual void Finalize const () { }\n\t}\n\n\tclass B\");\n char newCharacter = ' ';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536655, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536655\")]\n [Fact]\n public void ErrorWithOperatorDeclaration()\n {\n SourceText oldText = SourceText.From(@\"public class TestClass\n{\n public static TestClass operator ++\");\n char newCharacter = '(';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536661, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536661\")]\n [Fact]\n public void ErrorWithNestedTypeInNew()\n {\n SourceText oldText = SourceText.From(@\"using System;\n\nclass Test {\n\tstatic public int Main(String[] args) {\n\t\tAbstractBase b = new AbstractBase.\");\n char newCharacter = 'I';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536662, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536662\")]\n [Fact]\n public void ErrorWithInvalidMethodName()\n {\n SourceText oldText = SourceText.From(@\"public class MyClass {\t\n\tint -goo(\");\n char newCharacter = ')';\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536524, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536524\")]\n [Fact]\n public void AddingAFieldInIncompleteClass()\n {\n SourceText oldText = SourceText.From(@\"\npublic class Test\n{\n \");\n\n SyntaxTree incrementalTree, parsedTree;\n CharByCharIncrementalParse(oldText, 'C', out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(903526, \"DevDiv/Personal\")]\n [Fact]\n public void AddingTryBlockToMethodOneCharAtTime()\n {\n SourceText startingText = SourceText.From(@\"\npublic class Test\n{\n void Goo() {} // Point\n}\");\n\n SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText);\n\n // Insert a try/catch block inside the method, one char at a time\n foreach (char c in \"try{}catch{}\")\n {\n syntaxTree = syntaxTree.WithInsertBefore(\"} // Point\", c.ToString());\n }\n\n Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [WorkItem(903526, \"DevDiv/Personal\")]\n [Fact]\n public void AddingIfBlockToMethodOneCharAtTime()\n {\n SourceText startingText = SourceText.From(@\"\npublic class Test\n{\n void Goo() {} // Point\n}\");\n\n SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText);\n\n foreach (char c in \"if(true){}else{}\")\n {\n syntaxTree = syntaxTree.WithInsertBefore(\"} // Point\", c.ToString());\n }\n\n Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [Fact]\n public void AddingWhileBlockToMethodOneCharAtTime()\n {\n SourceText startingText = SourceText.From(@\"\npublic class Test\n{\n void Goo() {} // Point\n}\");\n\n SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText);\n\n foreach (char c in \"while(true){}\")\n {\n syntaxTree = syntaxTree.WithInsertBefore(\"} // Point\", c.ToString());\n }\n\n Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [WorkItem(536563, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536563\")]\n [Fact]\n public void CommentOutClassKeyword()\n {\n SourceText oldText = SourceText.From(@\"class MyClass \n{\n\tprivate enum E {zero, one, two, three};\n\tpublic const E test = E.two;\n\tpublic static int Main() \n\t{\n\t\treturn 1;\n\t}\n}\");\n int locationOfChange = 0, widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536565, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536565\")]\n [Fact]\n public void CommentOutOpeningCurlyOnPrivateDeclaration()\n {\n SourceText oldText = SourceText.From(@\"\nprivate class B{ public class MyClass \n{\n\n\tprivate enum E {zero, one, two, three};\n\tpublic const E test = E.two;\n\n\tpublic static int Main() \n\t{\n\t\treturn 1;\n\t}\n}}\");\n int locationOfChange = 42, widthOfChange = 1;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536567, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536567\")]\n [Fact]\n public void CommentOutBracesOnMethodDeclaration()\n {\n SourceText oldText = SourceText.From(@\"\nprivate class B{ private class MyClass \n{\n\n\tprivate enum E {zero, one, two, three};\n\tpublic const E test = E.two;\n\n\tpublic int Main() \n\t{\n\t\treturn 1;\n\t}\n}}\");\n int locationOfChange = 139, widthOfChange = 2;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536568, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536568\")]\n [Fact]\n public void CommentOutEventKeyword()\n {\n SourceText oldText = SourceText.From(@\"interface IGoo\n{\n\tevent EventHandler E { add { } remove { } }\n}\n\nclass Test \n{\n\tpublic static int Main()\n\t{\n\t\treturn 1;\n\t}\n}\");\n int locationOfChange = 20, widthOfChange = 6;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536571, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536571\")]\n [Fact]\n public void CommentOutEventAccessor()\n {\n SourceText oldText = SourceText.From(@\"interface IGoo\n{\n\tevent EventHandler E { add { } remove { } }\n}\n\nclass Test \n{\n\tpublic static int Main()\n\t{\n\t\treturn 1;\n\t}\n}\");\n int locationOfChange = 43, widthOfChange = 3;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536573, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536573\")]\n [Fact]\n public void CommentOutDotInUsingAlias()\n {\n SourceText oldText = SourceText.From(@\"using System.Runtime.CompilerServices;\n[assembly:InternalsVisibleTo(a)]\nclass A\n{\n\tpublic int x = 0;\n\tstatic int Main()\n\t{\t\n\t\treturn 0;\n\t}\n}\n\");\n int locationOfChange = 12, widthOfChange = 1;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536577, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536577\")]\n [Fact]\n public void CommentOutThisInIndexer()\n {\n SourceText oldText = SourceText.From(@\"class A\n{\n\t\tint MyInter.this[int i] {\n\t\tget {\n\t\t\treturn intI + 1;\n\t\t}\n\t\tset {\n\t\t\tintI = value + 1;\n\t\t}\n\t}\n\n}\n\");\n int locationOfChange = 26, widthOfChange = 4;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536578, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536578\")]\n [Fact]\n public void CommentOutReturnStatementInProperty()\n {\n SourceText oldText = SourceText.From(@\"public class MyClass {\n\tint this[] {\n\t\tget {\n\t\t\treturn intI;\n\t\t}\n\t\tset {\n\t\t\tintI = value;\n\t\t}\n\t}\n}\n\");\n int locationOfChange = 51, widthOfChange = 7;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(905311, \"DevDiv/Personal\")]\n [Fact]\n public void AddSemicolonInForLoop()\n {\n SourceText oldText = SourceText.From(@\"public class MyClass {\n void goo()\n {\n for (int i = 0\n }\n}\n\");\n int locationOfInsert = oldText.ToString().IndexOf('0') + 1;\n SyntaxTree oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // The bug was that this would simply assert\n SyntaxTree newTree = oldTree.WithInsertAt(locationOfInsert, \";\");\n }\n\n [WorkItem(536635, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536635\")]\n [Fact]\n public void AddSemicolonAfterStartOfVerbatimString()\n {\n var oldText = @\"class A\n{\nstring s = @\n}\n\";\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n var newTree = oldTree.WithInsertAt(oldText.IndexOf('@'), \";\");\n }\n\n [WorkItem(536717, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536717\")]\n [Fact]\n public void AddReturnWithTriviaAtStart()\n {\n string oldText = @\"0;\n }\n}\";\n string diffText = \"return \";\n\n // Get the Original parse tree\n SyntaxTree origTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // Get the tree after incremental parse after applying the change\n SyntaxTree incrTree = origTree.WithInsertAt(0, diffText);\n\n string newText = diffText + oldText;\n\n // Get the full parse tree with the applied change\n SyntaxTree fullTree = SyntaxFactory.ParseSyntaxTree(newText);\n\n CompareIncToFullParseErrors(incrTree, fullTree);\n }\n\n [WorkItem(536728, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536728\")]\n [Fact]\n public void CommentClassWithGTandGTEOperator()\n {\n // the token in question is now converted to skipped text so this check is no longer applicable\n#if false\n SourceText oldText = SourceText.From(@\"class Test\n{\n static bool Test()\n {\n if (b21 >>= b22)\n {\n }\n }\n}\n\");\n int locationOfChange = 0, widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"class\" to \"/*class*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify if the >>= operator in the incremental parse tree is actually 2 separate tokens (> and >=)\n Assert.Equal(SyntaxKind.GreaterThanToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind);\n Assert.Equal(SyntaxKind.GreaterThanEqualsToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind);\n\n // The full parse tree should also have the above tree structure for the >>= operator\n Assert.Equal(SyntaxKind.GreaterThanToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind);\n Assert.Equal(SyntaxKind.GreaterThanEqualsToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind);\n\n // Serialize the parse trees and compare the incremental parse tree against the full parse tree\n // Assert.Equal( parsedTree.GetCompilationUnitRoot().ToXml().ToString(), incrementalTree.GetCompilationUnitRoot().ToXml().ToString());\n Assert.True(parsedTree.GetCompilationUnitRoot().IsEquivalentTo(incrementalTree.GetCompilationUnitRoot()));\n#endif\n }\n\n [WorkItem(536730, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536730\")]\n [Fact]\n public void CodeWithDollarSign()\n {\n SourceText oldText = SourceText.From(@\"class filesystem{\n\tpo$i$;\n}\");\n int locationOfChange = 0, widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"class\" to \"/*class*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify when you roundtrip the text from the full parse with change should match the text from the incremental parse with change\n // The bug is that the \"$\" sign was being swallowed on the incremental parse\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString());\n }\n\n [WorkItem(536731, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536731\")]\n [Fact]\n public void CommentCodeInGOTOStatement()\n {\n SourceText oldText = SourceText.From(@\"class CSTR020mod{ public static void CSTR020() { ON ERROR GOTO ErrorTrap; } }\");\n int locationOfChange = oldText.ToString().IndexOf(\"ON\", StringComparison.Ordinal), widthOfChange = 2;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"ON\" to \"/*ON*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536734, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536734\")]\n [Fact]\n public void CommentConstInConstDeclError()\n {\n SourceText oldText = SourceText.From(@\"class A\n{\n const byte X4var As Byte = 55;\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf(\"const\", StringComparison.Ordinal), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"const\" to \"/*const*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536738, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738\")]\n [Fact]\n public void CommentClassWithDelegateDecl()\n {\n SourceText oldText = SourceText.From(@\"public class DynClassDrived\n{\n protected delegate void ProtectedDel(dynamic d);\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf(\"class\", StringComparison.Ordinal), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // This function will update \"class\" to \"/*class*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536738, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738\")]\n [Fact]\n public void CommentCloseBraceInPropertyDecl()\n {\n SourceText oldText = SourceText.From(@\"public class MemberClass\n{\n public MyStruct[] Property_MyStructArr { get; set; }\n public MyEnum[] Property_MyEnumArr { set; private get; }\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update the first closing brace in property declaration Property_MyStructArr \"}\" to \"/*}*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [Fact]\n public void CommentCloseBraceInInitOnlyPropertyDecl()\n {\n SourceText oldText = SourceText.From(@\"public class MemberClass\n{\n public MyStruct[] Property_MyStructArr { get; init; }\n public MyEnum[] Property_MyEnumArr { init; private get; }\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5;\n\n // This function will update the first closing brace in property declaration Property_MyStructArr \"}\" to \"/*}*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536739, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536739\")]\n [Fact]\n public void CommentFixedInIllegalArrayDecl()\n {\n SourceText oldText = SourceText.From(@\"class Test\n{\n unsafe struct A\n {\n public fixed byte Array[dy[\"\"Test\"\"]];\n }\n}\");\n int locationOfChange = oldText.ToString().IndexOf(\"fixed\", StringComparison.Ordinal), widthOfChange = 5;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"fixed\" to \"/*fixed*/\" in oldText above\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536788, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536788\")]\n [Fact]\n public void CommentGlobalUsedAsAlias()\n {\n SourceText oldText = SourceText.From(\n@\"using @global=System.Int32;\nclass Test\n{\n}\n\");\n int locationOfChange = oldText.ToString().IndexOf(\"@global\", StringComparison.Ordinal), widthOfChange = 7;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"@global\" to \"/*@global*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify if the fully parsed tree and the incrementally parse tree have the same number of children\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count);\n\n // Verify if the children of the trees are of the same kind\n for (int i = 0; i < parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; i++)\n {\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind());\n }\n }\n\n [WorkItem(536789, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536789\")]\n [Fact]\n public void CommentUsingStmtGlobalUsedAsAlias()\n {\n SourceText oldText = SourceText.From(\n@\"using @global=System.Int32;\nclass Test\n{\n static int Main()\n {\n return (@global) 0;\n }\n}\n\");\n string txtToCmnt = @\"using @global=System.Int32;\";\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"using @global=System.Int32;\" to \"/*using @global=System.Int32;*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536790, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536790\")]\n [Fact]\n public void CmntMainInCodeWithGlobalQualifierInUnsafe()\n {\n SourceText oldText = SourceText.From(\n@\"class Test\n{\n unsafe static int Main() \n {\n global::System.Int32* p = stackalloc global::System.Int32[5];\n }\n}\n\");\n string txtToCmnt = @\"Main\";\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will update \"Main\" to \"/*Main*/\" in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536842, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536842\"), WorkItem(543452, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543452\")]\n [Fact]\n public void DelegateDeclInvalidCastException()\n {\n SourceText oldText = SourceText.From(\n@\" public delegate void MyDelegate01(dynamic d, int n);\n [System.CLSCompliant(false)]\n\");\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n // The bug is that when you do the incremental parse with the change an InvalidCastException is thrown at runtime.\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree text and the fully parsed tree text matches\n Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536843, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536843\")]\n [Fact]\n public void KeyExistsArgumentException()\n {\n SourceText oldText = SourceText.From(\n@\" public abstract class AbstractCompiler : ICompiler\n {\n protected virtual IDictionary GetOptions()\n {\n foreach (string parameter in parameters.Split(' '))\n {\n if (true)\n {\n\n string[] parts = parameter.Remove(0, 1).Split(':');\n string key = parts[0].ToLower();\n\n if (true)\n {\n }\n if (true)\n {\n\n }\n else if (false)\n {\n\n }\n\n }\n\n }\n\n }\n\n protected virtual TargetType GetTargetType(IDictionary options)\n {\n }\n\n }\n\");\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n // The bug is that when you do the incremental parse with the change an ArgumentException is thrown at runtime.\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree text and the fully parsed tree text matches\n Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536849, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536849\")]\n [Fact]\n public void QueryExprWithKeywordsAsVariablesAndIncompleteJoin()\n {\n SourceText oldText = SourceText.From(\n@\"class Test { \n static void Main()\n { \n var q = \n\tfrom string @params in ( @foreach/9)\n\tjoin\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536865, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536865\")]\n [Fact]\n public void IncompleteGenericTypeParamVarDecl()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n public static int Main()\n {\n C' character to the end of oldText\n CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536866, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536866\")]\n [Fact]\n public void IncompleteArglistMethodInvocation()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n public static void Run()\n {\n testvar.Test(__arglist(10l, 1\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '2' character to the end of oldText\n CharByCharIncrementalParse(oldText, '2', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536867, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536867\")]\n [Fact]\n public void IncompleteErrorExtensionMethodDecl()\n {\n SourceText oldText = SourceText.From(\n@\"public static class Extensions\n{\n public static this Goo(int i, this string str)\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ' ' character to the end of oldText\n // The bug is that the Incremental Parser throws a NullReferenceException\n CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree text and the fully parsed tree text matches\n Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536868, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536868\")]\n [Fact]\n public void IncompleteErrorLambdaExpr()\n {\n SourceText oldText = SourceText.From(\n@\"public class Program\n{\n public static int Main()\n { \n D[] a2 = new [] {(int x)=\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '>' character to the end of oldText\n CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536871, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536871\")]\n [Fact]\n public void IncompleteCodeFollowingXmlDocStyleComment()\n {\n SourceText oldText = SourceText.From(\n@\"class C \n{\n /// =>\n \");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 's' character to the end of oldText\n CharByCharIncrementalParse(oldText, 's', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536897, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536897\")]\n [Fact]\n public void IncompleteNamespaceFollowingExternError()\n {\n SourceText oldText = SourceText.From(\n@\"using C1 = extern;\nnamespace N\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '1' character to the end of oldText\n CharByCharIncrementalParse(oldText, '1', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536898, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536898\")]\n [Fact]\n public void IncompleteConditionWithJaggedArrayAccess()\n {\n SourceText oldText = SourceText.From(\n@\"class A\n{\n public static int Main()\n {\n if (arr[2][3l] =\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '=' character to the end of oldText\n CharByCharIncrementalParse(oldText, '=', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536899, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536899\")]\n [Fact]\n public void TrailingCommentFollowingAttributesInsideMethod()\n {\n SourceText oldText = SourceText.From(\n@\"public class goo \n{\n public static int Goo\n {\n [method:A][goo:A]/\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // This function will add the '/' character to the end of oldText\n CharByCharIncrementalParse(oldText, '/', out incrementalTree, out parsedTree);\n\n // Verify that the first child node of the root is equivalent between incremental tree and full parse tree\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString());\n }\n\n [WorkItem(536901, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536901\")]\n [Fact]\n public void SpecialAttribNameWithDoubleAtToken()\n {\n SourceText oldText = SourceText.From(\n@\"[@@X\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ']' character to the end of oldText\n CharByCharIncrementalParse(oldText, ']', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536903, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536903\")]\n [Fact]\n public void AssertForAttributeWithGenericType()\n {\n SourceText oldText = SourceText.From(\n@\"[Goo:imeta where T\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ':' character to the end of oldText\n // The bug is that an assert is thrown when you perform the incremental parse with the change\n CharByCharIncrementalParse(oldText, ':', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536904, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536904\")]\n [Fact]\n public void ArithmeticExprWithLongConstant()\n {\n SourceText oldText = SourceText.From(\n@\"public class arith0018 \n{\n public static void Main()\n {\n long l1 = 1l/0\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 'l' character to the end of oldText\n CharByCharIncrementalParse(oldText, 'l', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536913, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536913\")]\n [Fact]\n public void AddClassKeywordWithAnonymousMethodThrowsIndexOutOfRangeException()\n {\n SourceText oldText = SourceText.From(\n@\"Production\n{\n private readonly T epsilon=default(T);\n\n public Production(T epsilon, Function, object> action, V variable, SomeType someType)\n {\n ((VoidDelegate)delegate\n {\n someType.Iterate(delegate(object o)\n {\n System.Console.WriteLine(((BoolDelegate)delegate { return object.Equals(o, this.epsilon); })());\n });\n })();\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"class \" text to the start of oldText\n // The bug is that the incremental parser was throwing an IndexOutofRangeException\n TokenByTokenBottomUp(oldText, \"class \", out incrementalTree, out parsedTree);\n\n // Verify the incrementalTree roundtrip text is the same as parsedTree roundtrip text\n Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString());\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536914, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536914\")]\n [Fact]\n public void AddClassKeywordWithParamsModifierInAnonymousMethod()\n {\n SourceText oldText = SourceText.From(\n@\"Test\n{\n static int Goo()\n {\n Dele f = delegate(params int[] a) { return 1;};\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"class \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"class \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536916, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536916\")]\n [Fact]\n public void AddEqualTokenBeforeLongConst()\n {\n SourceText oldText = SourceText.From(\n@\"3l;\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"=\" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"= \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536917, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536917\")]\n [Fact]\n public void AddEqualTokenBeforeHugeConst()\n {\n SourceText oldText = SourceText.From(\n@\"18446744073709551616;\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"=\" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"=\", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536616, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536616\")]\n [Fact]\n public void AddEndTagToXmlDocComment()\n {\n SourceText oldText = SourceText.From(\n@\"class c1\n{\n/// \n/// <\n\");\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n TokenByTokenBottomUp(oldText, \"/\", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537888, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537888\")]\n [Fact]\n public void AddClassKeywordToCodeWithConstructorAndProperty()\n {\n SourceText oldText = SourceText.From(\n@\"IntVector\n{\n public IntVector(int length)\n {\n }\n\n public int Length\n {\n get\n {\n return 1;\n }\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"class \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"class \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537890, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537890\")]\n [Fact]\n public void AddCurlyBracesToIncompleteCode()\n {\n SourceText oldText = SourceText.From(\n@\"\t\tint[][] arr;\n\n\t\tif (arr[1][1] == 0)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn 1;\n\t}\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"{ \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"{ \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537891, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537891\")]\n [Fact]\n public void AddOpenParenToIncompleteMethodDeclBeforeDestructor()\n {\n SourceText oldText = SourceText.From(\n@\"string s) {}\n~Widget() {}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"(\" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"(\", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(538977, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538977\")]\n [Fact]\n public void AddTokenToIncompleteQueryExpr()\n {\n SourceText oldText = SourceText.From(\n@\"equals abstract select new { };\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the \"i \" text to the start of oldText\n TokenByTokenBottomUp(oldText, \"i \", out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536986, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536986\")]\n [Fact]\n public void IncompleteGenericInterfaceImplementation()\n {\n SourceText oldText = SourceText.From(\n@\"class GenInt : IGenX, IGenY \n{\n\tstring IGenX.m\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the '(' character to the end of oldText\n CharByCharIncrementalParse(oldText, '(', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536988, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536988\")]\n [Fact]\n public void IncompleteIndexerDecl()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test \n{\n\tint this[ params int [] args, i\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 'n' character to the end of oldText\n CharByCharIncrementalParse(oldText, 'n', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536990, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536990\")]\n [Fact]\n public void IncompleteGenericVarDeclWithUnderscore()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n public static int Main()\n {\n cT ct = _class.TestT' character to the end of oldText\n CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(536991, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536991\")]\n [Fact]\n public void IncompleteUnsafeArrayInit()\n {\n SourceText oldText = SourceText.From(\n@\"unsafe class Test \n{\n\tunsafe void*[] A = {(void*\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the ')' character to the end of oldText\n CharByCharIncrementalParse(oldText, ')', out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537012, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537012\")]\n [Fact]\n public void RemoveClassIdentifierTokenWithDelegDecl()\n {\n SourceText oldText = SourceText.From(\n@\"class Test\n{\n static int Goo()\n {\n\n Dele f = delegate(params int[] a) { return 1;};\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"Test\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"Test\" token from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537889, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537889\")]\n [Fact]\n public void RemoveBracesInExtensionIndexer()\n {\n SourceText oldText = SourceText.From(\n@\"public static class Extensions\n{\n public static int this(this int x)[int index1] { get { return 9; } }\n\n public static int Main()\n {\n return 0;\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \")[\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \")[\" token from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537892, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537892\")]\n [Fact]\n public void RemoveParensInMethodDeclContainingPartialKeyword()\n {\n SourceText oldText = SourceText.From(\n@\"static int Main()\n{\n partial\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"()\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"()\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537020, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537020\")]\n [Fact]\n public void IncompleteGlobalQualifierExplInterfaceImpl()\n {\n SourceText oldText = SourceText.From(\n@\"class Test : N1.I1\n{\n int global::N1.\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will add the 'I' character to the end of oldText\n CharByCharIncrementalParse(oldText, 'I', out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537033, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537033\")]\n [Fact]\n public void RemoveParensInGetEnumeratorWithPropertyAccess()\n {\n SourceText oldText = SourceText.From(\n@\"public class QueueProducerConsumer\n{\n public IEnumerator GetEnumerator()\n {\n while (true)\n {\n if (!value.HasValue)\n {\n }\n }\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"()\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"()\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537053, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537053\")]\n [Fact]\n public void RemoveReturnTypeOnProperty()\n {\n SourceText oldText = SourceText.From(\n@\"public class Test\n{\n\tpublic int Prop\n\t{\n\t\tset\n\t\t{\n\t\t\tD d = delegate\n\t\t\t{\n\t\t\t\tValidator(value);\n\t\t\t};\n\t\t}\n\t}\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"int\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"int\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(538975, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538975\")]\n [Fact]\n public void RemoveTypeOnArrayInParameterWithMethodDeclError()\n {\n SourceText oldText = SourceText.From(\n@\"public class A\n{\n public void static Main(string[] args)\n {\n }\n}\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"string\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"string\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537054, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537054\")]\n [Fact]\n public void RemoveReturnTypeOnGenericMethodWithTypeParamConstraint()\n {\n SourceText oldText = SourceText.From(\n@\"class Test\n{\n public static int M() where U : IDisposable, new()\n {\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"int\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"int\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537084, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537084\")]\n [Fact]\n public void RemoveNamespaceQualifierFromTypeInIfCondition()\n {\n SourceText oldText = SourceText.From(\n@\"public class Driver \n{\n\tpublic void AddValidations()\n\t{\n\t\tif (typeof(K) is System.ValueType)\n\t\t{\n\n\t\t}\n\t}\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"System\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"System\" text from oldText\n // The bug is that \"Debug.Assert\" was thrown by the Incremental Parser with this change\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537092, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537092\")]\n [Fact]\n public void RemoveMethodNameWithLambdaExprInMethodBody()\n {\n SourceText oldText = SourceText.From(\n@\"class C\n{\n static int Main()\n {\n M((x, y) => new Pair());\n }\n}\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"Main\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"Main\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(538978, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538978\")]\n [Fact]\n public void RemoveInitializerOnDeclStatementWithErrors()\n {\n SourceText oldText = SourceText.From(\n@\"x public static string S = null;\n\");\n\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n string textToRemove = \"null\";\n int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal);\n int widthOfChange = textToRemove.Length;\n\n // This function will remove the \"null\" text from oldText\n RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537116, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537116\")]\n [Fact]\n public void CmntEndIfInMethodDecl()\n {\n SourceText oldText = SourceText.From(\n@\"class Referenced\n{\n\n#if PUBLIC\n\t\tpublic\n#else\n\t\tinternal\n#endif\n\t\t\tstatic RecordNotFound Method(){}\n}\n//\");\n\n string txtToCmnt = @\"internal\n#endif\n\t\t\tstatic RecordNotFound Method(){}\";\n\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will comment out the txtToCmnt in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537125, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537125\")]\n [Fact]\n public void CmntAnonTypeInQueryExpr()\n {\n SourceText oldText = SourceText.From(\n@\"public class QueryExpressionTest\n{\n public static int Main()\n {\n\n var query7 = from a in b join delegate in c on d equals delegate select new { e, delegate };\n var query13 = from delegate in f join g in h on delegate equals i select delegate;\n }\n}\");\n\n string txtToCmnt = @\"select new { e, delegate }\";\n\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will comment out the txtToCmnt in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same\n CompareIncToFullParseErrors(incrementalTree, parsedTree);\n }\n\n [WorkItem(537180, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537180\")]\n [Fact]\n public void CmntParamsInExtProperty()\n {\n SourceText oldText = SourceText.From(\n@\"public static class Extensions\n{\n public static int Goo2(this int x ) { set { var1 = value; } }\n}\");\n\n string txtToCmnt = @\"(this int x )\";\n\n int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length;\n SyntaxTree incrementalTree;\n SyntaxTree parsedTree;\n\n // This function will comment out the txtToCmnt in oldText\n CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree);\n\n // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(537533, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537533\")]\n [Fact]\n public void MultiCommentInserts()\n {\n var str = @\"using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n static void Main(string[] args)\n {\n // abc\n // 123\n // def\n if (true) { } else { }\n }\n}\";\n\n var text = SourceText.From(str);\n var tree = SyntaxFactory.ParseSyntaxTree(text);\n\n var text2 = text.WithChanges(\n new TextChange(new TextSpan(str.IndexOf(\" abc\", StringComparison.Ordinal), 0), \"//\"),\n new TextChange(new TextSpan(str.IndexOf(\" 123\", StringComparison.Ordinal), 0), \"//\"),\n new TextChange(new TextSpan(str.IndexOf(\" def\", StringComparison.Ordinal), 0), \"//\"));\n\n var parsedTree = SyntaxFactory.ParseSyntaxTree(text2);\n var reparsedTree = tree.WithChangedText(text2);\n\n CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), reparsedTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(542236, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542236\")]\n [Fact]\n public void InsertOpenBraceBeforeCodes()\n {\n SourceText oldText = SourceText.From(@\"\n\t\tthis.I = i;\n\t};\n}\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // first make certain this text round trips\n Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString());\n var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), \"{\"));\n var reparsedTree = startTree.WithChangedText(newText);\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(6676, \"https://github.com/dotnet/roslyn/issues/6676\")]\n [Fact]\n public void InsertExpressionStatementWithoutSemicolonBefore()\n {\n SourceText oldText = SourceText.From(@\"System.Console.WriteLine(true)\n\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script);\n\n startTree.GetDiagnostics().Verify();\n\n var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @\"System.Console.WriteLine(false)\n\"));\n\n AssertEx.AreEqual(@\"System.Console.WriteLine(false)\nSystem.Console.WriteLine(true)\n\",\nnewText.ToString());\n\n var reparsedTree = startTree.WithChangedText(newText);\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script);\n\n parsedTree.GetDiagnostics().Verify(\n // (1,32): error CS1002: ; expected\n // System.Console.WriteLine(false)\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(1, 32));\n\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(6676, \"https://github.com/dotnet/roslyn/issues/6676\")]\n [Fact]\n public void InsertExpressionStatementWithoutSemicolonAfter()\n {\n SourceText oldText = SourceText.From(@\"System.Console.WriteLine(true)\n\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script);\n\n startTree.GetDiagnostics().Verify();\n\n var newText = oldText.WithInsertAt(\n oldText.Length,\n @\"System.Console.WriteLine(false)\n\");\n\n AssertEx.Equal(@\"System.Console.WriteLine(true)\nSystem.Console.WriteLine(false)\n\", newText.ToString());\n\n var reparsedTree = startTree.WithChangedText(newText);\n\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script);\n parsedTree.GetDiagnostics().Verify(\n // (1,31): error CS1002: ; expected\n // System.Console.WriteLine(true)\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(1, 31));\n\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(6676, \"https://github.com/dotnet/roslyn/issues/6676\")]\n [Fact]\n public void MakeEmbeddedExpressionStatementWithoutSemicolon()\n {\n SourceText oldText = SourceText.From(@\"System.Console.WriteLine(true)\n\");\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script);\n\n startTree.GetDiagnostics().Verify();\n\n var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @\"if (false)\n\"));\n\n AssertEx.Equal(@\"if (false)\nSystem.Console.WriteLine(true)\n\", newText.ToString());\n\n var reparsedTree = startTree.WithChangedText(newText);\n var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script);\n\n parsedTree.GetDiagnostics().Verify(\n // (2,31): error CS1002: ; expected\n // System.Console.WriteLine(true)\n Diagnostic(ErrorCode.ERR_SemicolonExpected, \"\").WithLocation(2, 31));\n\n CompareIncToFullParseErrors(reparsedTree, parsedTree);\n }\n\n [WorkItem(531404, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531404\")]\n [Fact]\n public void AppendDisabledText()\n {\n var text =\n@\"class SmallDictionary\n{\n public void Add(int key, int value)\n {\n int hash = key + value;\n#if DEBUG\";\n var originalTree = this.Parse(text);\n var changedTree = originalTree.WithInsertAt(text.Length, \"\\r\\n hash++;\");\n var parsedTree = this.Parse(changedTree.GetCompilationUnitRoot().ToFullString());\n\n Assert.Equal(\n parsedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan,\n changedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan);\n }\n\n [Fact, WorkItem(531614, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531614\")]\n public void IncrementalParseStopAtEscapeBackSlash()\n {\n var text1 = @\"using System;\n\nclass Program\n{\n static void Main()\n {\n\";\n\n var text2 = @\" Console.WriteLine(\"\"\\'\\0\\a\\b\\\";\n\n var comp = CSharpTestBase.CreateCompilation(SyntaxFactory.ParseSyntaxTree(String.Empty));\n\n var oldTree = comp.SyntaxTrees.First();\n var oldIText = oldTree.GetText();\n var span = new TextSpan(oldIText.Length, 0);\n var change = new TextChange(span, text1);\n\n var newIText = oldIText.WithChanges(change);\n var newTree = oldTree.WithChangedText(newIText);\n\n var fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options);\n var fullText = fullTree.GetCompilationUnitRoot().ToFullString();\n var incText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(fullText.Length, incText.Length);\n Assert.Equal(fullText, incText);\n // \n oldTree = newTree;\n oldIText = oldTree.GetText();\n span = new TextSpan(oldIText.Length, 0);\n change = new TextChange(span, text2);\n\n newIText = oldIText.WithChanges(change);\n newTree = oldTree.WithChangedText(newIText);\n\n fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options);\n fullText = fullTree.GetCompilationUnitRoot().ToFullString();\n incText = newTree.GetCompilationUnitRoot().ToFullString();\n Assert.Equal(fullText.Length, incText.Length);\n Assert.Equal(fullText, incText);\n }\n\n [Fact, WorkItem(552741, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741\")]\n public void IncrementalParseTopDownCommentOutLines()\n {\n var text = @\"// Query Expression syntax \n// \n// from, join, on, equals, into, let, orderby, ascending, descending, group, by\n// @-with contextual keywords parseable as a type or identifier in a query expression\n// Various combinations\n// \n// \n\n//\n\n// \n\nusing System;\nusing System.Linq;\n\npublic class from { }\npublic class join { }\npublic class on { }\npublic class equals { }\npublic class into { }\npublic class let { }\npublic class orderby : let { }\npublic class ascending : orderby, descending { }\npublic interface descending { }\npublic class group { }\npublic class by { }\n\npublic class QueryExpressionTest\n{\n public static int Main()\n {\n var array02a = new[] { new join(), new join(), new join() } as object[];\n var array02b = new[] { new join(), new join(), new join() } as object[];\n var query02 = from i in array02a join j in array02b on (@from)i equals (@from)j select new { i, j };\n\n var array03a = new[] { new on(), new on(), new on() } as object[];\n var array03b = new[] { new on(), new on(), new on() } as object[];\n var query03 = from @on i in array03a join j in array03b on i equals (@on)j select new { i, j };\n\n var array04a = new[] { new equals(), new equals(), new equals() } as object[];\n\n return 0;\n }\n}\n\";\n\n var currTree = SyntaxFactory.ParseSyntaxTree(text);\n var currIText = currTree.GetText();\n\n var items = text.Split('\\n');\n int currLen = 0;\n foreach (var item in items)\n {\n var span = new TextSpan(currLen, 0);\n var change = new TextChange(span, \"// \");\n currLen += item.Length + 3;\n\n currIText = currIText.WithChanges(change);\n currTree = currTree.WithChangedText(currIText);\n\n var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString());\n\n int incCount = currTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count;\n int fullCount = fullTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count;\n\n WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n }\n\n [Fact, WorkItem(552741, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741\")]\n public void IncrementalParseStatementAfterQuery()\n {\n var text = @\"\nusing System.Linq;\n \nclass equals\n{\n static void Main(string[] args)\n {\n equals[] a;\n var q = from x in args select x;\n a = new[] { new equals() };\n }\n}\n\";\n\n var currTree = SyntaxFactory.ParseSyntaxTree(text);\n var currIText = currTree.GetText();\n\n // Insert \"// \" before the \"x\" in \"select x\"; the next statement becomes part of the query.\n var span = new TextSpan(text.LastIndexOf('x'), 0);\n var change = new TextChange(span, \"// \");\n\n currIText = currIText.WithChanges(change);\n currTree = currTree.WithChangedText(currIText);\n\n var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString());\n\n WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact, WorkItem(529260, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260\")]\n public void DoNotReuseAnnotatedNodes()\n {\n var text = @\"\nclass C { }\nclass D { }\n\";\n\n Func extractGreenClassC = tree =>\n tree.GetCompilationUnitRoot().Members.First().Green;\n\n // Check reuse after a trivial change in an unannotated tree.\n {\n var oldTree = SyntaxFactory.ParseSyntaxTree(text);\n var newTree = oldTree.WithInsertAt(text.Length, \" \");\n\n // Class declaration is reused.\n Assert.Same(extractGreenClassC(oldTree), extractGreenClassC(newTree));\n }\n\n // Check reuse after a trivial change in an annotated tree.\n {\n var tempTree = SyntaxFactory.ParseSyntaxTree(text);\n var tempRoot = tempTree.GetRoot();\n var tempToken = tempRoot.DescendantTokens().First(t => t.Kind() == SyntaxKind.IdentifierToken);\n var oldRoot = tempRoot.ReplaceToken(tempToken, tempToken.WithAdditionalAnnotations(new SyntaxAnnotation()));\n Assert.True(oldRoot.ContainsAnnotations, \"Should contain annotations.\");\n Assert.Equal(text, oldRoot.ToFullString());\n\n var oldTree = SyntaxFactory.SyntaxTree(oldRoot, options: tempTree.Options, path: tempTree.FilePath);\n var newTree = oldTree.WithInsertAt(text.Length, \" \");\n\n\n var oldClassC = extractGreenClassC(oldTree);\n var newClassC = extractGreenClassC(newTree);\n\n Assert.True(oldClassC.ContainsAnnotations, \"Should contain annotations\");\n Assert.False(newClassC.ContainsAnnotations, \"Annotations should have been removed.\");\n\n // Class declaration is not reused...\n Assert.NotSame(oldClassC, newClassC);\n // ...even though the text is the same.\n Assert.Equal(oldClassC.ToFullString(), newClassC.ToFullString());\n\n\n var oldToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)oldClassC).Identifier;\n var newToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)newClassC).Identifier;\n\n Assert.True(oldToken.ContainsAnnotations, \"Should contain annotations\");\n Assert.False(newToken.ContainsAnnotations, \"Annotations should have been removed.\");\n\n // Token is not reused...\n Assert.NotSame(oldToken, newToken);\n // ...even though the text is the same.\n Assert.Equal(oldToken.ToFullString(), newToken.ToFullString());\n }\n }\n\n [Fact]\n [WorkItem(658496, \"http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658496\")]\n public void DontReuseLambdaParameterAsMethodParameter()\n {\n var items = new string[]\n {\n \"a b.c*/ d => {e(f =>\",\n \"/*\",\n };\n\n var oldText = SourceText.From(items[0]);\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // f is a simple lambda parameter\n\n var change = new TextChange(new TextSpan(0, 0), items[1]); // Prepend\n var newText = oldText.WithChanges(change); // f is a method decl parameter\n\n var incrTree = oldTree.WithChangedText(newText);\n var fullTree = SyntaxFactory.ParseSyntaxTree(newText);\n\n Assert.Equal(\n fullTree.GetDiagnostics().Select(d => d.ToString()),\n incrTree.GetDiagnostics().Select(d => d.ToString()));\n\n WalkTreeAndVerify(incrTree.GetRoot(), fullTree.GetRoot());\n }\n\n\n [Fact]\n public void TestRescanInterpolatedString()\n {\n var interfaceKeyword = SyntaxFactory.ParseToken(\"interface\"); // prime the memoizer\n\n var text = @\"class goo { public void m() { string s = $\"\"{1} world\"\" ; } }\";\n var oldTree = this.Parse6(text);\n var newTree = oldTree.WithReplaceFirst(@\"world\"\" \", @\"world\"\" \");\n Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length);\n Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length);\n }\n\n [Fact]\n public void Goo()\n {\n var oldText = SourceText.From(@\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nclass Program\n{\n static void Main(string[] args)\n {\n\n }\n\n protected abstract int Stuff { get; }\n}\n\nclass G: Program\n{\n protected override int Stuff\n {\n get\n {\n throw new NotImplementedException();\n }\n }\n}\");\n var newText = SourceText.From(@\"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nclass Program\n{\n static void Main(string[] args)\n {\n\n }\n\n protected abstract int Stuff { get; }\n}\n\nclass G: Program\n{\n protected override int Stuff =>\n {\n get\n {\n throw new NotImplementedException();\n }\n }\n}\n\");\n var oldTree = SyntaxFactory.ParseSyntaxTree(oldText);\n var newTree = oldTree.WithChangedText(newText);\n WalkTreeAndVerify(newTree.GetCompilationUnitRoot(), SyntaxFactory.ParseSyntaxTree(newText).GetCompilationUnitRoot());\n }\n\n [WorkItem(23272, \"https://github.com/dotnet/roslyn/issues/23272\")]\n [Fact]\n public void AddAccessibilityToNullableArray()\n {\n var source =\n@\"class A { }\nclass B\n{\n A[]? F;\n}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\" A[]?\"), 0);\n var change = new TextChange(span, \"p\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n [WorkItem(37663, \"https://github.com/dotnet/roslyn/issues/37663\")]\n public void AssemblyAttributeBeforeNamespace()\n {\n var src = @\"\nusing System;\nusing System.Linq;\n\n[assembly:]\nnamespace N\n{ }\";\n var tree = SyntaxFactory.ParseSyntaxTree(src);\n var text = tree.GetText();\n var span = new TextSpan(src.IndexOf(\":\"), 1);\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddBracketInUsingDirective()\n {\n var source =\n@\"using System;\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\";\"), 0);\n var change = new TextChange(span, \"[\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddAttributeAfterUsingDirective()\n {\n var source =\n@\"using System;\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\";\") + 1, 0);\n var change = new TextChange(span, \"[Obsolete]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddTrailingModifierInUsingDirective()\n {\n var source =\n@\"using System;\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(\";\") + 1, 0);\n var change = new TextChange(span, \"public\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [WorkItem(37665, \"https://github.com/dotnet/roslyn/issues/37665\")]\n [Fact]\n public void AddTrailingModifierInUsingDirective_2()\n {\n var source =\n@\"using System;publi\nnamespace NS\n{\n class A { }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"publi\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"c\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void Statement_EditAttributeList_01()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr]\n void local1() { };\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"Attr\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"1, Attr2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void Statement_EditAttributeList_02()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n Method1();\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"Attr1\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \", Attr2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void Statement_AddAttributeList()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n void local1() { };\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"[Attr1]\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" [Attr2]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditStatementWithAttributes_01()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n void local1() { Method(); };\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"Method(\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"Arg\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditStatementWithAttributes_02()\n {\n var source = @\"\nclass C\n{\n void M()\n {\n [Attr1]\n Method1();\n }\n}\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"Method\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 1);\n var change = new TextChange(span, \"2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"[Attr] () => { }\")]\n [InlineData(\"[Attr] x => x\")]\n [InlineData(\"([Attr] x) => x\")]\n [InlineData(\"([Attr] int x) => x\")]\n public void Lambda_EditAttributeList(string lambdaExpression)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"Attr\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"1, Attr2\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"() => { }\", \"() => { }\")]\n [InlineData(\"x => x\", \"x => x\")]\n [InlineData(\"(x) => x\", \"x) => x\")]\n [InlineData(\"(int x) => x\", \"int x) => x\")]\n public void Lambda_AddFirstAttributeList(string lambdaExpression, string substring)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(source.IndexOf(substring), 0);\n var change = new TextChange(span, \"[Attr]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"[Attr1] () => { }\")]\n [InlineData(\"[Attr1] x => x\")]\n [InlineData(\"([Attr1] x) => x\")]\n [InlineData(\"([Attr1] int x) => x\")]\n public void Lambda_AddSecondAttributeList(string lambdaExpression)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"[Attr1]\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" [Attr2]\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Theory]\n [InlineData(\"[Attr] () => { }\")]\n [InlineData(\"[Attr] x => x\")]\n [InlineData(\"([Attr] x) => x\")]\n [InlineData(\"([Attr] int x) => x\")]\n public void Lambda_RemoveAttributeList(string lambdaExpression)\n {\n var source =\n$@\"class Program\n{{\n static void Main()\n {{\n F({lambdaExpression});\n }}\n}}\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"[Attr] \";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditGlobalStatementWithAttributes_01()\n {\n var source = @\"\n[Attr]\nx.y();\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"x.y\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \".z\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditGlobalStatementWithAttributes_02()\n {\n var source = @\"\n[Attr]\nif (b) { }\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"if (b) { }\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" if (c) { }\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditGlobalStatementWithAttributes_03()\n {\n var source = @\"\n[Attr]\nif (b) { }\n\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = @\"if (b) { }\";\n var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0);\n var change = new TextChange(span, \" else (c) { }\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditNestedStatementWithAttributes_01()\n {\n var source = \"{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(start: 0, length: 1); // delete first character\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditNestedStatementWithAttributes_02()\n {\n var source = \"{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var span = new TextSpan(start: 0, length: 0);\n var change = new TextChange(span, \"{ \");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n [Fact]\n public void EditNestedStatementWithAttributes_03()\n {\n var source = \"class C { void M() { Goo[Goo] [Goo]if(Goo) { } } }\";\n var tree = SyntaxFactory.ParseSyntaxTree(source);\n var text = tree.GetText();\n var substring = \"Goo[Goo]\";\n var span = new TextSpan(start: source.IndexOf(substring), length: 3); // Goo[Goo] -> [Goo]\n var change = new TextChange(span, \"\");\n text = text.WithChanges(change);\n tree = tree.WithChangedText(text);\n var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString());\n WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot());\n }\n\n #endregion\n\n #region Helper functions\n private void WalkTreeAndVerify(SyntaxNodeOrToken incNode, SyntaxNodeOrToken fullNode)\n {\n var incChildren = incNode.ChildNodesAndTokens();\n var fullChildren = fullNode.ChildNodesAndTokens();\n Assert.Equal(incChildren.Count, fullChildren.Count);\n\n for (int i = 0; i < incChildren.Count; i++)\n {\n var incChild = incChildren[i];\n var fullChild = fullChildren[i];\n\n WalkTreeAndVerify(incChild, fullChild);\n }\n }\n\n private static void CommentOutText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var newText = oldText.WithChanges(\n new TextChange[] {\n new TextChange(new TextSpan(locationOfChange, 0), \"/*\"),\n new TextChange(new TextSpan(locationOfChange + widthOfChange, 0), \"*/\")\n });\n var tree = SyntaxFactory.ParseSyntaxTree(oldText);\n incrementalTree = tree.WithChangedText(newText);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private static void RemoveText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var newText = oldText.WithChanges(new TextChange(new TextSpan(locationOfChange, widthOfChange), \"\"));\n var tree = SyntaxFactory.ParseSyntaxTree(oldText);\n incrementalTree = tree.WithChangedText(newText);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private void CompareIncToFullParseErrors(SyntaxTree incrementalTree, SyntaxTree parsedTree)\n {\n var pd = parsedTree.GetDiagnostics();\n var id = incrementalTree.GetDiagnostics();\n Assert.Equal(pd.Count(), id.Count());\n for (int i = 0; i < id.Count(); i++)\n {\n Assert.Equal(pd.ElementAt(i).Inspect(), id.ElementAt(i).Inspect());\n }\n\n ParentChecker.CheckParents(parsedTree.GetCompilationUnitRoot(), parsedTree);\n ParentChecker.CheckParents(incrementalTree.GetCompilationUnitRoot(), incrementalTree);\n }\n\n private static void CharByCharIncrementalParse(SourceText oldText, char newChar, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText);\n\n // first make certain this text round trips\n Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString());\n var newText = oldText.WithChanges(new TextChange(new TextSpan(oldText.Length, 0), newChar.ToString()));\n incrementalTree = startTree.WithChangedText(newText);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private static void TokenByTokenBottomUp(SourceText oldText, string token, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)\n {\n var startTree = SyntaxFactory.ParseSyntaxTree(oldText);\n SourceText newText = SourceText.From(token + oldText.ToString());\n incrementalTree = startTree.WithInsertAt(0, token);\n parsedTree = SyntaxFactory.ParseSyntaxTree(newText);\n }\n\n private static void CompareTreeEquivalence(SyntaxNodeOrToken parsedTreeNode, SyntaxNodeOrToken incrementalTreeNode)\n {\n Assert.Equal(parsedTreeNode.Kind(), incrementalTreeNode.Kind());\n\n Assert.Equal(parsedTreeNode.ChildNodesAndTokens().Count, incrementalTreeNode.ChildNodesAndTokens().Count);\n\n for (int i = 0; i < parsedTreeNode.ChildNodesAndTokens().Count; i++)\n {\n CompareTreeEquivalence(parsedTreeNode.ChildNodesAndTokens()[i], incrementalTreeNode.ChildNodesAndTokens()[i]);\n }\n }\n\n #endregion\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":448,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/Tests/TestWriter.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\n'-----------------------------------------------------------------------------------------------------------\n' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated\n' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data\n' structures like the kinds, visitor, etc.\n'-----------------------------------------------------------------------------------------------------------\n\nImports System.IO\n\nPublic Class TestWriter\n Inherits WriteUtils\n\n Private ReadOnly _checksum As String\n Private _writer As TextWriter 'output is sent here.\n Private Const s_externalSourceDirectiveString As String = \"ExternalSourceDirective\"\n\n ' Initialize the class with the parse tree to write.\n Public Sub New(parseTree As ParseTree, checksum As String)\n MyBase.New(parseTree)\n _checksum = checksum\n End Sub\n\n ' Write out the code defining the tree to the give file.\n Public Sub WriteTestCode(writer As TextWriter)\n _writer = writer\n\n GenerateFile()\n End Sub\n\n Private Sub GenerateFile()\n _writer.WriteLine(\"' Tests for parse trees.\")\n _writer.WriteLine(\"' DO NOT HAND EDIT\")\n _writer.WriteLine()\n\n GenerateNamespace()\n End Sub\n\n Private Sub GenerateNamespace()\n _writer.WriteLine()\n _writer.WriteLine(\"Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"Partial Public Class GeneratedTests\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Factory Calls\"\"\")\n GenerateFactoryCalls(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Factory Tests\"\"\")\n GenerateFactoryCallTests(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Rewriter Tests\"\"\")\n GenerateRewriterTests(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Visitor Tests\"\"\")\n GenerateVisitorTests(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Red Factory Calls\"\"\")\n GenerateFactoryCalls(False)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Red Factory Tests\"\"\")\n GenerateFactoryCallTests(False)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Red Rewriter Tests\"\"\")\n GenerateRewriterTests(False)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"End Class\")\n _writer.WriteLine(\"End Namespace\")\n End Sub\n\n Private Sub GenerateFactoryCalls(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then\n\n If Not nodeStructure.Name = \"KeywordSyntax\" AndAlso Not nodeStructure.Name = \"PunctuationSyntax\" Then\n GenerateFactoryCall(isGreen, nodeStructure)\n End If\n End If\n Next\n End Sub\n\n Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateFactoryCall(isGreen, nodeStructure, kind)\n Next\n\n 'If nodeStructure.NodeKinds.Count > 1 Then\n ' GenerateFactoryCall(isGreen, nodeStructure, Nothing)\n 'End If\n\n End Sub\n\n Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name = \"AttributeTarget\" AndAlso Not isGreen Then\n Dim x = 0\n End If\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim namespacePrefix As String = If(isGreen, \"InternalSyntax.\", String.Empty)\n\n _writer.Write(\" Private Shared Function \")\n\n Dim functionName As String = If(nodeKind Is Nothing, FactoryName(nodeStructure), FactoryName(nodeKind))\n\n If isGreen Then\n _writer.Write(\"GenerateGreen\" + functionName)\n Else\n _writer.Write(\"GenerateRed\" + functionName)\n End If\n\n If isGreen Then\n _writer.WriteLine(\"() As \" + namespacePrefix + nodeStructure.Name)\n Else\n\n If nodeStructure.IsToken Then\n _writer.WriteLine(\"() As SyntaxToken\")\n ElseIf nodeStructure.IsTrivia Then\n _writer.WriteLine(\"() As SyntaxTrivia\")\n Else\n _writer.WriteLine(\"() As {0}\", StructureTypeName(nodeStructure))\n End If\n End If\n\n Dim first As Boolean = True\n\n Dim callTokens As List(Of String) = New List(Of String)()\n Dim anePositions As List(Of Integer) = New List(Of Integer)()\n Dim aePositions As List(Of Integer) = New List(Of Integer)()\n Dim KindNonePositions As List(Of Integer) = New List(Of Integer)()\n\n Dim currentLine = 1\n\n If nodeKind Is Nothing Then\n callTokens.Add(namespacePrefix + \"SyntaxFactory.\" + nodeStructure.Name + \"(\")\n Else\n callTokens.Add(namespacePrefix + \"SyntaxFactory.\" + nodeKind.Name + \"(\")\n End If\n\n If nodeStructure.IsToken Then\n\n If isGreen Then\n If nodeStructure.IsTerminal Then\n callTokens.Add(\"String.Empty\")\n first = False\n End If\n Else\n If Not first Then callTokens.Add(\", \")\n first = False\n\n callTokens.Add(namespacePrefix + \"SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n\n 'If nodeStructure.Name.Contains(\"Xml\") Then\n ' callTokens.Add(\"String.Empty\")\n ' first = False\n 'End If\n\n If nodeKind.Name.EndsWith(\"LiteralToken\", StringComparison.Ordinal) OrElse\n nodeKind.Name.EndsWith(\"XmlNameToken\", StringComparison.Ordinal) OrElse\n nodeKind.Name.EndsWith(\"DocumentationCommentLineBreakToken\", StringComparison.Ordinal) OrElse\n nodeKind.Name = \"InterpolatedStringTextToken\" _\n Then\n If Not first Then callTokens.Add(\", \")\n callTokens.Add(\"String.Empty\")\n first = False\n End If\n\n End If\n\n Dim fields = GetAllFieldsOfStructure(nodeStructure)\n\n For Each field In fields\n\n If Not first Then callTokens.Add(\", \")\n first = False\n\n Dim fieldType = FieldTypeRef(field)\n callTokens.Add(GetInitValueForType(fieldType))\n\n Next\n\n If Not first Then callTokens.Add(\", \")\n first = False\n\n If isGreen Then\n callTokens.Add(namespacePrefix + \"SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"), \")\n callTokens.Add(namespacePrefix + \"SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n Else\n callTokens.Add(namespacePrefix + \"SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\")))\")\n End If\n\n If isGreen Then\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n Else\n _writer.WriteLine(\" Dim exceptionTest as boolean = false\")\n\n For exceptionChecks = 0 To anePositions.Count - 1\n\n _writer.WriteLine(\" Try\")\n\n For i = 0 To callTokens.Count - 1\n If (i <> anePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"Nothing\")\n End If\n Next\n\n _writer.WriteLine(\" catch e as ArgumentNullException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine(\" exceptionTest = false\")\n _writer.WriteLine()\n Next\n\n ' quick hack to cover more code in keyword factories ...\n If nodeStructure.IsTerminal AndAlso Not nodeStructure.IsTrivia AndAlso nodeStructure.Name = \"KeywordSyntax\" Then\n\n _writer.Write(\" Dim node1 = \")\n For i = 0 To callTokens.Count - 1\n _writer.Write(callTokens(i))\n If i = 0 Then _writer.Write(\"String.Empty, \")\n Next i\n _writer.WriteLine()\n\n _writer.Write(\" dim node2 = \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n\n _writer.WriteLine(\" Debug.Assert(node1.GetText() = String.Empty)\")\n _writer.WriteLine(\" Debug.Assert(node2.GetText() <> String.Empty)\")\n _writer.WriteLine()\n\n ' make parameter = nothing to cause exceptions\n _writer.WriteLine(\" Try\")\n _writer.WriteLine(\" exceptionTest = false\")\n\n For i = 0 To callTokens.Count - 1\n _writer.Write(callTokens(i))\n If i = 0 Then _writer.Write(\"Nothing, \")\n Next i\n _writer.WriteLine()\n\n _writer.WriteLine(\" catch e as ArgumentNullException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine()\n\n _writer.WriteLine(\" return node2\")\n Else\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n\n End If\n\n End If\n\n Else\n\n Dim children = GetAllFactoryChildrenOfStructure(nodeStructure)\n\n If nodeStructure.IsTrivia Then\n callTokens.Add(\"String.Empty\")\n anePositions.Add(callTokens.Count - 1)\n first = False\n End If\n\n For Each child In children\n If Not first Then\n callTokens.Add(\", \")\n End If\n\n If child.IsOptional Then\n ' Hack: remove when the factory methods have been fixed to not contain overloads.\n If nodeStructure.Name = \"MemberAccessExpressionSyntax\" Then\n If first Then\n callTokens.Add(String.Format(\"CType(Nothing, {0}{1})\", namespacePrefix, ChildFieldTypeRef(child)))\n End If\n Else\n callTokens.Add(\"Nothing\")\n End If\n\n ' TODO: remove\n first = False\n\n Continue For\n End If\n\n ' TODO: move up.\n first = False\n\n Dim childNodeKind As ParseNodeKind = If(Not child Is Nothing, TryCast(child.ChildKind, ParseNodeKind), Nothing)\n\n If TypeOf child.ChildKind Is List(Of ParseNodeKind) Then\n childNodeKind = child.ChildKind(nodeKind.Name)\n End If\n\n If childNodeKind Is Nothing Then\n childNodeKind = DirectCast(child.ChildKind, List(Of ParseNodeKind)).Item(0)\n End If\n\n If child.IsList AndAlso child.IsSeparated Then\n Dim childKindStructure = child.ParseTree.NodeStructures(childNodeKind.StructureId)\n childKindStructure = If(Not childKindStructure.ParentStructure Is Nothing, childKindStructure.ParentStructure, childKindStructure)\n callTokens.Add(\"New \" + ChildFactoryTypeRef(nodeStructure, child, isGreen, True) + \"()\")\n Else\n Dim structureOfchild = child.ParseTree.NodeStructures(childNodeKind.StructureId)\n If structureOfchild.Name = \"PunctuationSyntax\" OrElse structureOfchild.Name = \"KeywordSyntax\" Then\n\n If isGreen Then\n callTokens.Add(\"new InternalSyntax.\" + structureOfchild.Name + \"(\")\n callTokens.Add(\"SyntaxKind.\" + childNodeKind.Name + \", String.Empty, Nothing, Nothing)\")\n Else\n Dim token = \"SyntaxFactory.Token(SyntaxKind.\" + childNodeKind.Name + \")\"\n If child.IsList Then\n token = \"SyntaxTokenList.Create(\" & token & \")\"\n End If\n callTokens.Add(token)\n\n ' add none kind here\n If Not TypeOf child.ChildKind Is List(Of ParseNodeKind) Then\n If child.IsOptional Then\n KindNonePositions.Add(callTokens.Count - 1)\n End If\n Else\n If Not child.IsList Then\n aePositions.Add(callTokens.Count - 1)\n End If\n End If\n End If\n Else\n If isGreen Then\n callTokens.Add(\"GenerateGreen\" + FactoryName(childNodeKind) + \"()\")\n Else\n Dim result = \"GenerateRed\" + FactoryName(childNodeKind) + \"()\"\n If structureOfchild.IsToken AndAlso child.IsList Then\n result = \"SyntaxTokenList.Create(\" & result & \")\"\n ElseIf child.IsSeparated Then\n result = String.Format(\"SyntaxFactory.SingletonSeparatedList(Of {0}({1})\", BaseTypeReference(child), result)\n ElseIf child.IsList Then\n result = String.Format(\"SyntaxFactory.SingletonList(Of {0})({1})\", BaseTypeReference(child), result)\n End If\n callTokens.Add(result)\n End If\n End If\n\n If Not KindTypeStructure(child.ChildKind).IsToken AndAlso Not child.IsList Then\n anePositions.Add(callTokens.Count - 1)\n ElseIf KindTypeStructure(child.ChildKind).IsToken And Not child.IsList Then\n aePositions.Add(callTokens.Count - 1)\n End If\n End If\n Next\n\n callTokens.Add(\")\")\n\n ' TODO: remove extra conditions\n If isGreen OrElse nodeStructure.Name = \"CaseBlockSyntax\" OrElse nodeStructure.Name = \"IfPartSyntax\" OrElse nodeStructure.Name = \"MultiLineIfBlockSyntax\" Then\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n Else\n\n _writer.WriteLine(\" Dim exceptionTest as boolean = false\")\n\n For exceptionChecks = 0 To anePositions.Count - 1\n\n _writer.WriteLine(\" Try\")\n\n _writer.Write(\" \")\n For i = 0 To callTokens.Count - 1\n If (i <> anePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"Nothing\")\n End If\n Next\n _writer.WriteLine()\n\n _writer.WriteLine(\" catch e as ArgumentNullException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine(\" exceptionTest = false\")\n _writer.WriteLine()\n Next\n\n For exceptionChecks = 0 To aePositions.Count - 1\n\n _writer.WriteLine(\" Try\")\n _writer.Write(\" \")\n For i = 0 To callTokens.Count - 1\n If (i <> aePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"SyntaxFactory.Token(SyntaxKind.ExternalSourceKeyword)\") ' this syntaxtoken should not be legal anywhere in the tests\n End If\n Next\n _writer.WriteLine()\n\n _writer.WriteLine(\" catch e as ArgumentException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine(\" exceptionTest = false\")\n _writer.WriteLine()\n Next\n\n For exceptionChecks = 0 To KindNonePositions.Count - 1\n\n _writer.Write(\" \")\n For i = 0 To callTokens.Count - 1\n If (i <> KindNonePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"New SyntaxToken(Nothing, New InternalSyntax.KeywordSyntax(SyntaxKind.None, Nothing, Nothing, \"\"\"\", Nothing, Nothing), 0, 0)\")\n End If\n Next\n _writer.WriteLine()\n _writer.WriteLine()\n Next\n\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n End If\n\n End If\n\n _writer.WriteLine(\" End Function\")\n _writer.WriteLine()\n End Sub\n\n Private Sub GenerateFactoryCallTests(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then\n If Not nodeStructure.Name = \"KeywordSyntax\" AndAlso Not nodeStructure.Name = \"PunctuationSyntax\" Then\n GenerateFactoryCallTest(isGreen, nodeStructure)\n End If\n End If\n Next\n End Sub\n\n Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateFactoryCallTest(isGreen, nodeStructure, kind)\n Next\n End Sub\n\n Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim funcNamePart = If(isGreen, \"Green\", \"Red\")\n\n _writer.WriteLine(\" \")\n _writer.Write(\" Public Sub \")\n\n _writer.Write(\"Test{0}{1}\", funcNamePart, FactoryName(nodeKind))\n _writer.WriteLine(\"()\")\n\n _writer.WriteLine(\" dim objectUnderTest = Generate{0}{1}()\", funcNamePart, FactoryName(nodeKind))\n\n 'Dim children = GetAllChildrenOfStructure(nodeStructure)\n\n If isGreen Then\n _writer.WriteLine(\" AttachAndCheckDiagnostics(objectUnderTest)\")\n Else\n Dim withStat As String = Nothing\n For Each child In GetAllChildrenOfStructure(nodeStructure)\n If Not child.IsOptional Then\n _writer.WriteLine(\" Assert.NotNull(objectUnderTest.{0})\", LowerFirstCharacter(child.Name))\n End If\n withStat += String.Format(\".With{0}(objectUnderTest.{0})\", child.Name)\n Next\n If (withStat IsNot Nothing) Then\n _writer.WriteLine(\" Dim withObj = objectUnderTest{0}\", withStat)\n _writer.WriteLine(\" Assert.Equal(withobj, objectUnderTest)\")\n End If\n End If\n\n _writer.WriteLine(\" End Sub\")\n _writer.WriteLine()\n End Sub\n\n Private Sub GenerateRewriterTests(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then\n GenerateRewriterTest(isGreen, nodeStructure)\n End If\n Next\n End Sub\n\n Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateRewriterTest(isGreen, nodeStructure, kind)\n Next\n End Sub\n\n Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim funcNamePart = If(isGreen, \"Green\", \"Red\")\n\n _writer.WriteLine(\" \")\n _writer.Write(\" Public Sub \")\n\n _writer.Write(\"Test{0}{1}Rewriter\", funcNamePart, FactoryName(nodeKind))\n _writer.WriteLine(\"()\")\n\n _writer.WriteLine(\" dim oldNode = Generate{0}{1}()\", funcNamePart, FactoryName(nodeKind))\n _writer.WriteLine(\" Dim rewriter = New {0}IdentityRewriter()\", funcNamePart)\n _writer.WriteLine(\" Dim newNode = rewriter.Visit(oldNode)\")\n _writer.WriteLine(\" Assert.Equal(oldNode, newNode)\")\n _writer.WriteLine(\" End Sub\")\n _writer.WriteLine()\n\n End Sub\n\n Private Sub GenerateVisitorTests(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then\n GenerateVisitorTest(isGreen, nodeStructure)\n End If\n Next\n End Sub\n\n Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateVisitorTest(isGreen, nodeStructure, kind)\n Next\n End Sub\n\n Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim funcNamePart = If(isGreen, \"Green\", \"Red\")\n\n _writer.WriteLine(\" \")\n _writer.Write(\" Public Sub \")\n\n _writer.Write(\"Test\" + funcNamePart + FactoryName(nodeKind) + \"Visitor\")\n _writer.WriteLine(\"()\")\n\n _writer.WriteLine(\" Dim oldNode = Generate\" + funcNamePart + FactoryName(nodeKind) + \"()\")\n _writer.WriteLine(\" Dim visitor = New \" + funcNamePart + \"NodeVisitor()\")\n _writer.WriteLine(\" visitor.Visit(oldNode)\")\n _writer.WriteLine(\" End Sub\")\n _writer.WriteLine()\n End Sub\n\n Public Function GetInitValueForType(fieldType As String) As String\n Select Case fieldType\n Case \"Integer\"\n Return \"23\"\n Case \"String\"\n Return \"\"\"Bar\"\"\"\n Case \"Char\"\n Return \"\"\"E\"\"C\"\n Case \"DateTime\"\n Return \"New DateTime(2008,11,04)\"\n Case \"System.Decimal\"\n Return \"42\"\n Case \"TypeCharacter\"\n Return \"TypeCharacter.DecimalLiteral\"\n Case \"SyntaxKind\"\n Return \"SyntaxKind.IdentifierName\"\n Case Else\n Return \"Unknown Type\"\n End Select\n End Function\n\n Public Sub AddHandwrittenFactoryCall(baseType As String)\n\n Select Case baseType\n Case \"IdentifierTokenSyntax\"\n _writer.Write(\"new InternalSyntax.SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, \"\"text\"\",\")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"), \")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n\n Case \"IntegerLiteralTokenSyntax\"\n _writer.Write(\"new InternalSyntax.IntegerLiteralToken(\"\"42\"\", LiteralBase.Decimal, TypeCharacter.None, 42,\")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"), \")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n\n End Select\n End Sub\n\nEnd Class\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\n'-----------------------------------------------------------------------------------------------------------\n' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated\n' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data\n' structures like the kinds, visitor, etc.\n'-----------------------------------------------------------------------------------------------------------\n\nImports System.IO\n\nPublic Class TestWriter\n Inherits WriteUtils\n\n Private ReadOnly _checksum As String\n Private _writer As TextWriter 'output is sent here.\n Private Const s_externalSourceDirectiveString As String = \"ExternalSourceDirective\"\n\n ' Initialize the class with the parse tree to write.\n Public Sub New(parseTree As ParseTree, checksum As String)\n MyBase.New(parseTree)\n _checksum = checksum\n End Sub\n\n ' Write out the code defining the tree to the give file.\n Public Sub WriteTestCode(writer As TextWriter)\n _writer = writer\n\n GenerateFile()\n End Sub\n\n Private Sub GenerateFile()\n _writer.WriteLine(\"' Tests for parse trees.\")\n _writer.WriteLine(\"' DO NOT HAND EDIT\")\n _writer.WriteLine()\n\n GenerateNamespace()\n End Sub\n\n Private Sub GenerateNamespace()\n _writer.WriteLine()\n _writer.WriteLine(\"Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"Partial Public Class GeneratedTests\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Factory Calls\"\"\")\n GenerateFactoryCalls(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Factory Tests\"\"\")\n GenerateFactoryCallTests(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Rewriter Tests\"\"\")\n GenerateRewriterTests(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Green Visitor Tests\"\"\")\n GenerateVisitorTests(True)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Red Factory Calls\"\"\")\n GenerateFactoryCalls(False)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Red Factory Tests\"\"\")\n GenerateFactoryCallTests(False)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"#region \"\"Red Rewriter Tests\"\"\")\n GenerateRewriterTests(False)\n _writer.WriteLine(\"#end region\")\n _writer.WriteLine()\n\n _writer.WriteLine(\"End Class\")\n _writer.WriteLine(\"End Namespace\")\n End Sub\n\n Private Sub GenerateFactoryCalls(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then\n\n If Not nodeStructure.Name = \"KeywordSyntax\" AndAlso Not nodeStructure.Name = \"PunctuationSyntax\" Then\n GenerateFactoryCall(isGreen, nodeStructure)\n End If\n End If\n Next\n End Sub\n\n Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateFactoryCall(isGreen, nodeStructure, kind)\n Next\n\n 'If nodeStructure.NodeKinds.Count > 1 Then\n ' GenerateFactoryCall(isGreen, nodeStructure, Nothing)\n 'End If\n\n End Sub\n\n Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name = \"AttributeTarget\" AndAlso Not isGreen Then\n Dim x = 0\n End If\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim namespacePrefix As String = If(isGreen, \"InternalSyntax.\", String.Empty)\n\n _writer.Write(\" Private Shared Function \")\n\n Dim functionName As String = If(nodeKind Is Nothing, FactoryName(nodeStructure), FactoryName(nodeKind))\n\n If isGreen Then\n _writer.Write(\"GenerateGreen\" + functionName)\n Else\n _writer.Write(\"GenerateRed\" + functionName)\n End If\n\n If isGreen Then\n _writer.WriteLine(\"() As \" + namespacePrefix + nodeStructure.Name)\n Else\n\n If nodeStructure.IsToken Then\n _writer.WriteLine(\"() As SyntaxToken\")\n ElseIf nodeStructure.IsTrivia Then\n _writer.WriteLine(\"() As SyntaxTrivia\")\n Else\n _writer.WriteLine(\"() As {0}\", StructureTypeName(nodeStructure))\n End If\n End If\n\n Dim first As Boolean = True\n\n Dim callTokens As List(Of String) = New List(Of String)()\n Dim anePositions As List(Of Integer) = New List(Of Integer)()\n Dim aePositions As List(Of Integer) = New List(Of Integer)()\n Dim KindNonePositions As List(Of Integer) = New List(Of Integer)()\n\n Dim currentLine = 1\n\n If nodeKind Is Nothing Then\n callTokens.Add(namespacePrefix + \"SyntaxFactory.\" + nodeStructure.Name + \"(\")\n Else\n callTokens.Add(namespacePrefix + \"SyntaxFactory.\" + nodeKind.Name + \"(\")\n End If\n\n If nodeStructure.IsToken Then\n\n If isGreen Then\n If nodeStructure.IsTerminal Then\n callTokens.Add(\"String.Empty\")\n first = False\n End If\n Else\n If Not first Then callTokens.Add(\", \")\n first = False\n\n callTokens.Add(namespacePrefix + \"SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n\n 'If nodeStructure.Name.Contains(\"Xml\") Then\n ' callTokens.Add(\"String.Empty\")\n ' first = False\n 'End If\n\n If nodeKind.Name.EndsWith(\"LiteralToken\", StringComparison.Ordinal) OrElse\n nodeKind.Name.EndsWith(\"XmlNameToken\", StringComparison.Ordinal) OrElse\n nodeKind.Name.EndsWith(\"DocumentationCommentLineBreakToken\", StringComparison.Ordinal) OrElse\n nodeKind.Name = \"InterpolatedStringTextToken\" _\n Then\n If Not first Then callTokens.Add(\", \")\n callTokens.Add(\"String.Empty\")\n first = False\n End If\n\n End If\n\n Dim fields = GetAllFieldsOfStructure(nodeStructure)\n\n For Each field In fields\n\n If Not first Then callTokens.Add(\", \")\n first = False\n\n Dim fieldType = FieldTypeRef(field)\n callTokens.Add(GetInitValueForType(fieldType))\n\n Next\n\n If Not first Then callTokens.Add(\", \")\n first = False\n\n If isGreen Then\n callTokens.Add(namespacePrefix + \"SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"), \")\n callTokens.Add(namespacePrefix + \"SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n Else\n callTokens.Add(namespacePrefix + \"SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\")))\")\n End If\n\n If isGreen Then\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n Else\n _writer.WriteLine(\" Dim exceptionTest as boolean = false\")\n\n For exceptionChecks = 0 To anePositions.Count - 1\n\n _writer.WriteLine(\" Try\")\n\n For i = 0 To callTokens.Count - 1\n If (i <> anePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"Nothing\")\n End If\n Next\n\n _writer.WriteLine(\" catch e as ArgumentNullException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine(\" exceptionTest = false\")\n _writer.WriteLine()\n Next\n\n ' quick hack to cover more code in keyword factories ...\n If nodeStructure.IsTerminal AndAlso Not nodeStructure.IsTrivia AndAlso nodeStructure.Name = \"KeywordSyntax\" Then\n\n _writer.Write(\" Dim node1 = \")\n For i = 0 To callTokens.Count - 1\n _writer.Write(callTokens(i))\n If i = 0 Then _writer.Write(\"String.Empty, \")\n Next i\n _writer.WriteLine()\n\n _writer.Write(\" dim node2 = \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n\n _writer.WriteLine(\" Debug.Assert(node1.GetText() = String.Empty)\")\n _writer.WriteLine(\" Debug.Assert(node2.GetText() <> String.Empty)\")\n _writer.WriteLine()\n\n ' make parameter = nothing to cause exceptions\n _writer.WriteLine(\" Try\")\n _writer.WriteLine(\" exceptionTest = false\")\n\n For i = 0 To callTokens.Count - 1\n _writer.Write(callTokens(i))\n If i = 0 Then _writer.Write(\"Nothing, \")\n Next i\n _writer.WriteLine()\n\n _writer.WriteLine(\" catch e as ArgumentNullException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine()\n\n _writer.WriteLine(\" return node2\")\n Else\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n\n End If\n\n End If\n\n Else\n\n Dim children = GetAllFactoryChildrenOfStructure(nodeStructure)\n\n If nodeStructure.IsTrivia Then\n callTokens.Add(\"String.Empty\")\n anePositions.Add(callTokens.Count - 1)\n first = False\n End If\n\n For Each child In children\n If Not first Then\n callTokens.Add(\", \")\n End If\n\n If child.IsOptional Then\n ' Hack: remove when the factory methods have been fixed to not contain overloads.\n If nodeStructure.Name = \"MemberAccessExpressionSyntax\" Then\n If first Then\n callTokens.Add(String.Format(\"CType(Nothing, {0}{1})\", namespacePrefix, ChildFieldTypeRef(child)))\n End If\n Else\n callTokens.Add(\"Nothing\")\n End If\n\n ' TODO: remove\n first = False\n\n Continue For\n End If\n\n ' TODO: move up.\n first = False\n\n Dim childNodeKind As ParseNodeKind = If(Not child Is Nothing, TryCast(child.ChildKind, ParseNodeKind), Nothing)\n\n If TypeOf child.ChildKind Is List(Of ParseNodeKind) Then\n childNodeKind = child.ChildKind(nodeKind.Name)\n End If\n\n If childNodeKind Is Nothing Then\n childNodeKind = DirectCast(child.ChildKind, List(Of ParseNodeKind)).Item(0)\n End If\n\n If child.IsList AndAlso child.IsSeparated Then\n Dim childKindStructure = child.ParseTree.NodeStructures(childNodeKind.StructureId)\n childKindStructure = If(Not childKindStructure.ParentStructure Is Nothing, childKindStructure.ParentStructure, childKindStructure)\n callTokens.Add(\"New \" + ChildFactoryTypeRef(nodeStructure, child, isGreen, True) + \"()\")\n Else\n Dim structureOfchild = child.ParseTree.NodeStructures(childNodeKind.StructureId)\n If structureOfchild.Name = \"PunctuationSyntax\" OrElse structureOfchild.Name = \"KeywordSyntax\" Then\n\n If isGreen Then\n callTokens.Add(\"new InternalSyntax.\" + structureOfchild.Name + \"(\")\n callTokens.Add(\"SyntaxKind.\" + childNodeKind.Name + \", String.Empty, Nothing, Nothing)\")\n Else\n Dim token = \"SyntaxFactory.Token(SyntaxKind.\" + childNodeKind.Name + \")\"\n If child.IsList Then\n token = \"SyntaxTokenList.Create(\" & token & \")\"\n End If\n callTokens.Add(token)\n\n ' add none kind here\n If Not TypeOf child.ChildKind Is List(Of ParseNodeKind) Then\n If child.IsOptional Then\n KindNonePositions.Add(callTokens.Count - 1)\n End If\n Else\n If Not child.IsList Then\n aePositions.Add(callTokens.Count - 1)\n End If\n End If\n End If\n Else\n If isGreen Then\n callTokens.Add(\"GenerateGreen\" + FactoryName(childNodeKind) + \"()\")\n Else\n Dim result = \"GenerateRed\" + FactoryName(childNodeKind) + \"()\"\n If structureOfchild.IsToken AndAlso child.IsList Then\n result = \"SyntaxTokenList.Create(\" & result & \")\"\n ElseIf child.IsSeparated Then\n result = String.Format(\"SyntaxFactory.SingletonSeparatedList(Of {0}({1})\", BaseTypeReference(child), result)\n ElseIf child.IsList Then\n result = String.Format(\"SyntaxFactory.SingletonList(Of {0})({1})\", BaseTypeReference(child), result)\n End If\n callTokens.Add(result)\n End If\n End If\n\n If Not KindTypeStructure(child.ChildKind).IsToken AndAlso Not child.IsList Then\n anePositions.Add(callTokens.Count - 1)\n ElseIf KindTypeStructure(child.ChildKind).IsToken And Not child.IsList Then\n aePositions.Add(callTokens.Count - 1)\n End If\n End If\n Next\n\n callTokens.Add(\")\")\n\n ' TODO: remove extra conditions\n If isGreen OrElse nodeStructure.Name = \"CaseBlockSyntax\" OrElse nodeStructure.Name = \"IfPartSyntax\" OrElse nodeStructure.Name = \"MultiLineIfBlockSyntax\" Then\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n Else\n\n _writer.WriteLine(\" Dim exceptionTest as boolean = false\")\n\n For exceptionChecks = 0 To anePositions.Count - 1\n\n _writer.WriteLine(\" Try\")\n\n _writer.Write(\" \")\n For i = 0 To callTokens.Count - 1\n If (i <> anePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"Nothing\")\n End If\n Next\n _writer.WriteLine()\n\n _writer.WriteLine(\" catch e as ArgumentNullException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine(\" exceptionTest = false\")\n _writer.WriteLine()\n Next\n\n For exceptionChecks = 0 To aePositions.Count - 1\n\n _writer.WriteLine(\" Try\")\n _writer.Write(\" \")\n For i = 0 To callTokens.Count - 1\n If (i <> aePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"SyntaxFactory.Token(SyntaxKind.ExternalSourceKeyword)\") ' this syntaxtoken should not be legal anywhere in the tests\n End If\n Next\n _writer.WriteLine()\n\n _writer.WriteLine(\" catch e as ArgumentException\")\n _writer.WriteLine(\" exceptionTest = true\")\n _writer.WriteLine(\" End Try\")\n _writer.WriteLine(\" Debug.Assert(exceptionTest)\")\n _writer.WriteLine(\" exceptionTest = false\")\n _writer.WriteLine()\n Next\n\n For exceptionChecks = 0 To KindNonePositions.Count - 1\n\n _writer.Write(\" \")\n For i = 0 To callTokens.Count - 1\n If (i <> KindNonePositions(exceptionChecks)) Then\n _writer.Write(callTokens(i))\n Else\n _writer.Write(\"New SyntaxToken(Nothing, New InternalSyntax.KeywordSyntax(SyntaxKind.None, Nothing, Nothing, \"\"\"\", Nothing, Nothing), 0, 0)\")\n End If\n Next\n _writer.WriteLine()\n _writer.WriteLine()\n Next\n\n _writer.Write(\" return \")\n callTokens.ForEach(AddressOf _writer.Write)\n _writer.WriteLine()\n End If\n\n End If\n\n _writer.WriteLine(\" End Function\")\n _writer.WriteLine()\n End Sub\n\n Private Sub GenerateFactoryCallTests(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then\n If Not nodeStructure.Name = \"KeywordSyntax\" AndAlso Not nodeStructure.Name = \"PunctuationSyntax\" Then\n GenerateFactoryCallTest(isGreen, nodeStructure)\n End If\n End If\n Next\n End Sub\n\n Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateFactoryCallTest(isGreen, nodeStructure, kind)\n Next\n End Sub\n\n Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim funcNamePart = If(isGreen, \"Green\", \"Red\")\n\n _writer.WriteLine(\" \")\n _writer.Write(\" Public Sub \")\n\n _writer.Write(\"Test{0}{1}\", funcNamePart, FactoryName(nodeKind))\n _writer.WriteLine(\"()\")\n\n _writer.WriteLine(\" dim objectUnderTest = Generate{0}{1}()\", funcNamePart, FactoryName(nodeKind))\n\n 'Dim children = GetAllChildrenOfStructure(nodeStructure)\n\n If isGreen Then\n _writer.WriteLine(\" AttachAndCheckDiagnostics(objectUnderTest)\")\n Else\n Dim withStat As String = Nothing\n For Each child In GetAllChildrenOfStructure(nodeStructure)\n If Not child.IsOptional Then\n _writer.WriteLine(\" Assert.NotNull(objectUnderTest.{0})\", LowerFirstCharacter(child.Name))\n End If\n withStat += String.Format(\".With{0}(objectUnderTest.{0})\", child.Name)\n Next\n If (withStat IsNot Nothing) Then\n _writer.WriteLine(\" Dim withObj = objectUnderTest{0}\", withStat)\n _writer.WriteLine(\" Assert.Equal(withobj, objectUnderTest)\")\n End If\n End If\n\n _writer.WriteLine(\" End Sub\")\n _writer.WriteLine()\n End Sub\n\n Private Sub GenerateRewriterTests(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then\n GenerateRewriterTest(isGreen, nodeStructure)\n End If\n Next\n End Sub\n\n Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateRewriterTest(isGreen, nodeStructure, kind)\n Next\n End Sub\n\n Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim funcNamePart = If(isGreen, \"Green\", \"Red\")\n\n _writer.WriteLine(\" \")\n _writer.Write(\" Public Sub \")\n\n _writer.Write(\"Test{0}{1}Rewriter\", funcNamePart, FactoryName(nodeKind))\n _writer.WriteLine(\"()\")\n\n _writer.WriteLine(\" dim oldNode = Generate{0}{1}()\", funcNamePart, FactoryName(nodeKind))\n _writer.WriteLine(\" Dim rewriter = New {0}IdentityRewriter()\", funcNamePart)\n _writer.WriteLine(\" Dim newNode = rewriter.Visit(oldNode)\")\n _writer.WriteLine(\" Assert.Equal(oldNode, newNode)\")\n _writer.WriteLine(\" End Sub\")\n _writer.WriteLine()\n\n End Sub\n\n Private Sub GenerateVisitorTests(isGreen As Boolean)\n For Each nodeStructure In _parseTree.NodeStructures.Values\n If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then\n GenerateVisitorTest(isGreen, nodeStructure)\n End If\n Next\n End Sub\n\n Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure)\n For Each kind In nodeStructure.NodeKinds\n GenerateVisitorTest(isGreen, nodeStructure, kind)\n Next\n End Sub\n\n Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)\n\n If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then\n Return ' check for fix\n End If\n\n Dim funcNamePart = If(isGreen, \"Green\", \"Red\")\n\n _writer.WriteLine(\" \")\n _writer.Write(\" Public Sub \")\n\n _writer.Write(\"Test\" + funcNamePart + FactoryName(nodeKind) + \"Visitor\")\n _writer.WriteLine(\"()\")\n\n _writer.WriteLine(\" Dim oldNode = Generate\" + funcNamePart + FactoryName(nodeKind) + \"()\")\n _writer.WriteLine(\" Dim visitor = New \" + funcNamePart + \"NodeVisitor()\")\n _writer.WriteLine(\" visitor.Visit(oldNode)\")\n _writer.WriteLine(\" End Sub\")\n _writer.WriteLine()\n End Sub\n\n Public Function GetInitValueForType(fieldType As String) As String\n Select Case fieldType\n Case \"Integer\"\n Return \"23\"\n Case \"String\"\n Return \"\"\"Bar\"\"\"\n Case \"Char\"\n Return \"\"\"E\"\"C\"\n Case \"DateTime\"\n Return \"New DateTime(2008,11,04)\"\n Case \"System.Decimal\"\n Return \"42\"\n Case \"TypeCharacter\"\n Return \"TypeCharacter.DecimalLiteral\"\n Case \"SyntaxKind\"\n Return \"SyntaxKind.IdentifierName\"\n Case Else\n Return \"Unknown Type\"\n End Select\n End Function\n\n Public Sub AddHandwrittenFactoryCall(baseType As String)\n\n Select Case baseType\n Case \"IdentifierTokenSyntax\"\n _writer.Write(\"new InternalSyntax.SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, \"\"text\"\",\")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"), \")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n\n Case \"IntegerLiteralTokenSyntax\"\n _writer.Write(\"new InternalSyntax.IntegerLiteralToken(\"\"42\"\", LiteralBase.Decimal, TypeCharacter.None, 42,\")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"), \")\n _writer.Write(\"InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, \"\" \"\"))\")\n\n End Select\n End Sub\n\nEnd Class\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":449,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Threading\nImports Microsoft.CodeAnalysis\nImports Microsoft.CodeAnalysis.Formatting\nImports Microsoft.CodeAnalysis.PooledObjects\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic.Formatting\n Partial Friend Class VisualBasicTriviaFormatter\n Inherits AbstractTriviaFormatter\n\n Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia(\"_\")\n Private _newLine As SyntaxTrivia\n\n Private _succeeded As Boolean = True\n\n Public Sub New(context As FormattingContext,\n formattingRules As ChainedFormattingRules,\n token1 As SyntaxToken,\n token2 As SyntaxToken,\n originalString As String,\n lineBreaks As Integer,\n spaces As Integer)\n MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces)\n End Sub\n\n Protected Overrides Function Succeeded() As Boolean\n Return _succeeded\n End Function\n\n Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean\n Return trivia.RawKind = SyntaxKind.WhitespaceTrivia\n End Function\n\n Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean\n Return trivia.RawKind = SyntaxKind.EndOfLineTrivia\n End Function\n\n Protected Overrides Function IsWhitespace(ch As Char) As Boolean\n Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch)\n End Function\n\n Protected Overrides Function IsNewLine(ch As Char) As Boolean\n Return SyntaxFacts.IsNewLine(ch)\n End Function\n\n Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia\n Return SyntaxFactory.Whitespace(text)\n End Function\n\n Protected Overrides Function CreateEndOfLine() As SyntaxTrivia\n If _newLine = Nothing Then\n Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine)\n _newLine = SyntaxFactory.EndOfLine(text)\n End If\n\n Return _newLine\n End Function\n\n Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule\n\n ' line continuation\n If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then\n Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1)\n End If\n\n If IsStartOrEndOfFile(trivia1, trivia2) Then\n Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0)\n End If\n\n ' :: case\n If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso\n trivia2.Kind = SyntaxKind.ColonTrivia Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)\n End If\n\n ' : after : token\n If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)\n End If\n\n ' : [token]\n If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso\n Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n If trivia1.Kind = SyntaxKind.ColonTrivia OrElse\n trivia2.Kind = SyntaxKind.ColonTrivia Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n ' [trivia] [whitespace] [token] case\n If trivia2.Kind = SyntaxKind.None Then\n Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing\n\n If insertNewLine Then\n Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)\n End If\n\n Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)\n End If\n\n ' preprocessor case\n If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then\n ' if this is the first line of the file, don't put extra line 1\n Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None)\n\n Dim lines = If(firstLine, 0, 1)\n Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0)\n End If\n\n ' comment before a Case Statement case\n If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso\n Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then\n Return LineColumnRule.Preserve\n End If\n\n ' comment case\n If trivia2.Kind = SyntaxKind.CommentTrivia OrElse\n trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then\n\n ' [token] [whitespace] [trivia] case\n If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then\n Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then\n Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then\n Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)\n End If\n\n Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)\n End If\n\n ' skipped tokens\n If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then\n _succeeded = False\n End If\n\n Return LineColumnRule.Preserve\n End Function\n\n Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean\n Return False\n End Function\n\n Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean\n Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0)\n End Function\n\n Protected Overloads Overrides Function Format(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of SyntaxTrivia),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.HasStructure Then\n Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)\n End If\n\n If trivia.Kind = SyntaxKind.LineContinuationTrivia Then\n trivia = FormatLineContinuationTrivia(trivia)\n End If\n\n changes.Add(trivia)\n Return GetLineColumnDelta(lineColumn, trivia)\n End Function\n\n Protected Overloads Overrides Function Format(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of TextChange),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.HasStructure Then\n Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)\n End If\n\n If trivia.Kind = SyntaxKind.LineContinuationTrivia Then\n Dim lineContinuation = FormatLineContinuationTrivia(trivia)\n\n If trivia <> lineContinuation Then\n changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString()))\n End If\n\n Return GetLineColumnDelta(lineColumn, lineContinuation)\n End If\n\n Return GetLineColumnDelta(lineColumn, trivia)\n End Function\n\n Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia\n If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then\n Return _lineContinuationTrivia\n End If\n\n Return trivia\n End Function\n\n Private Function FormatStructuredTrivia(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of SyntaxTrivia),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then\n ' don't touch anything if it contains skipped tokens\n _succeeded = False\n\n changes.Add(trivia)\n Return GetLineColumnDelta(lineColumn, trivia)\n End If\n\n ' TODO : make document comment to be formatted by structured trivia formatter as well.\n If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then\n Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)\n Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))\n\n changes.Add(formattedTrivia)\n Return GetLineColumnDelta(lineColumn, formattedTrivia)\n End If\n\n Dim docComment = FormatDocumentComment(lineColumn, trivia)\n changes.Add(docComment)\n\n Return GetLineColumnDelta(lineColumn, docComment)\n End Function\n\n Private Function FormatStructuredTrivia(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of TextChange),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then\n ' don't touch anything if it contains skipped tokens\n _succeeded = False\n Return GetLineColumnDelta(lineColumn, trivia)\n End If\n\n ' TODO : make document comment to be formatted by structured trivia formatter as well.\n If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then\n Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(\n trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)\n\n If result.GetTextChanges(cancellationToken).Count = 0 Then\n Return GetLineColumnDelta(lineColumn, trivia)\n End If\n\n changes.AddRange(result.GetTextChanges(cancellationToken))\n\n Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))\n Return GetLineColumnDelta(lineColumn, formattedTrivia)\n End If\n\n Dim docComment = FormatDocumentComment(lineColumn, trivia)\n If docComment <> trivia Then\n changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString()))\n End If\n\n Return GetLineColumnDelta(lineColumn, docComment)\n End Function\n\n Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia\n\n Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart)\n\n Dim text = trivia.ToFullString()\n\n ' When the doc comment is parsed from source, even if it is only one\n ' line long, the end-of-line will get included into the trivia text.\n ' If the doc comment was parsed from a text fragment, there may not be\n ' an end-of-line at all. We need to trim the end before we check the\n ' number of line breaks in the text.\n#If NETCOREAPP Then\n Dim textWithoutFinalNewLine = text.TrimEnd()\n#Else\n Dim textWithoutFinalNewLine = text.TrimEnd(Nothing)\n#End If\n If Not textWithoutFinalNewLine.ContainsLineBreak() Then\n Return trivia\n End If\n\n Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment(\n forceIndentation:=True,\n indentation:=indentation,\n indentationDelta:=0,\n useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs),\n tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize),\n newLine:=Me.Options.GetOption(FormattingOptions2.NewLine))\n\n If text = singlelineDocComments Then\n Return trivia\n End If\n\n Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments)\n Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1)\n\n Return singlelineDocCommentTrivia.ElementAt(0)\n End Function\n\n End Class\nEnd Namespace\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Threading\nImports Microsoft.CodeAnalysis\nImports Microsoft.CodeAnalysis.Formatting\nImports Microsoft.CodeAnalysis.PooledObjects\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic.Formatting\n Partial Friend Class VisualBasicTriviaFormatter\n Inherits AbstractTriviaFormatter\n\n Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia(\"_\")\n Private _newLine As SyntaxTrivia\n\n Private _succeeded As Boolean = True\n\n Public Sub New(context As FormattingContext,\n formattingRules As ChainedFormattingRules,\n token1 As SyntaxToken,\n token2 As SyntaxToken,\n originalString As String,\n lineBreaks As Integer,\n spaces As Integer)\n MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces)\n End Sub\n\n Protected Overrides Function Succeeded() As Boolean\n Return _succeeded\n End Function\n\n Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean\n Return trivia.RawKind = SyntaxKind.WhitespaceTrivia\n End Function\n\n Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean\n Return trivia.RawKind = SyntaxKind.EndOfLineTrivia\n End Function\n\n Protected Overrides Function IsWhitespace(ch As Char) As Boolean\n Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch)\n End Function\n\n Protected Overrides Function IsNewLine(ch As Char) As Boolean\n Return SyntaxFacts.IsNewLine(ch)\n End Function\n\n Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia\n Return SyntaxFactory.Whitespace(text)\n End Function\n\n Protected Overrides Function CreateEndOfLine() As SyntaxTrivia\n If _newLine = Nothing Then\n Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine)\n _newLine = SyntaxFactory.EndOfLine(text)\n End If\n\n Return _newLine\n End Function\n\n Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule\n\n ' line continuation\n If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then\n Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1)\n End If\n\n If IsStartOrEndOfFile(trivia1, trivia2) Then\n Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0)\n End If\n\n ' :: case\n If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso\n trivia2.Kind = SyntaxKind.ColonTrivia Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)\n End If\n\n ' : after : token\n If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)\n End If\n\n ' : [token]\n If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso\n Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n If trivia1.Kind = SyntaxKind.ColonTrivia OrElse\n trivia2.Kind = SyntaxKind.ColonTrivia Then\n Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n ' [trivia] [whitespace] [token] case\n If trivia2.Kind = SyntaxKind.None Then\n Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing\n\n If insertNewLine Then\n Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)\n End If\n\n Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)\n End If\n\n ' preprocessor case\n If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then\n ' if this is the first line of the file, don't put extra line 1\n Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None)\n\n Dim lines = If(firstLine, 0, 1)\n Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0)\n End If\n\n ' comment before a Case Statement case\n If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso\n Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then\n Return LineColumnRule.Preserve\n End If\n\n ' comment case\n If trivia2.Kind = SyntaxKind.CommentTrivia OrElse\n trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then\n\n ' [token] [whitespace] [trivia] case\n If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then\n Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then\n Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)\n End If\n\n If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then\n Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)\n End If\n\n Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)\n End If\n\n ' skipped tokens\n If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then\n _succeeded = False\n End If\n\n Return LineColumnRule.Preserve\n End Function\n\n Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean\n Return False\n End Function\n\n Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean\n Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0)\n End Function\n\n Protected Overloads Overrides Function Format(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of SyntaxTrivia),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.HasStructure Then\n Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)\n End If\n\n If trivia.Kind = SyntaxKind.LineContinuationTrivia Then\n trivia = FormatLineContinuationTrivia(trivia)\n End If\n\n changes.Add(trivia)\n Return GetLineColumnDelta(lineColumn, trivia)\n End Function\n\n Protected Overloads Overrides Function Format(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of TextChange),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.HasStructure Then\n Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)\n End If\n\n If trivia.Kind = SyntaxKind.LineContinuationTrivia Then\n Dim lineContinuation = FormatLineContinuationTrivia(trivia)\n\n If trivia <> lineContinuation Then\n changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString()))\n End If\n\n Return GetLineColumnDelta(lineColumn, lineContinuation)\n End If\n\n Return GetLineColumnDelta(lineColumn, trivia)\n End Function\n\n Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia\n If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then\n Return _lineContinuationTrivia\n End If\n\n Return trivia\n End Function\n\n Private Function FormatStructuredTrivia(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of SyntaxTrivia),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then\n ' don't touch anything if it contains skipped tokens\n _succeeded = False\n\n changes.Add(trivia)\n Return GetLineColumnDelta(lineColumn, trivia)\n End If\n\n ' TODO : make document comment to be formatted by structured trivia formatter as well.\n If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then\n Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)\n Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))\n\n changes.Add(formattedTrivia)\n Return GetLineColumnDelta(lineColumn, formattedTrivia)\n End If\n\n Dim docComment = FormatDocumentComment(lineColumn, trivia)\n changes.Add(docComment)\n\n Return GetLineColumnDelta(lineColumn, docComment)\n End Function\n\n Private Function FormatStructuredTrivia(lineColumn As LineColumn,\n trivia As SyntaxTrivia,\n changes As ArrayBuilder(Of TextChange),\n cancellationToken As CancellationToken) As LineColumnDelta\n If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then\n ' don't touch anything if it contains skipped tokens\n _succeeded = False\n Return GetLineColumnDelta(lineColumn, trivia)\n End If\n\n ' TODO : make document comment to be formatted by structured trivia formatter as well.\n If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then\n Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(\n trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)\n\n If result.GetTextChanges(cancellationToken).Count = 0 Then\n Return GetLineColumnDelta(lineColumn, trivia)\n End If\n\n changes.AddRange(result.GetTextChanges(cancellationToken))\n\n Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))\n Return GetLineColumnDelta(lineColumn, formattedTrivia)\n End If\n\n Dim docComment = FormatDocumentComment(lineColumn, trivia)\n If docComment <> trivia Then\n changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString()))\n End If\n\n Return GetLineColumnDelta(lineColumn, docComment)\n End Function\n\n Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia\n\n Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart)\n\n Dim text = trivia.ToFullString()\n\n ' When the doc comment is parsed from source, even if it is only one\n ' line long, the end-of-line will get included into the trivia text.\n ' If the doc comment was parsed from a text fragment, there may not be\n ' an end-of-line at all. We need to trim the end before we check the\n ' number of line breaks in the text.\n#If NETCOREAPP Then\n Dim textWithoutFinalNewLine = text.TrimEnd()\n#Else\n Dim textWithoutFinalNewLine = text.TrimEnd(Nothing)\n#End If\n If Not textWithoutFinalNewLine.ContainsLineBreak() Then\n Return trivia\n End If\n\n Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment(\n forceIndentation:=True,\n indentation:=indentation,\n indentationDelta:=0,\n useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs),\n tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize),\n newLine:=Me.Options.GetOption(FormattingOptions2.NewLine))\n\n If text = singlelineDocComments Then\n Return trivia\n End If\n\n Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments)\n Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1)\n\n Return singlelineDocCommentTrivia.ElementAt(0)\n End Function\n\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":450,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreation.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Collections.Immutable\nImports System.Diagnostics\nImports Microsoft.CodeAnalysis.PooledObjects\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic\n Partial Friend NotInheritable Class LocalRewriter\n Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode\n\n ' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them\n ' two times.\n Dim objectInitializer = node.InitializerOpt\n node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type)\n\n Dim ctor = node.ConstructorOpt\n Dim result As BoundExpression = node\n\n If ctor IsNot Nothing Then\n Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing\n Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing\n\n result = node.Update(ctor,\n RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False),\n node.DefaultArguments,\n Nothing,\n ctor.ContainingType)\n\n If Not temporaries.IsDefault Then\n result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack)\n End If\n\n ' If a coclass was instantiated, convert the class to the interface type.\n If node.Type.IsInterfaceType() Then\n Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType))\n\n Dim useSiteInfo = GetNewCompoundUseSiteInfo()\n Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo)\n Debug.Assert(Conversions.ConversionExists(conv))\n _diagnostics.Add(result, useSiteInfo)\n result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing)\n Else\n Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type))\n End If\n End If\n\n If objectInitializer IsNot Nothing Then\n Return VisitObjectCreationInitializer(objectInitializer, node, result)\n End If\n\n Return result\n End Function\n\n Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode\n ' For the NoPIA feature, we need to gather the GUID from the coclass, and \n ' generate the following:\n ' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType)\n '\n ' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework),\n ' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID.\n\n Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics)\n\n Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor)\n Dim newGuid As BoundExpression\n If ctor IsNot Nothing Then\n newGuid = factory.[New](ctor, factory.Literal(node.GuidString))\n Else\n newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)\n End If\n\n Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True),\n factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID))\n Dim callGetTypeFromCLSID As BoundExpression\n If getTypeFromCLSID IsNot Nothing Then\n callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid)\n Else\n callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)\n End If\n\n Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance)\n Dim rewrittenObjectCreation As BoundExpression\n If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then\n Dim useSiteInfo = GetNewCompoundUseSiteInfo()\n Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo)\n _diagnostics.Add(node, useSiteInfo)\n rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type)\n Else\n rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True)\n End If\n\n If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then\n Return rewrittenObjectCreation\n End If\n\n Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation)\n End Function\n\n Private Function VisitObjectCreationInitializer(\n objectInitializer As BoundObjectInitializerExpressionBase,\n objectCreationExpression As BoundExpression,\n rewrittenObjectCreationExpression As BoundExpression\n ) As BoundNode\n If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then\n Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression),\n objectCreationExpression, rewrittenObjectCreationExpression)\n Else\n Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression),\n objectCreationExpression, rewrittenObjectCreationExpression)\n End If\n End Function\n\n Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode\n ' Unlike C#, \"New T()\" is always rewritten as \"Activator.CreateInstance()\",\n ' even if T is known to be a value type or reference type. This matches Dev10 VB.\n\n If _inExpressionLambda Then\n ' NOTE: If we are in expression lambda, we want to keep BoundNewT \n ' NOTE: node, but we need to rewrite initializers if any.\n\n If node.InitializerOpt IsNot Nothing Then\n Return VisitObjectCreationInitializer(node.InitializerOpt, node, node)\n Else\n Return node\n End If\n End If\n\n Dim syntax = node.Syntax\n Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol)\n\n Dim result As BoundExpression\n\n Dim method As MethodSymbol = Nothing\n If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then\n Debug.Assert(method IsNot Nothing)\n method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter))\n\n result = New BoundCall(syntax,\n method,\n methodGroupOpt:=Nothing,\n receiverOpt:=Nothing,\n arguments:=ImmutableArray(Of BoundExpression).Empty,\n constantValueOpt:=Nothing,\n isLValue:=False,\n suppressObjectClone:=False,\n type:=typeParameter)\n Else\n result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True)\n End If\n\n If node.InitializerOpt IsNot Nothing Then\n Return VisitObjectCreationInitializer(node.InitializerOpt, result, result)\n End If\n\n Return result\n End Function\n\n ''' \n ''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary.\n ''' E.g. the following code:\n ''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}}\n ''' gets rewritten to \n ''' Dim temp as CollectionType \n ''' temp = new CollectionType(param1)\n ''' temp.Add(1)\n ''' temp.Add(2, 3)\n ''' temp.Add(4, {5, 6, 7})\n ''' x = temp\n ''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression\n ''' only represents the object creation expression with the initialization.\n ''' \n ''' The BoundCollectionInitializerExpression that should be rewritten.\n ''' A bound sequence for the object creation expression containing the invocation expressions.\n Public Function RewriteCollectionInitializerExpression(\n node As BoundCollectionInitializerExpression,\n objectCreationExpression As BoundExpression,\n rewrittenObjectCreationExpression As BoundExpression\n ) As BoundNode\n Debug.Assert(node.PlaceholderOpt IsNot Nothing)\n\n Dim expressionType = node.Type\n\n Dim syntaxNode = node.Syntax\n Dim tempLocalSymbol As LocalSymbol\n Dim tempLocal As BoundLocal\n Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance()\n Dim newPlaceholder As BoundWithLValueExpressionPlaceholder\n\n If _inExpressionLambda Then\n ' A temp is not needed for this case \n tempLocalSymbol = Nothing\n tempLocal = Nothing\n\n ' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to \n ' keep the double rewrite tracking happy.\n newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type)\n AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder)\n Else\n ' Create a temp symbol \n ' Dim temp as CollectionType\n\n ' Create assignment for the rewritten object \n ' creation expression to the temp\n ' temp = new CollectionType(param1)\n tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)\n tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)\n Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode,\n tempLocal,\n GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),\n suppressObjectClone:=True,\n type:=expressionType)\n expressions.Add(temporaryAssignment)\n\n newPlaceholder = Nothing\n AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal)\n End If\n\n Dim initializerCount = node.Initializers.Length\n\n ' rewrite the invocation expressions and add them to the expression of the sequence\n ' temp.Add(...)\n For initializerIndex = 0 To initializerCount - 1\n ' NOTE: if the method Add(...) is omitted we build a local which\n ' seems to be redundant, this will optimized out later \n ' by stack scheduler\n Dim initializer As BoundExpression = node.Initializers(initializerIndex)\n If Not IsOmittedBoundCall(initializer) Then\n expressions.Add(VisitExpressionNode(initializer))\n End If\n Next\n\n RemovePlaceholderReplacement(node.PlaceholderOpt)\n\n If _inExpressionLambda Then\n Debug.Assert(tempLocalSymbol Is Nothing)\n Debug.Assert(tempLocal Is Nothing)\n\n ' NOTE: if inside expression lambda we rewrite the collection initializer \n ' NOTE: node and attach it back to object creation expression, it will be \n ' NOTE: rewritten later in ExpressionLambdaRewriter\n\n ' Rewrite object creation\n Return ReplaceObjectOrCollectionInitializer(\n rewrittenObjectCreationExpression,\n node.Update(newPlaceholder,\n expressions.ToImmutableAndFree(),\n node.Type))\n Else\n Debug.Assert(tempLocalSymbol IsNot Nothing)\n Debug.Assert(tempLocal IsNot Nothing)\n\n Return New BoundSequence(syntaxNode,\n ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol),\n expressions.ToImmutableAndFree(),\n tempLocal.MakeRValue(),\n expressionType)\n End If\n End Function\n\n ''' \n ''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound\n ''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is \n ''' stored in the bound object member initializer node itself.\n ''' \n ''' E.g. the following code:\n ''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}\n ''' gets rewritten to \n ''' Dim temp as RefTypeName \n ''' temp = new RefTypeName(param1)\n ''' temp.FieldName1 = 23\n ''' temp.FieldName2 = temp.FieldName3\n ''' temp.FieldName4 = x.FieldName1\n ''' x = temp\n ''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression\n ''' only represents the object creation expression with the initialization.\n ''' \n ''' In a case where no temporary is used the following code:\n ''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}\n ''' gets rewritten to \n ''' x = new ValueTypeName(param1)\n ''' x.FieldName1 = 23\n ''' x.FieldName2 = x.FieldName3\n ''' x.FieldName4 = x.FieldName1\n ''' \n ''' The BoundObjectInitializerExpression that should be rewritten.\n ''' A bound sequence for the object creation expression containing the invocation expressions, or a \n ''' bound statement list if no temporary should be used.\n Public Function RewriteObjectInitializerExpression(\n node As BoundObjectInitializerExpression,\n objectCreationExpression As BoundExpression,\n rewrittenObjectCreationExpression As BoundExpression\n ) As BoundNode\n Dim targetObjectReference As BoundExpression\n Dim expressionType = node.Type\n Dim initializerCount = node.Initializers.Length\n Dim syntaxNode = node.Syntax\n Dim sequenceType As TypeSymbol\n Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol)\n Dim sequenceValueExpression As BoundExpression\n\n Debug.Assert(node.PlaceholderOpt IsNot Nothing)\n\n ' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially\n ' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to \n ' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments,\n ' NOTE: ExpressionLambdaRewriter will get rid of them\n ' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the \n ' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself\n\n If node.CreateTemporaryLocalForInitialization Then\n ' create temporary\n ' Dim temp as RefTypeName \n Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)\n sequenceType = expressionType\n\n sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol)\n\n targetObjectReference = If(_inExpressionLambda,\n DirectCast(node.PlaceholderOpt, BoundExpression),\n New BoundLocal(syntaxNode, tempLocalSymbol, expressionType))\n sequenceValueExpression = targetObjectReference.MakeRValue()\n AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference)\n Else\n ' Get the receiver for the current initialized variable in case of an \"AsNew\" declaration\n ' this is the only case where there might be no temporary needed.\n ' The replacement for this placeholder was added in VisitAsNewLocalDeclarations.\n targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt)\n sequenceType = GetSpecialType(SpecialType.System_Void)\n\n sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty\n sequenceValueExpression = Nothing\n End If\n\n Dim sequenceExpressions(initializerCount) As BoundExpression\n\n ' create assignment for object creation expression to temporary or variable declaration\n ' x = new TypeName(...)\n ' or\n ' temp = new TypeName(...)\n sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode,\n targetObjectReference,\n GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),\n suppressObjectClone:=True,\n type:=expressionType)\n\n ' rewrite the assignment expressions and add them to the statement list\n ' x.FieldName = value expression\n ' or\n ' temp.FieldName = value expression\n For initializerIndex = 0 To initializerCount - 1\n If _inExpressionLambda Then\n ' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part \n ' NOTE: will be kept unchanged to make sure we got proper symbol out of it \n Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator)\n Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing)\n sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left,\n assignment.LeftOnTheRightOpt,\n VisitExpressionNode(assignment.Right),\n True,\n assignment.Type)\n Else\n sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex))\n End If\n Next\n\n If node.CreateTemporaryLocalForInitialization Then\n RemovePlaceholderReplacement(node.PlaceholderOpt)\n End If\n\n If _inExpressionLambda Then\n ' when converting object initializer inside expression lambdas we want to keep \n ' object initializer in object creation expression; we just store visited initializers \n ' back to the original object initializer and update the original object creation expression\n\n ' create new initializers\n Dim newInitializers(initializerCount - 1) As BoundExpression\n Dim errors As Boolean = False\n For index = 0 To initializerCount - 1\n newInitializers(index) = sequenceExpressions(index + 1)\n Next\n\n ' Rewrite object creation\n Return ReplaceObjectOrCollectionInitializer(\n rewrittenObjectCreationExpression,\n node.Update(node.CreateTemporaryLocalForInitialization,\n node.PlaceholderOpt,\n newInitializers.AsImmutableOrNull(),\n node.Type))\n End If\n\n Return New BoundSequence(syntaxNode,\n sequenceTemporaries,\n sequenceExpressions.AsImmutableOrNull,\n sequenceValueExpression,\n sequenceType)\n End Function\n\n Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression\n Select Case rewrittenObjectCreationExpression.Kind\n Case BoundKind.ObjectCreationExpression\n Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression)\n Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type)\n\n Case BoundKind.NewT\n Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT)\n Return newT.Update(rewrittenInitializer, newT.Type)\n\n Case BoundKind.Sequence\n ' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it \n ' NOTE: was probably wrapped with sequence which means that this case is not supported \n ' NOTE: inside expression lambdas.\n Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence)\n Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression)\n Return sequence.Update(sequence.Locals,\n sequence.SideEffects,\n ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer),\n sequence.Type)\n\n Case Else\n Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind)\n End Select\n End Function\n\n End Class\nEnd Namespace\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Collections.Immutable\nImports System.Diagnostics\nImports Microsoft.CodeAnalysis.PooledObjects\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic\n Partial Friend NotInheritable Class LocalRewriter\n Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode\n\n ' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them\n ' two times.\n Dim objectInitializer = node.InitializerOpt\n node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type)\n\n Dim ctor = node.ConstructorOpt\n Dim result As BoundExpression = node\n\n If ctor IsNot Nothing Then\n Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing\n Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing\n\n result = node.Update(ctor,\n RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False),\n node.DefaultArguments,\n Nothing,\n ctor.ContainingType)\n\n If Not temporaries.IsDefault Then\n result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack)\n End If\n\n ' If a coclass was instantiated, convert the class to the interface type.\n If node.Type.IsInterfaceType() Then\n Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType))\n\n Dim useSiteInfo = GetNewCompoundUseSiteInfo()\n Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo)\n Debug.Assert(Conversions.ConversionExists(conv))\n _diagnostics.Add(result, useSiteInfo)\n result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing)\n Else\n Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type))\n End If\n End If\n\n If objectInitializer IsNot Nothing Then\n Return VisitObjectCreationInitializer(objectInitializer, node, result)\n End If\n\n Return result\n End Function\n\n Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode\n ' For the NoPIA feature, we need to gather the GUID from the coclass, and \n ' generate the following:\n ' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType)\n '\n ' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework),\n ' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID.\n\n Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics)\n\n Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor)\n Dim newGuid As BoundExpression\n If ctor IsNot Nothing Then\n newGuid = factory.[New](ctor, factory.Literal(node.GuidString))\n Else\n newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)\n End If\n\n Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True),\n factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID))\n Dim callGetTypeFromCLSID As BoundExpression\n If getTypeFromCLSID IsNot Nothing Then\n callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid)\n Else\n callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)\n End If\n\n Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance)\n Dim rewrittenObjectCreation As BoundExpression\n If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then\n Dim useSiteInfo = GetNewCompoundUseSiteInfo()\n Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo)\n _diagnostics.Add(node, useSiteInfo)\n rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type)\n Else\n rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True)\n End If\n\n If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then\n Return rewrittenObjectCreation\n End If\n\n Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation)\n End Function\n\n Private Function VisitObjectCreationInitializer(\n objectInitializer As BoundObjectInitializerExpressionBase,\n objectCreationExpression As BoundExpression,\n rewrittenObjectCreationExpression As BoundExpression\n ) As BoundNode\n If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then\n Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression),\n objectCreationExpression, rewrittenObjectCreationExpression)\n Else\n Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression),\n objectCreationExpression, rewrittenObjectCreationExpression)\n End If\n End Function\n\n Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode\n ' Unlike C#, \"New T()\" is always rewritten as \"Activator.CreateInstance()\",\n ' even if T is known to be a value type or reference type. This matches Dev10 VB.\n\n If _inExpressionLambda Then\n ' NOTE: If we are in expression lambda, we want to keep BoundNewT \n ' NOTE: node, but we need to rewrite initializers if any.\n\n If node.InitializerOpt IsNot Nothing Then\n Return VisitObjectCreationInitializer(node.InitializerOpt, node, node)\n Else\n Return node\n End If\n End If\n\n Dim syntax = node.Syntax\n Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol)\n\n Dim result As BoundExpression\n\n Dim method As MethodSymbol = Nothing\n If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then\n Debug.Assert(method IsNot Nothing)\n method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter))\n\n result = New BoundCall(syntax,\n method,\n methodGroupOpt:=Nothing,\n receiverOpt:=Nothing,\n arguments:=ImmutableArray(Of BoundExpression).Empty,\n constantValueOpt:=Nothing,\n isLValue:=False,\n suppressObjectClone:=False,\n type:=typeParameter)\n Else\n result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True)\n End If\n\n If node.InitializerOpt IsNot Nothing Then\n Return VisitObjectCreationInitializer(node.InitializerOpt, result, result)\n End If\n\n Return result\n End Function\n\n ''' \n ''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary.\n ''' E.g. the following code:\n ''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}}\n ''' gets rewritten to \n ''' Dim temp as CollectionType \n ''' temp = new CollectionType(param1)\n ''' temp.Add(1)\n ''' temp.Add(2, 3)\n ''' temp.Add(4, {5, 6, 7})\n ''' x = temp\n ''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression\n ''' only represents the object creation expression with the initialization.\n ''' \n ''' The BoundCollectionInitializerExpression that should be rewritten.\n ''' A bound sequence for the object creation expression containing the invocation expressions.\n Public Function RewriteCollectionInitializerExpression(\n node As BoundCollectionInitializerExpression,\n objectCreationExpression As BoundExpression,\n rewrittenObjectCreationExpression As BoundExpression\n ) As BoundNode\n Debug.Assert(node.PlaceholderOpt IsNot Nothing)\n\n Dim expressionType = node.Type\n\n Dim syntaxNode = node.Syntax\n Dim tempLocalSymbol As LocalSymbol\n Dim tempLocal As BoundLocal\n Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance()\n Dim newPlaceholder As BoundWithLValueExpressionPlaceholder\n\n If _inExpressionLambda Then\n ' A temp is not needed for this case \n tempLocalSymbol = Nothing\n tempLocal = Nothing\n\n ' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to \n ' keep the double rewrite tracking happy.\n newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type)\n AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder)\n Else\n ' Create a temp symbol \n ' Dim temp as CollectionType\n\n ' Create assignment for the rewritten object \n ' creation expression to the temp\n ' temp = new CollectionType(param1)\n tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)\n tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)\n Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode,\n tempLocal,\n GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),\n suppressObjectClone:=True,\n type:=expressionType)\n expressions.Add(temporaryAssignment)\n\n newPlaceholder = Nothing\n AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal)\n End If\n\n Dim initializerCount = node.Initializers.Length\n\n ' rewrite the invocation expressions and add them to the expression of the sequence\n ' temp.Add(...)\n For initializerIndex = 0 To initializerCount - 1\n ' NOTE: if the method Add(...) is omitted we build a local which\n ' seems to be redundant, this will optimized out later \n ' by stack scheduler\n Dim initializer As BoundExpression = node.Initializers(initializerIndex)\n If Not IsOmittedBoundCall(initializer) Then\n expressions.Add(VisitExpressionNode(initializer))\n End If\n Next\n\n RemovePlaceholderReplacement(node.PlaceholderOpt)\n\n If _inExpressionLambda Then\n Debug.Assert(tempLocalSymbol Is Nothing)\n Debug.Assert(tempLocal Is Nothing)\n\n ' NOTE: if inside expression lambda we rewrite the collection initializer \n ' NOTE: node and attach it back to object creation expression, it will be \n ' NOTE: rewritten later in ExpressionLambdaRewriter\n\n ' Rewrite object creation\n Return ReplaceObjectOrCollectionInitializer(\n rewrittenObjectCreationExpression,\n node.Update(newPlaceholder,\n expressions.ToImmutableAndFree(),\n node.Type))\n Else\n Debug.Assert(tempLocalSymbol IsNot Nothing)\n Debug.Assert(tempLocal IsNot Nothing)\n\n Return New BoundSequence(syntaxNode,\n ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol),\n expressions.ToImmutableAndFree(),\n tempLocal.MakeRValue(),\n expressionType)\n End If\n End Function\n\n ''' \n ''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound\n ''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is \n ''' stored in the bound object member initializer node itself.\n ''' \n ''' E.g. the following code:\n ''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}\n ''' gets rewritten to \n ''' Dim temp as RefTypeName \n ''' temp = new RefTypeName(param1)\n ''' temp.FieldName1 = 23\n ''' temp.FieldName2 = temp.FieldName3\n ''' temp.FieldName4 = x.FieldName1\n ''' x = temp\n ''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression\n ''' only represents the object creation expression with the initialization.\n ''' \n ''' In a case where no temporary is used the following code:\n ''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1}\n ''' gets rewritten to \n ''' x = new ValueTypeName(param1)\n ''' x.FieldName1 = 23\n ''' x.FieldName2 = x.FieldName3\n ''' x.FieldName4 = x.FieldName1\n ''' \n ''' The BoundObjectInitializerExpression that should be rewritten.\n ''' A bound sequence for the object creation expression containing the invocation expressions, or a \n ''' bound statement list if no temporary should be used.\n Public Function RewriteObjectInitializerExpression(\n node As BoundObjectInitializerExpression,\n objectCreationExpression As BoundExpression,\n rewrittenObjectCreationExpression As BoundExpression\n ) As BoundNode\n Dim targetObjectReference As BoundExpression\n Dim expressionType = node.Type\n Dim initializerCount = node.Initializers.Length\n Dim syntaxNode = node.Syntax\n Dim sequenceType As TypeSymbol\n Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol)\n Dim sequenceValueExpression As BoundExpression\n\n Debug.Assert(node.PlaceholderOpt IsNot Nothing)\n\n ' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially\n ' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to \n ' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments,\n ' NOTE: ExpressionLambdaRewriter will get rid of them\n ' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the \n ' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself\n\n If node.CreateTemporaryLocalForInitialization Then\n ' create temporary\n ' Dim temp as RefTypeName \n Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp)\n sequenceType = expressionType\n\n sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol)\n\n targetObjectReference = If(_inExpressionLambda,\n DirectCast(node.PlaceholderOpt, BoundExpression),\n New BoundLocal(syntaxNode, tempLocalSymbol, expressionType))\n sequenceValueExpression = targetObjectReference.MakeRValue()\n AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference)\n Else\n ' Get the receiver for the current initialized variable in case of an \"AsNew\" declaration\n ' this is the only case where there might be no temporary needed.\n ' The replacement for this placeholder was added in VisitAsNewLocalDeclarations.\n targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt)\n sequenceType = GetSpecialType(SpecialType.System_Void)\n\n sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty\n sequenceValueExpression = Nothing\n End If\n\n Dim sequenceExpressions(initializerCount) As BoundExpression\n\n ' create assignment for object creation expression to temporary or variable declaration\n ' x = new TypeName(...)\n ' or\n ' temp = new TypeName(...)\n sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode,\n targetObjectReference,\n GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression),\n suppressObjectClone:=True,\n type:=expressionType)\n\n ' rewrite the assignment expressions and add them to the statement list\n ' x.FieldName = value expression\n ' or\n ' temp.FieldName = value expression\n For initializerIndex = 0 To initializerCount - 1\n If _inExpressionLambda Then\n ' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part \n ' NOTE: will be kept unchanged to make sure we got proper symbol out of it \n Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator)\n Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing)\n sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left,\n assignment.LeftOnTheRightOpt,\n VisitExpressionNode(assignment.Right),\n True,\n assignment.Type)\n Else\n sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex))\n End If\n Next\n\n If node.CreateTemporaryLocalForInitialization Then\n RemovePlaceholderReplacement(node.PlaceholderOpt)\n End If\n\n If _inExpressionLambda Then\n ' when converting object initializer inside expression lambdas we want to keep \n ' object initializer in object creation expression; we just store visited initializers \n ' back to the original object initializer and update the original object creation expression\n\n ' create new initializers\n Dim newInitializers(initializerCount - 1) As BoundExpression\n Dim errors As Boolean = False\n For index = 0 To initializerCount - 1\n newInitializers(index) = sequenceExpressions(index + 1)\n Next\n\n ' Rewrite object creation\n Return ReplaceObjectOrCollectionInitializer(\n rewrittenObjectCreationExpression,\n node.Update(node.CreateTemporaryLocalForInitialization,\n node.PlaceholderOpt,\n newInitializers.AsImmutableOrNull(),\n node.Type))\n End If\n\n Return New BoundSequence(syntaxNode,\n sequenceTemporaries,\n sequenceExpressions.AsImmutableOrNull,\n sequenceValueExpression,\n sequenceType)\n End Function\n\n Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression\n Select Case rewrittenObjectCreationExpression.Kind\n Case BoundKind.ObjectCreationExpression\n Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression)\n Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type)\n\n Case BoundKind.NewT\n Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT)\n Return newT.Update(rewrittenInitializer, newT.Type)\n\n Case BoundKind.Sequence\n ' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it \n ' NOTE: was probably wrapped with sequence which means that this case is not supported \n ' NOTE: inside expression lambdas.\n Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence)\n Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression)\n Return sequence.Update(sequence.Locals,\n sequence.SideEffects,\n ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer),\n sequence.Type)\n\n Case Else\n Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind)\n End Select\n End Function\n\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":451,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertyAccessorSymbol.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Collections.Immutable\nImports System.Threading\nImports Microsoft.CodeAnalysis.PooledObjects\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic.Symbols\n Friend NotInheritable Class SourcePropertyAccessorSymbol\n Inherits SourceMethodSymbol\n\n Protected ReadOnly m_property As SourcePropertySymbol\n Private ReadOnly _name As String\n Private _lazyMetadataName As String\n\n Private _lazyExplicitImplementations As ImmutableArray(Of MethodSymbol) ' lazily populated with explicit implementations\n\n ' Parameters.\n Private _lazyParameters As ImmutableArray(Of ParameterSymbol)\n\n ' Return type. Void for a Sub.\n Private _lazyReturnType As TypeSymbol\n\n Friend Sub New(propertySymbol As SourcePropertySymbol,\n name As String,\n flags As SourceMemberFlags,\n syntaxRef As SyntaxReference,\n locations As ImmutableArray(Of Location))\n\n MyBase.New(\n propertySymbol.ContainingSourceType,\n If(flags.ToMethodKind() = MethodKind.PropertyGet, flags, flags And Not SourceMemberFlags.Iterator),\n syntaxRef,\n locations)\n\n m_property = propertySymbol\n _name = name\n End Sub\n\n Private Shared Function SynthesizeAutoGetterParameters(getter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol)\n If propertySymbol.ParameterCount = 0 Then\n Return ImmutableArray(Of ParameterSymbol).Empty\n End If\n\n Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount)\n propertySymbol.CloneParametersForAccessor(getter, parameters)\n Return parameters.ToImmutableAndFree()\n End Function\n\n Private Shared Function SynthesizeAutoSetterParameters(setter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol)\n Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter(\n setter,\n propertySymbol,\n If(propertySymbol.IsAutoProperty, StringConstants.AutoPropertyValueParameterName, StringConstants.ValueParameterName))\n\n If propertySymbol.ParameterCount = 0 Then\n Return ImmutableArray.Create(valueParameter)\n End If\n\n Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount + 1)\n propertySymbol.CloneParametersForAccessor(setter, parameters)\n parameters.Add(valueParameter)\n Return parameters.ToImmutableAndFree()\n End Function\n\n Friend Shared Function CreatePropertyAccessor(propertySymbol As SourcePropertySymbol,\n kindFlags As SourceMemberFlags,\n propertyFlags As SourceMemberFlags,\n binder As Binder,\n blockSyntax As AccessorBlockSyntax,\n diagnostics As DiagnosticBag) As SourcePropertyAccessorSymbol\n\n Dim syntax = blockSyntax.BlockStatement\n Dim modifiers = binder.DecodeModifiers(syntax.Modifiers,\n SourceMemberFlags.AllAccessibilityModifiers,\n ERRID.ERR_BadPropertyAccessorFlags,\n Accessibility.NotApplicable,\n diagnostics)\n\n If (modifiers.FoundFlags And SourceMemberFlags.Private) <> 0 Then\n ' Private accessors cannot be overridable.\n propertyFlags = propertyFlags And (Not SourceMemberFlags.Overridable)\n End If\n\n If (modifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then\n Select Case propertySymbol.ContainingType.TypeKind\n Case TypeKind.Structure\n binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_StructCantUseVarSpecifier1, diagnostics, SyntaxKind.ProtectedKeyword)\n modifiers = New MemberModifiers(modifiers.FoundFlags And Not SourceMemberFlags.Protected,\n modifiers.ComputedFlags And Not SourceMemberFlags.AccessibilityMask)\n\n Case TypeKind.Module\n Debug.Assert((SourceMemberFlags.Protected And SourceMemberFlags.InvalidInModule) <> 0)\n binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_BadFlagsOnStdModuleProperty1, diagnostics, SyntaxKind.ProtectedKeyword)\n End Select\n End If\n\n ' Include modifiers from the containing property.\n Dim flags = modifiers.AllFlags Or kindFlags Or propertyFlags\n Dim methodKind = kindFlags.ToMethodKind()\n If methodKind = MethodKind.PropertySet Then\n flags = flags Or SourceMemberFlags.MethodIsSub\n End If\n\n Dim method As New SourcePropertyAccessorSymbol(\n propertySymbol,\n Binder.GetAccessorName(propertySymbol.Name, methodKind, propertySymbol.IsCompilationOutputWinMdObj()),\n flags,\n binder.GetSyntaxReference(syntax),\n ImmutableArray.Create(syntax.DeclarationKeyword.GetLocation()))\n\n Return method\n End Function\n\n Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol\n Get\n Return m_property.GetAccessorOverride(getter:=(MethodKind = MethodKind.PropertyGet))\n End Get\n End Property\n\n Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol)\n Get\n Return OverriddenMembersResult(Of MethodSymbol).Empty\n End Get\n End Property\n\n Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean\n Get\n Return Not Me.m_property.IsCustomProperty OrElse MyBase.IsImplicitlyDeclared\n End Get\n End Property\n\n Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)\n Get\n Return If(Me.m_property.IsCustomProperty, MyBase.DeclaringSyntaxReferences, ImmutableArray(Of SyntaxReference).Empty)\n End Get\n End Property\n\n Public Overrides ReadOnly Property Name As String\n Get\n Return _name\n End Get\n End Property\n\n Public Overrides ReadOnly Property MetadataName As String\n Get\n If _lazyMetadataName Is Nothing Then\n ' VB compiler uses different rules for accessors that other members or the associated properties\n ' (probably a bug, but we have to maintain binary compatibility now). An accessor name is set to match\n ' its overridden method, regardless of what happens to its associated property.\n Dim overriddenMethod = Me.OverriddenMethod\n If overriddenMethod IsNot Nothing Then\n Interlocked.CompareExchange(_lazyMetadataName, overriddenMethod.MetadataName, Nothing)\n Else\n Interlocked.CompareExchange(_lazyMetadataName, _name, Nothing)\n End If\n End If\n\n Return _lazyMetadataName\n End Get\n End Property\n\n Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility\n Get\n Dim accessibility = Me.LocalAccessibility\n If accessibility <> Accessibility.NotApplicable Then\n Return accessibility\n End If\n\n Dim propertyAccessibility = m_property.DeclaredAccessibility\n Debug.Assert(propertyAccessibility <> Accessibility.NotApplicable)\n Return propertyAccessibility\n End Get\n End Property\n\n Public Overrides ReadOnly Property ReturnType As TypeSymbol\n Get\n Dim retType = _lazyReturnType\n If retType Is Nothing Then\n\n Dim diagBag = BindingDiagnosticBag.GetInstance()\n Dim sourceModule = ContainingSourceModule\n Dim errorLocation As SyntaxNodeOrToken = Nothing\n retType = GetReturnType(sourceModule, errorLocation, diagBag)\n\n If Not errorLocation.IsKind(SyntaxKind.None) Then\n Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()\n Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing\n\n retType.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly))\n\n If useSiteDiagnosticsBuilder IsNot Nothing Then\n diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder)\n End If\n\n For Each diag In diagnosticsBuilder\n diagBag.Add(diag.UseSiteInfo, errorLocation.GetLocation())\n Next\n diagnosticsBuilder.Free()\n End If\n\n sourceModule.AtomicStoreReferenceAndDiagnostics(\n _lazyReturnType,\n retType,\n diagBag)\n\n diagBag.Free()\n\n retType = _lazyReturnType\n End If\n\n Return retType\n End Get\n End Property\n\n Private Function GetReturnType(sourceModule As SourceModuleSymbol,\n ByRef errorLocation As SyntaxNodeOrToken,\n diagBag As BindingDiagnosticBag) As TypeSymbol\n Select Case MethodKind\n Case MethodKind.PropertyGet\n Dim accessorSym = DirectCast(Me, SourcePropertyAccessorSymbol)\n Dim prop = DirectCast(accessorSym.AssociatedSymbol, PropertySymbol)\n\n Dim result = prop.Type\n\n Dim overriddenMethod = Me.OverriddenMethod\n If overriddenMethod IsNot Nothing AndAlso overriddenMethod.ReturnType.IsSameTypeIgnoringAll(result) Then\n result = overriddenMethod.ReturnType\n End If\n\n Return result\n\n Case MethodKind.PropertySet\n Debug.Assert(Me.IsSub)\n Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType)\n Return binder.GetSpecialType(SpecialType.System_Void, Me.DeclarationSyntax, diagBag)\n\n Case Else\n Throw ExceptionUtilities.Unreachable()\n End Select\n End Function\n\n Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)\n Get\n Dim params = _lazyParameters\n If params.IsDefault Then\n\n Dim diagBag = BindingDiagnosticBag.GetInstance()\n Dim sourceModule = ContainingSourceModule\n\n params = GetParameters(sourceModule, diagBag)\n\n For Each param In params\n ' TODO: The check for Locations is to rule out cases such as implicit parameters\n ' from property accessors but it allows explicit accessor parameters. Is that correct?\n If param.Locations.Length > 0 Then\n ' Note: Errors are reported on the parameter name. Ideally, we should\n ' match Dev10 and report errors on the parameter type syntax instead.\n param.Type.CheckAllConstraints(param.Locations(0), diagBag, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly))\n End If\n Next\n\n sourceModule.AtomicStoreArrayAndDiagnostics(\n _lazyParameters,\n params,\n diagBag)\n\n diagBag.Free()\n\n params = _lazyParameters\n End If\n\n Return params\n End Get\n End Property\n\n Private Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)\n If m_property.IsCustomProperty Then\n Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType)\n binder = New LocationSpecificBinder(BindingLocation.PropertyAccessorSignature, Me, binder)\n\n Return BindParameters(Me.m_property, Me, Me.Locations.FirstOrDefault, binder, BlockSyntax.BlockStatement.ParameterList, diagBag)\n Else\n ' synthesize parameters for auto-properties and abstract properties\n Return If(MethodKind = MethodKind.PropertyGet,\n SynthesizeAutoGetterParameters(Me, m_property),\n SynthesizeAutoSetterParameters(Me, m_property))\n End If\n End Function\n\n Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)\n Get\n Return ImmutableArray(Of TypeParameterSymbol).Empty\n End Get\n End Property\n\n Public Overrides ReadOnly Property AssociatedSymbol As Symbol\n Get\n Return m_property\n End Get\n End Property\n\n Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean\n Get\n Return m_property.ShadowsExplicitly\n End Get\n End Property '\n\n Friend Overrides Function GetLexicalSortKey() As LexicalSortKey\n Return If(m_property.IsCustomProperty, MyBase.GetLexicalSortKey(), m_property.GetLexicalSortKey())\n End Function\n\n Public Overrides ReadOnly Property IsExtensionMethod As Boolean\n Get\n Return False\n End Get\n End Property\n\n Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean\n Get\n Return False\n End Get\n End Property\n\n Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)\n Get\n If _lazyExplicitImplementations.IsDefault Then\n ImmutableInterlocked.InterlockedCompareExchange(\n _lazyExplicitImplementations,\n m_property.GetAccessorImplementations(getter:=(MethodKind = MethodKind.PropertyGet)),\n Nothing)\n End If\n\n Return _lazyExplicitImplementations\n End Get\n End Property\n\n Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)\n Get\n Dim overriddenMethod = Me.OverriddenMethod\n If overriddenMethod IsNot Nothing Then\n Return overriddenMethod.ReturnTypeCustomModifiers\n End If\n\n Return If(Me.MethodKind = MethodKind.PropertySet, ImmutableArray(Of CustomModifier).Empty, m_property.TypeCustomModifiers)\n End Get\n End Property\n\n Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))\n If m_property.IsCustomProperty Then\n Return OneOrMany.Create(AttributeDeclarationSyntaxList)\n Else\n Return Nothing\n End If\n End Function\n\n Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))\n ' getter return type attributes should be copied from the property return type attributes\n Debug.Assert(Me.MethodKind = MethodKind.PropertySet)\n Return Nothing\n End Function\n\n Protected Overrides ReadOnly Property BoundReturnTypeAttributesSource As SourcePropertySymbol\n Get\n Return If(Me.MethodKind = MethodKind.PropertyGet, m_property, Nothing)\n End Get\n End Property\n\n Friend ReadOnly Property LocalAccessibility As Accessibility\n Get\n Return MyBase.DeclaredAccessibility\n End Get\n End Property\n\n ''' \n ''' Bind parameters declared on the accessor and combine with any\n ''' parameters declared on the property. If there are no explicit parameters\n ''' and this is a setter, create a synthesized value parameter.\n ''' \n Private Shared Function BindParameters(propertySymbol As SourcePropertySymbol,\n method As SourcePropertyAccessorSymbol,\n location As Location,\n binder As Binder,\n parameterListOpt As ParameterListSyntax,\n diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)\n Dim propertyParameters = propertySymbol.Parameters\n Dim nPropertyParameters = propertyParameters.Length\n Dim isSetter As Boolean = (method.MethodKind = MethodKind.PropertySet)\n Dim parameterListSyntax = If(parameterListOpt Is Nothing OrElse Not isSetter, Nothing, parameterListOpt.Parameters)\n Dim synthesizeParameter = isSetter AndAlso (parameterListSyntax.Count = 0)\n Dim nParameters = nPropertyParameters + parameterListSyntax.Count + If(synthesizeParameter, 1, 0)\n Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(nParameters)\n\n propertySymbol.CloneParametersForAccessor(method, parameters)\n\n If parameterListSyntax.Count > 0 Then\n ' Explicit accessor parameters. Bind all parameters (even though at most one\n ' parameter was expected), to ensure all diagnostics are generated and\n ' ensure parameter symbols are available for binding the method body.\n binder.DecodeParameterList(\n method,\n False,\n SourceMemberFlags.None,\n parameterListSyntax,\n parameters,\n s_checkParameterModifierCallback,\n diagnostics)\n\n ' Check for duplicate parameter names across accessor (setter) and property.\n ' It is only necessary to check the one expected setter parameter since we'll report\n ' setter must have one parameter otherwise, and it's not necessary to check for\n ' duplicates if the setter parameter is named 'Value' since we'll report property\n ' cannot contain parameter named 'Value' if there is a duplicate in that case.\n Dim param = parameters(nPropertyParameters)\n If Not IdentifierComparison.Equals(param.Name, StringConstants.ValueParameterName) Then\n Dim paramSyntax = parameterListSyntax(0)\n Binder.CheckParameterNameNotDuplicate(parameters, nPropertyParameters, paramSyntax, param, diagnostics)\n End If\n\n If parameterListSyntax.Count = 1 Then\n ' Verify parameter type matches property type.\n Dim propertyType = propertySymbol.Type\n Dim valueParameter = parameters(parameters.Count - 1)\n Dim valueParameterType = valueParameter.Type\n\n If Not propertyType.IsSameTypeIgnoringAll(valueParameterType) Then\n If (Not propertyType.IsErrorType()) AndAlso (Not valueParameterType.IsErrorType()) Then\n diagnostics.Add(ERRID.ERR_SetValueNotPropertyType, valueParameter.Locations(0))\n End If\n\n Else\n Dim overriddenMethod = method.OverriddenMethod\n If overriddenMethod IsNot Nothing Then\n Dim overriddenParameter = overriddenMethod.Parameters(parameters.Count - 1)\n\n If overriddenParameter.Type.IsSameTypeIgnoringAll(valueParameterType) AndAlso\n CustomModifierUtils.CopyParameterCustomModifiers(overriddenParameter, valueParameter) Then\n parameters(parameters.Count - 1) = valueParameter\n End If\n End If\n End If\n Else\n diagnostics.Add(ERRID.ERR_SetHasOnlyOneParam, location)\n End If\n ElseIf synthesizeParameter Then\n ' No explicit set accessor parameter. Create a synthesized parameter.\n Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter(method, propertySymbol, parameterName:=StringConstants.ValueParameterName)\n parameters.Add(valueParameter)\n End If\n\n Return parameters.ToImmutableAndFree()\n End Function\n\n Private Shared ReadOnly s_checkParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckParameterModifier\n\n Private Shared Function CheckParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags\n If flag <> SourceParameterFlags.ByVal Then\n Dim location = token.GetLocation()\n diagnostics.Add(ERRID.ERR_SetHasToBeByVal1, location, token.ToString())\n Return flag And SourceParameterFlags.ByVal\n End If\n Return SourceParameterFlags.ByVal\n End Function\n\n Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock\n Debug.Assert(Not m_property.IsMustOverride)\n\n If m_property.IsAutoProperty Then\n Return SynthesizedPropertyAccessorHelper.GetBoundMethodBody(Me, m_property.AssociatedField, methodBodyBinder)\n Else\n Return MyBase.GetBoundMethodBody(compilationState, diagnostics, methodBodyBinder)\n End If\n End Function\n\n Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation))\n If arguments.SymbolPart = AttributeLocation.None Then\n If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.DebuggerHiddenAttribute) Then\n arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().IsPropertyAccessorWithDebuggerHiddenAttribute = True\n End If\n End If\n\n MyBase.DecodeWellKnownAttribute(arguments)\n End Sub\n\n Friend ReadOnly Property HasDebuggerHiddenAttribute As Boolean\n Get\n Dim attributeData = GetDecodedWellKnownAttributeData()\n Return attributeData IsNot Nothing AndAlso attributeData.IsPropertyAccessorWithDebuggerHiddenAttribute\n End Get\n End Property\n\n Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))\n MyBase.AddSynthesizedAttributes(compilationState, attributes)\n\n If m_property.IsAutoProperty Then\n Dim compilation = DeclaringCompilation\n\n AddSynthesizedAttribute(attributes,\n compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))\n\n ' Dev11 adds DebuggerNonUserCode; there is no reason to do so since:\n ' - we emit no debug info for the body\n ' - the code doesn't call any user code that could inspect the stack and find the accessor's frame\n ' - the code doesn't throw exceptions whose stack frames we would need to hide\n ' \n ' C# also doesn't add DebuggerHidden nor DebuggerNonUserCode attributes.\n End If\n End Sub\n\n Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean\n Get\n Return Not m_property.IsAutoProperty AndAlso MyBase.GenerateDebugInfoImpl\n End Get\n End Property\n End Class\nEnd Namespace\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\nImports System.Collections.Immutable\nImports System.Threading\nImports Microsoft.CodeAnalysis.PooledObjects\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic.Symbols\n Friend NotInheritable Class SourcePropertyAccessorSymbol\n Inherits SourceMethodSymbol\n\n Protected ReadOnly m_property As SourcePropertySymbol\n Private ReadOnly _name As String\n Private _lazyMetadataName As String\n\n Private _lazyExplicitImplementations As ImmutableArray(Of MethodSymbol) ' lazily populated with explicit implementations\n\n ' Parameters.\n Private _lazyParameters As ImmutableArray(Of ParameterSymbol)\n\n ' Return type. Void for a Sub.\n Private _lazyReturnType As TypeSymbol\n\n Friend Sub New(propertySymbol As SourcePropertySymbol,\n name As String,\n flags As SourceMemberFlags,\n syntaxRef As SyntaxReference,\n locations As ImmutableArray(Of Location))\n\n MyBase.New(\n propertySymbol.ContainingSourceType,\n If(flags.ToMethodKind() = MethodKind.PropertyGet, flags, flags And Not SourceMemberFlags.Iterator),\n syntaxRef,\n locations)\n\n m_property = propertySymbol\n _name = name\n End Sub\n\n Private Shared Function SynthesizeAutoGetterParameters(getter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol)\n If propertySymbol.ParameterCount = 0 Then\n Return ImmutableArray(Of ParameterSymbol).Empty\n End If\n\n Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount)\n propertySymbol.CloneParametersForAccessor(getter, parameters)\n Return parameters.ToImmutableAndFree()\n End Function\n\n Private Shared Function SynthesizeAutoSetterParameters(setter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol)\n Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter(\n setter,\n propertySymbol,\n If(propertySymbol.IsAutoProperty, StringConstants.AutoPropertyValueParameterName, StringConstants.ValueParameterName))\n\n If propertySymbol.ParameterCount = 0 Then\n Return ImmutableArray.Create(valueParameter)\n End If\n\n Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount + 1)\n propertySymbol.CloneParametersForAccessor(setter, parameters)\n parameters.Add(valueParameter)\n Return parameters.ToImmutableAndFree()\n End Function\n\n Friend Shared Function CreatePropertyAccessor(propertySymbol As SourcePropertySymbol,\n kindFlags As SourceMemberFlags,\n propertyFlags As SourceMemberFlags,\n binder As Binder,\n blockSyntax As AccessorBlockSyntax,\n diagnostics As DiagnosticBag) As SourcePropertyAccessorSymbol\n\n Dim syntax = blockSyntax.BlockStatement\n Dim modifiers = binder.DecodeModifiers(syntax.Modifiers,\n SourceMemberFlags.AllAccessibilityModifiers,\n ERRID.ERR_BadPropertyAccessorFlags,\n Accessibility.NotApplicable,\n diagnostics)\n\n If (modifiers.FoundFlags And SourceMemberFlags.Private) <> 0 Then\n ' Private accessors cannot be overridable.\n propertyFlags = propertyFlags And (Not SourceMemberFlags.Overridable)\n End If\n\n If (modifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then\n Select Case propertySymbol.ContainingType.TypeKind\n Case TypeKind.Structure\n binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_StructCantUseVarSpecifier1, diagnostics, SyntaxKind.ProtectedKeyword)\n modifiers = New MemberModifiers(modifiers.FoundFlags And Not SourceMemberFlags.Protected,\n modifiers.ComputedFlags And Not SourceMemberFlags.AccessibilityMask)\n\n Case TypeKind.Module\n Debug.Assert((SourceMemberFlags.Protected And SourceMemberFlags.InvalidInModule) <> 0)\n binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_BadFlagsOnStdModuleProperty1, diagnostics, SyntaxKind.ProtectedKeyword)\n End Select\n End If\n\n ' Include modifiers from the containing property.\n Dim flags = modifiers.AllFlags Or kindFlags Or propertyFlags\n Dim methodKind = kindFlags.ToMethodKind()\n If methodKind = MethodKind.PropertySet Then\n flags = flags Or SourceMemberFlags.MethodIsSub\n End If\n\n Dim method As New SourcePropertyAccessorSymbol(\n propertySymbol,\n Binder.GetAccessorName(propertySymbol.Name, methodKind, propertySymbol.IsCompilationOutputWinMdObj()),\n flags,\n binder.GetSyntaxReference(syntax),\n ImmutableArray.Create(syntax.DeclarationKeyword.GetLocation()))\n\n Return method\n End Function\n\n Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol\n Get\n Return m_property.GetAccessorOverride(getter:=(MethodKind = MethodKind.PropertyGet))\n End Get\n End Property\n\n Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol)\n Get\n Return OverriddenMembersResult(Of MethodSymbol).Empty\n End Get\n End Property\n\n Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean\n Get\n Return Not Me.m_property.IsCustomProperty OrElse MyBase.IsImplicitlyDeclared\n End Get\n End Property\n\n Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)\n Get\n Return If(Me.m_property.IsCustomProperty, MyBase.DeclaringSyntaxReferences, ImmutableArray(Of SyntaxReference).Empty)\n End Get\n End Property\n\n Public Overrides ReadOnly Property Name As String\n Get\n Return _name\n End Get\n End Property\n\n Public Overrides ReadOnly Property MetadataName As String\n Get\n If _lazyMetadataName Is Nothing Then\n ' VB compiler uses different rules for accessors that other members or the associated properties\n ' (probably a bug, but we have to maintain binary compatibility now). An accessor name is set to match\n ' its overridden method, regardless of what happens to its associated property.\n Dim overriddenMethod = Me.OverriddenMethod\n If overriddenMethod IsNot Nothing Then\n Interlocked.CompareExchange(_lazyMetadataName, overriddenMethod.MetadataName, Nothing)\n Else\n Interlocked.CompareExchange(_lazyMetadataName, _name, Nothing)\n End If\n End If\n\n Return _lazyMetadataName\n End Get\n End Property\n\n Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility\n Get\n Dim accessibility = Me.LocalAccessibility\n If accessibility <> Accessibility.NotApplicable Then\n Return accessibility\n End If\n\n Dim propertyAccessibility = m_property.DeclaredAccessibility\n Debug.Assert(propertyAccessibility <> Accessibility.NotApplicable)\n Return propertyAccessibility\n End Get\n End Property\n\n Public Overrides ReadOnly Property ReturnType As TypeSymbol\n Get\n Dim retType = _lazyReturnType\n If retType Is Nothing Then\n\n Dim diagBag = BindingDiagnosticBag.GetInstance()\n Dim sourceModule = ContainingSourceModule\n Dim errorLocation As SyntaxNodeOrToken = Nothing\n retType = GetReturnType(sourceModule, errorLocation, diagBag)\n\n If Not errorLocation.IsKind(SyntaxKind.None) Then\n Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()\n Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing\n\n retType.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly))\n\n If useSiteDiagnosticsBuilder IsNot Nothing Then\n diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder)\n End If\n\n For Each diag In diagnosticsBuilder\n diagBag.Add(diag.UseSiteInfo, errorLocation.GetLocation())\n Next\n diagnosticsBuilder.Free()\n End If\n\n sourceModule.AtomicStoreReferenceAndDiagnostics(\n _lazyReturnType,\n retType,\n diagBag)\n\n diagBag.Free()\n\n retType = _lazyReturnType\n End If\n\n Return retType\n End Get\n End Property\n\n Private Function GetReturnType(sourceModule As SourceModuleSymbol,\n ByRef errorLocation As SyntaxNodeOrToken,\n diagBag As BindingDiagnosticBag) As TypeSymbol\n Select Case MethodKind\n Case MethodKind.PropertyGet\n Dim accessorSym = DirectCast(Me, SourcePropertyAccessorSymbol)\n Dim prop = DirectCast(accessorSym.AssociatedSymbol, PropertySymbol)\n\n Dim result = prop.Type\n\n Dim overriddenMethod = Me.OverriddenMethod\n If overriddenMethod IsNot Nothing AndAlso overriddenMethod.ReturnType.IsSameTypeIgnoringAll(result) Then\n result = overriddenMethod.ReturnType\n End If\n\n Return result\n\n Case MethodKind.PropertySet\n Debug.Assert(Me.IsSub)\n Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType)\n Return binder.GetSpecialType(SpecialType.System_Void, Me.DeclarationSyntax, diagBag)\n\n Case Else\n Throw ExceptionUtilities.Unreachable()\n End Select\n End Function\n\n Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)\n Get\n Dim params = _lazyParameters\n If params.IsDefault Then\n\n Dim diagBag = BindingDiagnosticBag.GetInstance()\n Dim sourceModule = ContainingSourceModule\n\n params = GetParameters(sourceModule, diagBag)\n\n For Each param In params\n ' TODO: The check for Locations is to rule out cases such as implicit parameters\n ' from property accessors but it allows explicit accessor parameters. Is that correct?\n If param.Locations.Length > 0 Then\n ' Note: Errors are reported on the parameter name. Ideally, we should\n ' match Dev10 and report errors on the parameter type syntax instead.\n param.Type.CheckAllConstraints(param.Locations(0), diagBag, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly))\n End If\n Next\n\n sourceModule.AtomicStoreArrayAndDiagnostics(\n _lazyParameters,\n params,\n diagBag)\n\n diagBag.Free()\n\n params = _lazyParameters\n End If\n\n Return params\n End Get\n End Property\n\n Private Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)\n If m_property.IsCustomProperty Then\n Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType)\n binder = New LocationSpecificBinder(BindingLocation.PropertyAccessorSignature, Me, binder)\n\n Return BindParameters(Me.m_property, Me, Me.Locations.FirstOrDefault, binder, BlockSyntax.BlockStatement.ParameterList, diagBag)\n Else\n ' synthesize parameters for auto-properties and abstract properties\n Return If(MethodKind = MethodKind.PropertyGet,\n SynthesizeAutoGetterParameters(Me, m_property),\n SynthesizeAutoSetterParameters(Me, m_property))\n End If\n End Function\n\n Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)\n Get\n Return ImmutableArray(Of TypeParameterSymbol).Empty\n End Get\n End Property\n\n Public Overrides ReadOnly Property AssociatedSymbol As Symbol\n Get\n Return m_property\n End Get\n End Property\n\n Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean\n Get\n Return m_property.ShadowsExplicitly\n End Get\n End Property '\n\n Friend Overrides Function GetLexicalSortKey() As LexicalSortKey\n Return If(m_property.IsCustomProperty, MyBase.GetLexicalSortKey(), m_property.GetLexicalSortKey())\n End Function\n\n Public Overrides ReadOnly Property IsExtensionMethod As Boolean\n Get\n Return False\n End Get\n End Property\n\n Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean\n Get\n Return False\n End Get\n End Property\n\n Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)\n Get\n If _lazyExplicitImplementations.IsDefault Then\n ImmutableInterlocked.InterlockedCompareExchange(\n _lazyExplicitImplementations,\n m_property.GetAccessorImplementations(getter:=(MethodKind = MethodKind.PropertyGet)),\n Nothing)\n End If\n\n Return _lazyExplicitImplementations\n End Get\n End Property\n\n Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)\n Get\n Dim overriddenMethod = Me.OverriddenMethod\n If overriddenMethod IsNot Nothing Then\n Return overriddenMethod.ReturnTypeCustomModifiers\n End If\n\n Return If(Me.MethodKind = MethodKind.PropertySet, ImmutableArray(Of CustomModifier).Empty, m_property.TypeCustomModifiers)\n End Get\n End Property\n\n Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))\n If m_property.IsCustomProperty Then\n Return OneOrMany.Create(AttributeDeclarationSyntaxList)\n Else\n Return Nothing\n End If\n End Function\n\n Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))\n ' getter return type attributes should be copied from the property return type attributes\n Debug.Assert(Me.MethodKind = MethodKind.PropertySet)\n Return Nothing\n End Function\n\n Protected Overrides ReadOnly Property BoundReturnTypeAttributesSource As SourcePropertySymbol\n Get\n Return If(Me.MethodKind = MethodKind.PropertyGet, m_property, Nothing)\n End Get\n End Property\n\n Friend ReadOnly Property LocalAccessibility As Accessibility\n Get\n Return MyBase.DeclaredAccessibility\n End Get\n End Property\n\n ''' \n ''' Bind parameters declared on the accessor and combine with any\n ''' parameters declared on the property. If there are no explicit parameters\n ''' and this is a setter, create a synthesized value parameter.\n ''' \n Private Shared Function BindParameters(propertySymbol As SourcePropertySymbol,\n method As SourcePropertyAccessorSymbol,\n location As Location,\n binder As Binder,\n parameterListOpt As ParameterListSyntax,\n diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)\n Dim propertyParameters = propertySymbol.Parameters\n Dim nPropertyParameters = propertyParameters.Length\n Dim isSetter As Boolean = (method.MethodKind = MethodKind.PropertySet)\n Dim parameterListSyntax = If(parameterListOpt Is Nothing OrElse Not isSetter, Nothing, parameterListOpt.Parameters)\n Dim synthesizeParameter = isSetter AndAlso (parameterListSyntax.Count = 0)\n Dim nParameters = nPropertyParameters + parameterListSyntax.Count + If(synthesizeParameter, 1, 0)\n Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(nParameters)\n\n propertySymbol.CloneParametersForAccessor(method, parameters)\n\n If parameterListSyntax.Count > 0 Then\n ' Explicit accessor parameters. Bind all parameters (even though at most one\n ' parameter was expected), to ensure all diagnostics are generated and\n ' ensure parameter symbols are available for binding the method body.\n binder.DecodeParameterList(\n method,\n False,\n SourceMemberFlags.None,\n parameterListSyntax,\n parameters,\n s_checkParameterModifierCallback,\n diagnostics)\n\n ' Check for duplicate parameter names across accessor (setter) and property.\n ' It is only necessary to check the one expected setter parameter since we'll report\n ' setter must have one parameter otherwise, and it's not necessary to check for\n ' duplicates if the setter parameter is named 'Value' since we'll report property\n ' cannot contain parameter named 'Value' if there is a duplicate in that case.\n Dim param = parameters(nPropertyParameters)\n If Not IdentifierComparison.Equals(param.Name, StringConstants.ValueParameterName) Then\n Dim paramSyntax = parameterListSyntax(0)\n Binder.CheckParameterNameNotDuplicate(parameters, nPropertyParameters, paramSyntax, param, diagnostics)\n End If\n\n If parameterListSyntax.Count = 1 Then\n ' Verify parameter type matches property type.\n Dim propertyType = propertySymbol.Type\n Dim valueParameter = parameters(parameters.Count - 1)\n Dim valueParameterType = valueParameter.Type\n\n If Not propertyType.IsSameTypeIgnoringAll(valueParameterType) Then\n If (Not propertyType.IsErrorType()) AndAlso (Not valueParameterType.IsErrorType()) Then\n diagnostics.Add(ERRID.ERR_SetValueNotPropertyType, valueParameter.Locations(0))\n End If\n\n Else\n Dim overriddenMethod = method.OverriddenMethod\n If overriddenMethod IsNot Nothing Then\n Dim overriddenParameter = overriddenMethod.Parameters(parameters.Count - 1)\n\n If overriddenParameter.Type.IsSameTypeIgnoringAll(valueParameterType) AndAlso\n CustomModifierUtils.CopyParameterCustomModifiers(overriddenParameter, valueParameter) Then\n parameters(parameters.Count - 1) = valueParameter\n End If\n End If\n End If\n Else\n diagnostics.Add(ERRID.ERR_SetHasOnlyOneParam, location)\n End If\n ElseIf synthesizeParameter Then\n ' No explicit set accessor parameter. Create a synthesized parameter.\n Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter(method, propertySymbol, parameterName:=StringConstants.ValueParameterName)\n parameters.Add(valueParameter)\n End If\n\n Return parameters.ToImmutableAndFree()\n End Function\n\n Private Shared ReadOnly s_checkParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckParameterModifier\n\n Private Shared Function CheckParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags\n If flag <> SourceParameterFlags.ByVal Then\n Dim location = token.GetLocation()\n diagnostics.Add(ERRID.ERR_SetHasToBeByVal1, location, token.ToString())\n Return flag And SourceParameterFlags.ByVal\n End If\n Return SourceParameterFlags.ByVal\n End Function\n\n Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock\n Debug.Assert(Not m_property.IsMustOverride)\n\n If m_property.IsAutoProperty Then\n Return SynthesizedPropertyAccessorHelper.GetBoundMethodBody(Me, m_property.AssociatedField, methodBodyBinder)\n Else\n Return MyBase.GetBoundMethodBody(compilationState, diagnostics, methodBodyBinder)\n End If\n End Function\n\n Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation))\n If arguments.SymbolPart = AttributeLocation.None Then\n If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.DebuggerHiddenAttribute) Then\n arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().IsPropertyAccessorWithDebuggerHiddenAttribute = True\n End If\n End If\n\n MyBase.DecodeWellKnownAttribute(arguments)\n End Sub\n\n Friend ReadOnly Property HasDebuggerHiddenAttribute As Boolean\n Get\n Dim attributeData = GetDecodedWellKnownAttributeData()\n Return attributeData IsNot Nothing AndAlso attributeData.IsPropertyAccessorWithDebuggerHiddenAttribute\n End Get\n End Property\n\n Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))\n MyBase.AddSynthesizedAttributes(compilationState, attributes)\n\n If m_property.IsAutoProperty Then\n Dim compilation = DeclaringCompilation\n\n AddSynthesizedAttribute(attributes,\n compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))\n\n ' Dev11 adds DebuggerNonUserCode; there is no reason to do so since:\n ' - we emit no debug info for the body\n ' - the code doesn't call any user code that could inspect the stack and find the accessor's frame\n ' - the code doesn't throw exceptions whose stack frames we would need to hide\n ' \n ' C# also doesn't add DebuggerHidden nor DebuggerNonUserCode attributes.\n End If\n End Sub\n\n Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean\n Get\n Return Not m_property.IsAutoProperty AndAlso MyBase.GenerateDebugInfoImpl\n End Get\n End Property\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":452,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpF1Help.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Microsoft.VisualStudio.IntegrationTest.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Roslyn.VisualStudio.IntegrationTests.CSharp\n{\n [Collection(nameof(SharedIntegrationHostFixture))]\n public class CSharpF1Help : AbstractEditorTest\n {\n protected override string LanguageName => LanguageNames.CSharp;\n\n public CSharpF1Help(VisualStudioInstanceFactory instanceFactory)\n : base(instanceFactory, nameof(CSharpF1Help))\n {\n }\n\n [WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]\n private void F1Help()\n {\n var text = @\"\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\n\nnamespace F1TestNamespace\n{\n #region TaoRegion\n abstract class ShapesClass { }\n\n class Program$$\n {\n public static void Main()\n {\n }\n\n public IEnumerable Linq1()\n {\n int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };\n int i = numbers.First();\n int j = Array.IndexOf(numbers, 1);\n\n var lowNums1 =\n from n in numbers\n orderby n ascending\n where n < 5\n select n;\n\n var numberGroups =\n from n in numbers\n let m = 1\n join p in numbers on i equals p\n group n by n % 5 into g\n select new { Remainder = g.Key, Numbers = g };\n\n foreach (int element in numbers) yield return i;\n }\n\n }\n #endregion TaoRegion\n}\";\n\n SetUpEditor(text);\n Verify(\"abstract\", \"abstract_CSharpKeyword\");\n Verify(\"ascending\", \"ascending_CSharpKeyword\");\n Verify(\"from\", \"from_CSharpKeyword\");\n Verify(\"First();\", \"System.Linq.Enumerable.First``1\");\n }\n\n private void Verify(string word, string expectedKeyword)\n {\n VisualStudio.Editor.PlaceCaret(word, charsOffset: -1);\n Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword());\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Microsoft.VisualStudio.IntegrationTest.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Roslyn.VisualStudio.IntegrationTests.CSharp\n{\n [Collection(nameof(SharedIntegrationHostFixture))]\n public class CSharpF1Help : AbstractEditorTest\n {\n protected override string LanguageName => LanguageNames.CSharp;\n\n public CSharpF1Help(VisualStudioInstanceFactory instanceFactory)\n : base(instanceFactory, nameof(CSharpF1Help))\n {\n }\n\n [WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]\n private void F1Help()\n {\n var text = @\"\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Collections.Generic;\n\nnamespace F1TestNamespace\n{\n #region TaoRegion\n abstract class ShapesClass { }\n\n class Program$$\n {\n public static void Main()\n {\n }\n\n public IEnumerable Linq1()\n {\n int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };\n int i = numbers.First();\n int j = Array.IndexOf(numbers, 1);\n\n var lowNums1 =\n from n in numbers\n orderby n ascending\n where n < 5\n select n;\n\n var numberGroups =\n from n in numbers\n let m = 1\n join p in numbers on i equals p\n group n by n % 5 into g\n select new { Remainder = g.Key, Numbers = g };\n\n foreach (int element in numbers) yield return i;\n }\n\n }\n #endregion TaoRegion\n}\";\n\n SetUpEditor(text);\n Verify(\"abstract\", \"abstract_CSharpKeyword\");\n Verify(\"ascending\", \"ascending_CSharpKeyword\");\n Verify(\"from\", \"from_CSharpKeyword\");\n Verify(\"First();\", \"System.Linq.Enumerable.First``1\");\n }\n\n private void Verify(string word, string expectedKeyword)\n {\n VisualStudio.Editor.PlaceCaret(word, charsOffset: -1);\n Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword());\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":453,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Features/CSharp/Portable/Formatting/CSharpAccessibilityModifiersNewDocumentFormattingProvider.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.AddAccessibilityModifiers;\nusing Microsoft.CodeAnalysis.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.LanguageServices;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\n\nnamespace Microsoft.CodeAnalysis.Formatting\n{\n [ExportNewDocumentFormattingProvider(LanguageNames.CSharp), Shared]\n internal class CSharpAccessibilityModifiersNewDocumentFormattingProvider : INewDocumentFormattingProvider\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public CSharpAccessibilityModifiersNewDocumentFormattingProvider()\n {\n }\n\n public async Task FormatNewDocumentAsync(Document document, Document? hintDocument, CancellationToken cancellationToken)\n {\n var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);\n var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, document.Project.Language);\n if (accessibilityPreferences.Value == AccessibilityModifiersRequired.Never)\n {\n return document;\n }\n\n var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n var syntaxFacts = document.GetRequiredLanguageService();\n var typeDeclarations = root.DescendantNodes().Where(node => syntaxFacts.IsTypeDeclaration(node));\n var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);\n\n var service = document.GetRequiredLanguageService();\n\n foreach (var declaration in typeDeclarations)\n {\n if (!service.ShouldUpdateAccessibilityModifier(CSharpAccessibilityFacts.Instance, declaration, accessibilityPreferences.Value, out _))\n continue;\n\n // Since we format each document as they are added to a project we can't assume we know about all\n // of the files that are coming, so we have to opt out of changing partial classes. This especially\n // manifests when creating new projects as we format before we have a project at all, so we could get a\n // situation like this:\n //\n // File1.cs:\n // partial class C { }\n // File2.cs:\n // public partial class C { }\n //\n // When we see File1, we don't know about File2, so would add an internal modifier, which would result in a compile\n // error.\n var modifiers = syntaxFacts.GetModifiers(declaration);\n CSharpAccessibilityFacts.GetAccessibilityAndModifiers(modifiers, out _, out var declarationModifiers, out _);\n if (declarationModifiers.IsPartial)\n continue;\n\n var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken);\n if (type == null)\n continue;\n\n AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, type, declaration);\n }\n\n return document.WithSyntaxRoot(editor.GetChangedRoot());\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.AddAccessibilityModifiers;\nusing Microsoft.CodeAnalysis.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.LanguageServices;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\n\nnamespace Microsoft.CodeAnalysis.Formatting\n{\n [ExportNewDocumentFormattingProvider(LanguageNames.CSharp), Shared]\n internal class CSharpAccessibilityModifiersNewDocumentFormattingProvider : INewDocumentFormattingProvider\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public CSharpAccessibilityModifiersNewDocumentFormattingProvider()\n {\n }\n\n public async Task FormatNewDocumentAsync(Document document, Document? hintDocument, CancellationToken cancellationToken)\n {\n var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);\n var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, document.Project.Language);\n if (accessibilityPreferences.Value == AccessibilityModifiersRequired.Never)\n {\n return document;\n }\n\n var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n var syntaxFacts = document.GetRequiredLanguageService();\n var typeDeclarations = root.DescendantNodes().Where(node => syntaxFacts.IsTypeDeclaration(node));\n var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);\n\n var service = document.GetRequiredLanguageService();\n\n foreach (var declaration in typeDeclarations)\n {\n if (!service.ShouldUpdateAccessibilityModifier(CSharpAccessibilityFacts.Instance, declaration, accessibilityPreferences.Value, out _))\n continue;\n\n // Since we format each document as they are added to a project we can't assume we know about all\n // of the files that are coming, so we have to opt out of changing partial classes. This especially\n // manifests when creating new projects as we format before we have a project at all, so we could get a\n // situation like this:\n //\n // File1.cs:\n // partial class C { }\n // File2.cs:\n // public partial class C { }\n //\n // When we see File1, we don't know about File2, so would add an internal modifier, which would result in a compile\n // error.\n var modifiers = syntaxFacts.GetModifiers(declaration);\n CSharpAccessibilityFacts.GetAccessibilityAndModifiers(modifiers, out _, out var declarationModifiers, out _);\n if (declarationModifiers.IsPartial)\n continue;\n\n var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken);\n if (type == null)\n continue;\n\n AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, type, declaration);\n }\n\n return document.WithSyntaxRoot(editor.GetChangedRoot());\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":454,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CastExpressionSyntaxExtensions.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Linq;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Simplification;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Extensions\n{\n internal static partial class CastExpressionSyntaxExtensions\n {\n public static ExpressionSyntax Uncast(this CastExpressionSyntax node)\n {\n var leadingTrivia = node.OpenParenToken.LeadingTrivia\n .Concat(node.OpenParenToken.TrailingTrivia)\n .Concat(node.Type.GetLeadingTrivia())\n .Concat(node.Type.GetTrailingTrivia())\n .Concat(node.CloseParenToken.LeadingTrivia)\n .Concat(node.CloseParenToken.TrailingTrivia)\n .Concat(node.Expression.GetLeadingTrivia())\n .Where(t => !t.IsElastic());\n\n var trailingTrivia = node.GetTrailingTrivia().Where(t => !t.IsElastic());\n\n var resultNode = node.Expression\n .WithLeadingTrivia(leadingTrivia)\n .WithTrailingTrivia(trailingTrivia)\n .WithAdditionalAnnotations(Simplifier.Annotation);\n\n resultNode = SimplificationHelpers.CopyAnnotations(from: node, to: resultNode);\n\n return resultNode;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Linq;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Simplification;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Extensions\n{\n internal static partial class CastExpressionSyntaxExtensions\n {\n public static ExpressionSyntax Uncast(this CastExpressionSyntax node)\n {\n var leadingTrivia = node.OpenParenToken.LeadingTrivia\n .Concat(node.OpenParenToken.TrailingTrivia)\n .Concat(node.Type.GetLeadingTrivia())\n .Concat(node.Type.GetTrailingTrivia())\n .Concat(node.CloseParenToken.LeadingTrivia)\n .Concat(node.CloseParenToken.TrailingTrivia)\n .Concat(node.Expression.GetLeadingTrivia())\n .Where(t => !t.IsElastic());\n\n var trailingTrivia = node.GetTrailingTrivia().Where(t => !t.IsElastic());\n\n var resultNode = node.Expression\n .WithLeadingTrivia(leadingTrivia)\n .WithTrailingTrivia(trailingTrivia)\n .WithAdditionalAnnotations(Simplifier.Annotation);\n\n resultNode = SimplificationHelpers.CopyAnnotations(from: node, to: resultNode);\n\n return resultNode;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":455,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.CodeAction.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Linq;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.GenerateDefaultConstructors\n{\n internal abstract partial class AbstractGenerateDefaultConstructorsService\n {\n private class GenerateDefaultConstructorCodeAction : AbstractCodeAction\n {\n public GenerateDefaultConstructorCodeAction(\n Document document,\n State state,\n IMethodSymbol constructor)\n : base(document, state, new[] { constructor }, GetDisplayText(state, constructor))\n {\n }\n\n private static string GetDisplayText(State state, IMethodSymbol constructor)\n {\n var parameters = constructor.Parameters.Select(p => p.Name);\n var parameterString = string.Join(\", \", parameters);\n\n Contract.ThrowIfNull(state.ClassType);\n return string.Format(FeaturesResources.Generate_constructor_0_1,\n state.ClassType.Name, parameterString);\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Linq;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.GenerateDefaultConstructors\n{\n internal abstract partial class AbstractGenerateDefaultConstructorsService\n {\n private class GenerateDefaultConstructorCodeAction : AbstractCodeAction\n {\n public GenerateDefaultConstructorCodeAction(\n Document document,\n State state,\n IMethodSymbol constructor)\n : base(document, state, new[] { constructor }, GetDisplayText(state, constructor))\n {\n }\n\n private static string GetDisplayText(State state, IMethodSymbol constructor)\n {\n var parameters = constructor.Parameters.Select(p => p.Name);\n var parameterString = string.Join(\", \", parameters);\n\n Contract.ThrowIfNull(state.ClassType);\n return string.Format(FeaturesResources.Generate_constructor_0_1,\n state.ClassType.Name, parameterString);\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":456,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayLocalOptions.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Specifies the options for how locals are displayed in the description of a symbol.\n /// \n [Flags]\n public enum SymbolDisplayLocalOptions\n {\n /// \n /// Shows only the name of the local.\n /// For example, \"x\".\n /// \n None = 0,\n\n /// \n /// Shows the type of the local in addition to its name.\n /// For example, \"int x\" in C# or \"x As Integer\" in Visual Basic.\n /// \n IncludeType = 1 << 0,\n\n /// \n /// Shows the constant value of the local, if there is one, in addition to its name.\n /// For example \"x = 1\".\n /// \n IncludeConstantValue = 1 << 1,\n\n /// \n /// Includes the ref keyword for ref-locals.\n /// \n IncludeRef = 1 << 2,\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Specifies the options for how locals are displayed in the description of a symbol.\n /// \n [Flags]\n public enum SymbolDisplayLocalOptions\n {\n /// \n /// Shows only the name of the local.\n /// For example, \"x\".\n /// \n None = 0,\n\n /// \n /// Shows the type of the local in addition to its name.\n /// For example, \"int x\" in C# or \"x As Integer\" in Visual Basic.\n /// \n IncludeType = 1 << 0,\n\n /// \n /// Shows the constant value of the local, if there is one, in addition to its name.\n /// For example \"x = 1\".\n /// \n IncludeConstantValue = 1 << 1,\n\n /// \n /// Includes the ref keyword for ref-locals.\n /// \n IncludeRef = 1 << 2,\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":457,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodePartials.vb"},"before_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\n'-----------------------------------------------------------------------------------------------------------\n' Contains hand-written Partial class extensions to certain of the syntax nodes (other that the \n' base node SyntaxNode, which is in a different file.)\n'-----------------------------------------------------------------------------------------------------------\n\nImports System.Threading\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic.Syntax\n\n Partial Public Class DocumentationCommentTriviaSyntax\n Friend Function GetInteriorXml() As String\n ' NOTE: is only used in parse tests\n Return DirectCast(Me.Green, InternalSyntax.DocumentationCommentTriviaSyntax).GetInteriorXml\n End Function\n End Class\n\n Partial Public Class DirectiveTriviaSyntax\n Private Shared ReadOnly s_hasDirectivesFunction As Func(Of SyntaxToken, Boolean) = Function(n) n.ContainsDirectives\n\n Public Function GetNextDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax\n Dim token = CType(MyBase.ParentTrivia.Token, SyntaxToken)\n\n Dim [next] As Boolean = False\n Do While (token.Kind <> SyntaxKind.None)\n Dim tr As SyntaxTrivia\n For Each tr In token.LeadingTrivia\n If [next] Then\n If tr.IsDirective Then\n Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)\n If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then\n Return d\n End If\n End If\n Continue For\n End If\n If (tr.UnderlyingNode Is MyBase.Green) Then\n [next] = True\n End If\n Next\n token = token.GetNextToken(s_hasDirectivesFunction)\n Loop\n Return Nothing\n End Function\n\n Public Function GetPreviousDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax\n Dim token As SyntaxToken = CType(MyBase.ParentTrivia.Token, SyntaxToken)\n\n Dim [next] As Boolean = False\n Do While (token.Kind <> SyntaxKind.None)\n For Each tr In token.LeadingTrivia.Reverse()\n If [next] Then\n If tr.IsDirective Then\n Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)\n If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then\n Return d\n End If\n End If\n ElseIf (tr.UnderlyingNode Is MyBase.Green) Then\n [next] = True\n End If\n Next\n token = token.GetPreviousToken(s_hasDirectivesFunction)\n Loop\n Return Nothing\n End Function\n End Class\n\n Partial Public Class SingleLineLambdaExpressionSyntax\n ''' \n ''' Single line subs only have a single statement. However, when binding it is convenient to have a statement list. For example,\n ''' dim statements are not valid in a single line lambda. However, it is nice to be able to provide semantic info about the local.\n ''' The only way to create locals is to have a statement list. This method is friend because the statement list should not be part\n ''' of the public api.\n ''' \n Friend ReadOnly Property Statements As SyntaxList(Of StatementSyntax)\n Get\n Debug.Assert(Kind = SyntaxKind.SingleLineSubLambdaExpression, \"Only SingleLineSubLambdas have statements.\")\n Debug.Assert(GetNodeSlot(1) Is Body, \"SingleLineLambdaExpressionSyntax structure has changed. Update index passed to GetChildIndex.\")\n\n Return New SyntaxList(Of StatementSyntax)(Body)\n End Get\n End Property\n End Class\n\n Partial Public Class MethodBaseSyntax\n\n Friend ReadOnly Property AsClauseInternal As AsClauseSyntax\n Get\n Select Case Me.Kind\n Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement\n Return DirectCast(Me, MethodStatementSyntax).AsClause\n\n Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader\n Return DirectCast(Me, LambdaHeaderSyntax).AsClause\n\n Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement\n Return DirectCast(Me, DeclareStatementSyntax).AsClause\n\n Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement\n Return DirectCast(Me, DelegateStatementSyntax).AsClause\n\n Case SyntaxKind.EventStatement\n Return DirectCast(Me, EventStatementSyntax).AsClause\n\n Case SyntaxKind.OperatorStatement\n Return DirectCast(Me, OperatorStatementSyntax).AsClause\n\n Case SyntaxKind.PropertyStatement\n Return DirectCast(Me, PropertyStatementSyntax).AsClause\n\n Case SyntaxKind.SubNewStatement,\n SyntaxKind.GetAccessorStatement,\n SyntaxKind.SetAccessorStatement,\n SyntaxKind.AddHandlerAccessorStatement,\n SyntaxKind.RemoveHandlerAccessorStatement,\n SyntaxKind.RaiseEventAccessorStatement\n Return Nothing\n\n Case Else\n Throw ExceptionUtilities.UnexpectedValue(Me.Kind)\n End Select\n End Get\n End Property\n\n End Class\n\nEnd Namespace\n\n"},"after_content":{"kind":"string","value":"' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses this file to you under the MIT license.\n' See the LICENSE file in the project root for more information.\n\n'-----------------------------------------------------------------------------------------------------------\n' Contains hand-written Partial class extensions to certain of the syntax nodes (other that the \n' base node SyntaxNode, which is in a different file.)\n'-----------------------------------------------------------------------------------------------------------\n\nImports System.Threading\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\n\nNamespace Microsoft.CodeAnalysis.VisualBasic.Syntax\n\n Partial Public Class DocumentationCommentTriviaSyntax\n Friend Function GetInteriorXml() As String\n ' NOTE: is only used in parse tests\n Return DirectCast(Me.Green, InternalSyntax.DocumentationCommentTriviaSyntax).GetInteriorXml\n End Function\n End Class\n\n Partial Public Class DirectiveTriviaSyntax\n Private Shared ReadOnly s_hasDirectivesFunction As Func(Of SyntaxToken, Boolean) = Function(n) n.ContainsDirectives\n\n Public Function GetNextDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax\n Dim token = CType(MyBase.ParentTrivia.Token, SyntaxToken)\n\n Dim [next] As Boolean = False\n Do While (token.Kind <> SyntaxKind.None)\n Dim tr As SyntaxTrivia\n For Each tr In token.LeadingTrivia\n If [next] Then\n If tr.IsDirective Then\n Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)\n If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then\n Return d\n End If\n End If\n Continue For\n End If\n If (tr.UnderlyingNode Is MyBase.Green) Then\n [next] = True\n End If\n Next\n token = token.GetNextToken(s_hasDirectivesFunction)\n Loop\n Return Nothing\n End Function\n\n Public Function GetPreviousDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax\n Dim token As SyntaxToken = CType(MyBase.ParentTrivia.Token, SyntaxToken)\n\n Dim [next] As Boolean = False\n Do While (token.Kind <> SyntaxKind.None)\n For Each tr In token.LeadingTrivia.Reverse()\n If [next] Then\n If tr.IsDirective Then\n Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)\n If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then\n Return d\n End If\n End If\n ElseIf (tr.UnderlyingNode Is MyBase.Green) Then\n [next] = True\n End If\n Next\n token = token.GetPreviousToken(s_hasDirectivesFunction)\n Loop\n Return Nothing\n End Function\n End Class\n\n Partial Public Class SingleLineLambdaExpressionSyntax\n ''' \n ''' Single line subs only have a single statement. However, when binding it is convenient to have a statement list. For example,\n ''' dim statements are not valid in a single line lambda. However, it is nice to be able to provide semantic info about the local.\n ''' The only way to create locals is to have a statement list. This method is friend because the statement list should not be part\n ''' of the public api.\n ''' \n Friend ReadOnly Property Statements As SyntaxList(Of StatementSyntax)\n Get\n Debug.Assert(Kind = SyntaxKind.SingleLineSubLambdaExpression, \"Only SingleLineSubLambdas have statements.\")\n Debug.Assert(GetNodeSlot(1) Is Body, \"SingleLineLambdaExpressionSyntax structure has changed. Update index passed to GetChildIndex.\")\n\n Return New SyntaxList(Of StatementSyntax)(Body)\n End Get\n End Property\n End Class\n\n Partial Public Class MethodBaseSyntax\n\n Friend ReadOnly Property AsClauseInternal As AsClauseSyntax\n Get\n Select Case Me.Kind\n Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement\n Return DirectCast(Me, MethodStatementSyntax).AsClause\n\n Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader\n Return DirectCast(Me, LambdaHeaderSyntax).AsClause\n\n Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement\n Return DirectCast(Me, DeclareStatementSyntax).AsClause\n\n Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement\n Return DirectCast(Me, DelegateStatementSyntax).AsClause\n\n Case SyntaxKind.EventStatement\n Return DirectCast(Me, EventStatementSyntax).AsClause\n\n Case SyntaxKind.OperatorStatement\n Return DirectCast(Me, OperatorStatementSyntax).AsClause\n\n Case SyntaxKind.PropertyStatement\n Return DirectCast(Me, PropertyStatementSyntax).AsClause\n\n Case SyntaxKind.SubNewStatement,\n SyntaxKind.GetAccessorStatement,\n SyntaxKind.SetAccessorStatement,\n SyntaxKind.AddHandlerAccessorStatement,\n SyntaxKind.RemoveHandlerAccessorStatement,\n SyntaxKind.RaiseEventAccessorStatement\n Return Nothing\n\n Case Else\n Throw ExceptionUtilities.UnexpectedValue(Me.Kind)\n End Select\n End Get\n End Property\n\n End Class\n\nEnd Namespace\n\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":458,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiaSymReader/Writer/SymUnmanagedWriterCreationOptions.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\n\nnamespace Microsoft.DiaSymReader\n{\n /// \n /// creation options.\n /// \n [Flags]\n internal enum SymUnmanagedWriterCreationOptions\n {\n /// \n /// Default options.\n /// \n Default = 0,\n\n /// \n /// Use environment variable MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH to locate Microsoft.DiaSymReader.Native.{platform}.dll.\n /// \n UseAlternativeLoadPath = 1 << 1,\n\n /// \n /// Use COM registry to locate an implementation of the writer.\n /// \n UseComRegistry = 1 << 2,\n\n /// \n /// Create a deterministic PDB writer.\n /// \n Deterministic = 1 << 3,\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\n\nnamespace Microsoft.DiaSymReader\n{\n /// \n /// creation options.\n /// \n [Flags]\n internal enum SymUnmanagedWriterCreationOptions\n {\n /// \n /// Default options.\n /// \n Default = 0,\n\n /// \n /// Use environment variable MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH to locate Microsoft.DiaSymReader.Native.{platform}.dll.\n /// \n UseAlternativeLoadPath = 1 << 1,\n\n /// \n /// Use COM registry to locate an implementation of the writer.\n /// \n UseComRegistry = 1 << 2,\n\n /// \n /// Create a deterministic PDB writer.\n /// \n Deterministic = 1 << 3,\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":459,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/Test/Resources/Core/SymbolsTests/ExplicitInterfaceImplementation/CSharpExplicitInterfaceImplementationEvents.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n//csc /target:library\n\nusing System;\n\ninterface Interface\n{\n event Action Event;\n}\n\nclass Class : Interface\n{\n event Action Interface.Event { add { } remove { } }\n}\n\ninterface IGeneric\n{\n event Action Event;\n}\n\nclass Generic : IGeneric\n{\n event Action IGeneric.Event { add { } remove { } }\n}\n\nclass Constructed : IGeneric\n{\n event Action IGeneric.Event { add { } remove { } }\n}\n\ninterface IGenericInterface : Interface\n{\n}\n\n//we'll see a type def for this class, a type ref for IGenericInterface,\n//and then a type def for Interface (i.e. back and forth)\nclass IndirectImplementation : IGenericInterface\n{\n event Action Interface.Event { add { } remove { } }\n}\n\ninterface IGeneric2\n{\n event Action Event;\n}\n\nclass Outer\n{\n public interface IInner\n {\n event Action Event;\n }\n\n public class Inner1 : IGeneric2 //outer interface, inner type param\n {\n event Action IGeneric2.Event { add { } remove { } }\n }\n\n public class Inner2 : IGeneric2 //outer interface, outer type param\n {\n event Action IGeneric2.Event { add { } remove { } }\n }\n\n internal class Inner3 : IInner //inner interface, inner type param\n {\n event Action IInner.Event { add { } remove { } }\n }\n\n protected class Inner4 : IInner //inner interface, outer type param\n {\n event Action IInner.Event { add { } remove { } }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n//csc /target:library\n\nusing System;\n\ninterface Interface\n{\n event Action Event;\n}\n\nclass Class : Interface\n{\n event Action Interface.Event { add { } remove { } }\n}\n\ninterface IGeneric\n{\n event Action Event;\n}\n\nclass Generic : IGeneric\n{\n event Action IGeneric.Event { add { } remove { } }\n}\n\nclass Constructed : IGeneric\n{\n event Action IGeneric.Event { add { } remove { } }\n}\n\ninterface IGenericInterface : Interface\n{\n}\n\n//we'll see a type def for this class, a type ref for IGenericInterface,\n//and then a type def for Interface (i.e. back and forth)\nclass IndirectImplementation : IGenericInterface\n{\n event Action Interface.Event { add { } remove { } }\n}\n\ninterface IGeneric2\n{\n event Action Event;\n}\n\nclass Outer\n{\n public interface IInner\n {\n event Action Event;\n }\n\n public class Inner1 : IGeneric2 //outer interface, inner type param\n {\n event Action IGeneric2.Event { add { } remove { } }\n }\n\n public class Inner2 : IGeneric2 //outer interface, outer type param\n {\n event Action IGeneric2.Event { add { } remove { } }\n }\n\n internal class Inner3 : IInner //inner interface, inner type param\n {\n event Action IInner.Event { add { } remove { } }\n }\n\n protected class Inner4 : IInner //inner interface, outer type param\n {\n event Action IInner.Event { add { } remove { } }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":460,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/EditorFeatures/TestUtilities/EditAndContinue/DeclaratorMapDescription.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests\n{\n public sealed class SyntaxMapDescription\n {\n public readonly ImmutableArray> OldSpans;\n public readonly ImmutableArray> NewSpans;\n\n public SyntaxMapDescription(string oldSource, string newSource)\n {\n OldSpans = GetSpans(oldSource);\n NewSpans = GetSpans(newSource);\n\n Assert.Equal(OldSpans.Length, NewSpans.Length);\n for (var i = 0; i < OldSpans.Length; i++)\n {\n Assert.Equal(OldSpans[i].Length, NewSpans[i].Length);\n }\n }\n\n private static readonly Regex s_statementPattern = new Regex(\n @\"[<]N[:] (?[0-9]+[.][0-9]+) [>]\n (?.*)\n [<][/]N[:] (\\k) [>]\", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n\n internal static ImmutableArray> GetSpans(string src)\n {\n var matches = s_statementPattern.Matches(src);\n var result = new List>();\n\n for (var i = 0; i < matches.Count; i++)\n {\n var stmt = matches[i].Groups[\"Node\"];\n var id = matches[i].Groups[\"Id\"].Value.Split('.');\n var id0 = int.Parse(id[0]);\n var id1 = int.Parse(id[1]);\n\n EnsureSlot(result, id0);\n\n if (result[id0] == null)\n {\n result[id0] = new List();\n }\n\n EnsureSlot(result[id0], id1);\n result[id0][id1] = new TextSpan(stmt.Index, stmt.Length);\n }\n\n return result.Select(r => r.AsImmutableOrEmpty()).AsImmutableOrEmpty();\n }\n\n internal IEnumerable> this[int i]\n {\n get\n {\n for (var j = 0; j < OldSpans[i].Length; j++)\n {\n yield return KeyValuePairUtil.Create(OldSpans[i][j], NewSpans[i][j]);\n }\n }\n }\n\n private static void EnsureSlot(List list, int i)\n {\n while (i >= list.Count)\n {\n list.Add(default);\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests\n{\n public sealed class SyntaxMapDescription\n {\n public readonly ImmutableArray> OldSpans;\n public readonly ImmutableArray> NewSpans;\n\n public SyntaxMapDescription(string oldSource, string newSource)\n {\n OldSpans = GetSpans(oldSource);\n NewSpans = GetSpans(newSource);\n\n Assert.Equal(OldSpans.Length, NewSpans.Length);\n for (var i = 0; i < OldSpans.Length; i++)\n {\n Assert.Equal(OldSpans[i].Length, NewSpans[i].Length);\n }\n }\n\n private static readonly Regex s_statementPattern = new Regex(\n @\"[<]N[:] (?[0-9]+[.][0-9]+) [>]\n (?.*)\n [<][/]N[:] (\\k) [>]\", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n\n internal static ImmutableArray> GetSpans(string src)\n {\n var matches = s_statementPattern.Matches(src);\n var result = new List>();\n\n for (var i = 0; i < matches.Count; i++)\n {\n var stmt = matches[i].Groups[\"Node\"];\n var id = matches[i].Groups[\"Id\"].Value.Split('.');\n var id0 = int.Parse(id[0]);\n var id1 = int.Parse(id[1]);\n\n EnsureSlot(result, id0);\n\n if (result[id0] == null)\n {\n result[id0] = new List();\n }\n\n EnsureSlot(result[id0], id1);\n result[id0][id1] = new TextSpan(stmt.Index, stmt.Length);\n }\n\n return result.Select(r => r.AsImmutableOrEmpty()).AsImmutableOrEmpty();\n }\n\n internal IEnumerable> this[int i]\n {\n get\n {\n for (var j = 0; j < OldSpans[i].Length; j++)\n {\n yield return KeyValuePairUtil.Create(OldSpans[i][j], NewSpans[i][j]);\n }\n }\n }\n\n private static void EnsureSlot(List list, int i)\n {\n while (i >= list.Count)\n {\n list.Add(default);\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":461,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Diagnostics;\nusing Microsoft.CodeAnalysis.ExpressionEvaluator;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;\n\nnamespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator\n{\n [DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]\n internal sealed class CSharpFrameDecoder : FrameDecoder\n {\n public CSharpFrameDecoder()\n : base(CSharpInstructionDecoder.Instance)\n {\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Diagnostics;\nusing Microsoft.CodeAnalysis.ExpressionEvaluator;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;\n\nnamespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator\n{\n [DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]\n internal sealed class CSharpFrameDecoder : FrameDecoder\n {\n public CSharpFrameDecoder()\n : base(CSharpInstructionDecoder.Instance)\n {\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":462,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptDiagnosticAnalyzerLanguageService.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;\n\nnamespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript\n{\n [Shared]\n [ExportLanguageService(typeof(VSTypeScriptDiagnosticAnalyzerLanguageService), InternalLanguageNames.TypeScript)]\n internal sealed class VSTypeScriptDiagnosticAnalyzerLanguageService : ILanguageService\n {\n internal readonly IVSTypeScriptDiagnosticAnalyzerImplementation? Implementation;\n\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public VSTypeScriptDiagnosticAnalyzerLanguageService(\n [Import(AllowDefault = true)] IVSTypeScriptDiagnosticAnalyzerImplementation? implementation = null)\n {\n Implementation = implementation;\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;\n\nnamespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript\n{\n [Shared]\n [ExportLanguageService(typeof(VSTypeScriptDiagnosticAnalyzerLanguageService), InternalLanguageNames.TypeScript)]\n internal sealed class VSTypeScriptDiagnosticAnalyzerLanguageService : ILanguageService\n {\n internal readonly IVSTypeScriptDiagnosticAnalyzerImplementation? Implementation;\n\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public VSTypeScriptDiagnosticAnalyzerLanguageService(\n [Import(AllowDefault = true)] IVSTypeScriptDiagnosticAnalyzerImplementation? implementation = null)\n {\n Implementation = implementation;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":463,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/Parser/SyntaxParser.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax\n{\n using Microsoft.CodeAnalysis.Syntax.InternalSyntax;\n\n internal abstract partial class SyntaxParser : IDisposable\n {\n protected readonly Lexer lexer;\n private readonly bool _isIncremental;\n private readonly bool _allowModeReset;\n protected readonly CancellationToken cancellationToken;\n\n private LexerMode _mode;\n private Blender _firstBlender;\n private BlendedNode _currentNode;\n private SyntaxToken _currentToken;\n private ArrayElement[] _lexedTokens;\n private GreenNode _prevTokenTrailingTrivia;\n private int _firstToken; // The position of _lexedTokens[0] (or _blendedTokens[0]).\n private int _tokenOffset; // The index of the current token within _lexedTokens or _blendedTokens.\n private int _tokenCount;\n private int _resetCount;\n private int _resetStart;\n\n private static readonly ObjectPool s_blendedNodesPool = new ObjectPool(() => new BlendedNode[32], 2);\n\n private BlendedNode[] _blendedTokens;\n\n protected SyntaxParser(\n Lexer lexer,\n LexerMode mode,\n CSharp.CSharpSyntaxNode oldTree,\n IEnumerable changes,\n bool allowModeReset,\n bool preLexIfNotIncremental = false,\n CancellationToken cancellationToken = default(CancellationToken))\n {\n this.lexer = lexer;\n _mode = mode;\n _allowModeReset = allowModeReset;\n this.cancellationToken = cancellationToken;\n _currentNode = default(BlendedNode);\n _isIncremental = oldTree != null;\n\n if (this.IsIncremental || allowModeReset)\n {\n _firstBlender = new Blender(lexer, oldTree, changes);\n _blendedTokens = s_blendedNodesPool.Allocate();\n }\n else\n {\n _firstBlender = default(Blender);\n _lexedTokens = new ArrayElement[32];\n }\n\n // PreLex is not cancellable. \n // If we may cancel why would we aggressively lex ahead?\n // Cancellations in a constructor make disposing complicated\n //\n // So, if we have a real cancellation token, do not do prelexing.\n if (preLexIfNotIncremental && !this.IsIncremental && !cancellationToken.CanBeCanceled)\n {\n this.PreLex();\n }\n }\n\n public void Dispose()\n {\n var blendedTokens = _blendedTokens;\n if (blendedTokens != null)\n {\n _blendedTokens = null;\n if (blendedTokens.Length < 4096)\n {\n Array.Clear(blendedTokens, 0, blendedTokens.Length);\n s_blendedNodesPool.Free(blendedTokens);\n }\n else\n {\n s_blendedNodesPool.ForgetTrackedObject(blendedTokens);\n }\n }\n }\n\n protected void ReInitialize()\n {\n _firstToken = 0;\n _tokenOffset = 0;\n _tokenCount = 0;\n _resetCount = 0;\n _resetStart = 0;\n _currentToken = null;\n _prevTokenTrailingTrivia = null;\n if (this.IsIncremental || _allowModeReset)\n {\n _firstBlender = new Blender(this.lexer, null, null);\n }\n }\n\n protected bool IsIncremental\n {\n get\n {\n return _isIncremental;\n }\n }\n\n private void PreLex()\n {\n // NOTE: Do not cancel in this method. It is called from the constructor.\n var size = Math.Min(4096, Math.Max(32, this.lexer.TextWindow.Text.Length / 2));\n _lexedTokens = new ArrayElement[size];\n var lexer = this.lexer;\n var mode = _mode;\n\n for (int i = 0; i < size; i++)\n {\n var token = lexer.Lex(mode);\n this.AddLexedToken(token);\n if (token.Kind == SyntaxKind.EndOfFileToken)\n {\n break;\n }\n }\n }\n\n protected ResetPoint GetResetPoint()\n {\n var pos = CurrentTokenPosition;\n if (_resetCount == 0)\n {\n _resetStart = pos; // low water mark\n }\n\n _resetCount++;\n return new ResetPoint(_resetCount, _mode, pos, _prevTokenTrailingTrivia);\n }\n\n protected void Reset(ref ResetPoint point)\n {\n var offset = point.Position - _firstToken;\n Debug.Assert(offset >= 0);\n\n if (offset >= _tokenCount)\n {\n // Re-fetch tokens to the position in the reset point\n PeekToken(offset - _tokenOffset);\n\n // Re-calculate new offset in case tokens got shifted to the left while we were peeking. \n offset = point.Position - _firstToken;\n }\n\n _mode = point.Mode;\n Debug.Assert(offset >= 0 && offset < _tokenCount);\n _tokenOffset = offset;\n _currentToken = null;\n _currentNode = default(BlendedNode);\n _prevTokenTrailingTrivia = point.PrevTokenTrailingTrivia;\n if (_blendedTokens != null)\n {\n // look forward for slots not holding a token\n for (int i = _tokenOffset; i < _tokenCount; i++)\n {\n if (_blendedTokens[i].Token == null)\n {\n // forget anything after and including any slot not holding a token\n _tokenCount = i;\n if (_tokenCount == _tokenOffset)\n {\n FetchCurrentToken();\n }\n break;\n }\n }\n }\n }\n\n protected void Release(ref ResetPoint point)\n {\n Debug.Assert(_resetCount == point.ResetCount);\n _resetCount--;\n if (_resetCount == 0)\n {\n _resetStart = -1;\n }\n }\n\n public CSharpParseOptions Options\n {\n get { return this.lexer.Options; }\n }\n\n public bool IsScript\n {\n get { return Options.Kind == SourceCodeKind.Script; }\n }\n\n protected LexerMode Mode\n {\n get\n {\n return _mode;\n }\n\n set\n {\n if (_mode != value)\n {\n Debug.Assert(_allowModeReset);\n\n _mode = value;\n _currentToken = null;\n _currentNode = default(BlendedNode);\n _tokenCount = _tokenOffset;\n }\n }\n }\n\n protected CSharp.CSharpSyntaxNode CurrentNode\n {\n get\n {\n // we will fail anyways. Assert is just to catch that earlier.\n Debug.Assert(_blendedTokens != null);\n\n //PERF: currentNode is a BlendedNode, which is a fairly large struct.\n // the following code tries not to pull the whole struct into a local\n // we only need .Node\n var node = _currentNode.Node;\n if (node != null)\n {\n return node;\n }\n\n this.ReadCurrentNode();\n return _currentNode.Node;\n }\n }\n\n protected SyntaxKind CurrentNodeKind\n {\n get\n {\n var cn = this.CurrentNode;\n return cn != null ? cn.Kind() : SyntaxKind.None;\n }\n }\n\n private void ReadCurrentNode()\n {\n if (_tokenOffset == 0)\n {\n _currentNode = _firstBlender.ReadNode(_mode);\n }\n else\n {\n _currentNode = _blendedTokens[_tokenOffset - 1].Blender.ReadNode(_mode);\n }\n }\n\n protected GreenNode EatNode()\n {\n // we will fail anyways. Assert is just to catch that earlier.\n Debug.Assert(_blendedTokens != null);\n\n // remember result\n var result = CurrentNode.Green;\n\n // store possible non-token in token sequence \n if (_tokenOffset >= _blendedTokens.Length)\n {\n this.AddTokenSlot();\n }\n\n _blendedTokens[_tokenOffset++] = _currentNode;\n _tokenCount = _tokenOffset; // forget anything after this slot\n\n // erase current state\n _currentNode = default(BlendedNode);\n _currentToken = null;\n\n return result;\n }\n\n protected SyntaxToken CurrentToken\n {\n get\n {\n return _currentToken ?? (_currentToken = this.FetchCurrentToken());\n }\n }\n\n private SyntaxToken FetchCurrentToken()\n {\n if (_tokenOffset >= _tokenCount)\n {\n this.AddNewToken();\n }\n\n if (_blendedTokens != null)\n {\n return _blendedTokens[_tokenOffset].Token;\n }\n else\n {\n return _lexedTokens[_tokenOffset];\n }\n }\n\n private void AddNewToken()\n {\n if (_blendedTokens != null)\n {\n if (_tokenCount > 0)\n {\n this.AddToken(_blendedTokens[_tokenCount - 1].Blender.ReadToken(_mode));\n }\n else\n {\n if (_currentNode.Token != null)\n {\n this.AddToken(_currentNode);\n }\n else\n {\n this.AddToken(_firstBlender.ReadToken(_mode));\n }\n }\n }\n else\n {\n this.AddLexedToken(this.lexer.Lex(_mode));\n }\n }\n\n // adds token to end of current token array\n private void AddToken(in BlendedNode tokenResult)\n {\n Debug.Assert(tokenResult.Token != null);\n if (_tokenCount >= _blendedTokens.Length)\n {\n this.AddTokenSlot();\n }\n\n _blendedTokens[_tokenCount] = tokenResult;\n _tokenCount++;\n }\n\n private void AddLexedToken(SyntaxToken token)\n {\n Debug.Assert(token != null);\n if (_tokenCount >= _lexedTokens.Length)\n {\n this.AddLexedTokenSlot();\n }\n\n _lexedTokens[_tokenCount].Value = token;\n _tokenCount++;\n }\n\n private void AddTokenSlot()\n {\n // shift tokens to left if we are far to the right\n // don't shift if reset points have fixed locked the starting point at the token in the window\n if (_tokenOffset > (_blendedTokens.Length >> 1)\n && (_resetStart == -1 || _resetStart > _firstToken))\n {\n int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;\n int shiftCount = _tokenCount - shiftOffset;\n Debug.Assert(shiftOffset > 0);\n _firstBlender = _blendedTokens[shiftOffset - 1].Blender;\n if (shiftCount > 0)\n {\n Array.Copy(_blendedTokens, shiftOffset, _blendedTokens, 0, shiftCount);\n }\n\n _firstToken += shiftOffset;\n _tokenCount -= shiftOffset;\n _tokenOffset -= shiftOffset;\n }\n else\n {\n var old = _blendedTokens;\n Array.Resize(ref _blendedTokens, _blendedTokens.Length * 2);\n s_blendedNodesPool.ForgetTrackedObject(old, replacement: _blendedTokens);\n }\n }\n\n private void AddLexedTokenSlot()\n {\n // shift tokens to left if we are far to the right\n // don't shift if reset points have fixed locked the starting point at the token in the window\n if (_tokenOffset > (_lexedTokens.Length >> 1)\n && (_resetStart == -1 || _resetStart > _firstToken))\n {\n int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;\n int shiftCount = _tokenCount - shiftOffset;\n Debug.Assert(shiftOffset > 0);\n if (shiftCount > 0)\n {\n Array.Copy(_lexedTokens, shiftOffset, _lexedTokens, 0, shiftCount);\n }\n\n _firstToken += shiftOffset;\n _tokenCount -= shiftOffset;\n _tokenOffset -= shiftOffset;\n }\n else\n {\n var tmp = new ArrayElement[_lexedTokens.Length * 2];\n Array.Copy(_lexedTokens, tmp, _lexedTokens.Length);\n _lexedTokens = tmp;\n }\n }\n\n protected SyntaxToken PeekToken(int n)\n {\n Debug.Assert(n >= 0);\n while (_tokenOffset + n >= _tokenCount)\n {\n this.AddNewToken();\n }\n\n if (_blendedTokens != null)\n {\n return _blendedTokens[_tokenOffset + n].Token;\n }\n else\n {\n return _lexedTokens[_tokenOffset + n];\n }\n }\n\n //this method is called very frequently\n //we should keep it simple so that it can be inlined.\n protected SyntaxToken EatToken()\n {\n var ct = this.CurrentToken;\n MoveToNextToken();\n return ct;\n }\n\n /// \n /// Returns and consumes the current token if it has the requested .\n /// Otherwise, returns .\n /// \n protected SyntaxToken TryEatToken(SyntaxKind kind)\n => this.CurrentToken.Kind == kind ? this.EatToken() : null;\n\n private void MoveToNextToken()\n {\n _prevTokenTrailingTrivia = _currentToken.GetTrailingTrivia();\n\n _currentToken = null;\n\n if (_blendedTokens != null)\n {\n _currentNode = default(BlendedNode);\n }\n\n _tokenOffset++;\n }\n\n protected void ForceEndOfFile()\n {\n _currentToken = SyntaxFactory.Token(SyntaxKind.EndOfFileToken);\n }\n\n //this method is called very frequently\n //we should keep it simple so that it can be inlined.\n protected SyntaxToken EatToken(SyntaxKind kind)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n\n var ct = this.CurrentToken;\n if (ct.Kind == kind)\n {\n MoveToNextToken();\n return ct;\n }\n\n //slow part of EatToken(SyntaxKind kind)\n return CreateMissingToken(kind, this.CurrentToken.Kind, reportError: true);\n }\n\n // Consume a token if it is the right kind. Otherwise skip a token and replace it with one of the correct kind.\n protected SyntaxToken EatTokenAsKind(SyntaxKind expected)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(expected));\n\n var ct = this.CurrentToken;\n if (ct.Kind == expected)\n {\n MoveToNextToken();\n return ct;\n }\n\n var replacement = CreateMissingToken(expected, this.CurrentToken.Kind, reportError: true);\n return AddTrailingSkippedSyntax(replacement, this.EatToken());\n }\n\n private SyntaxToken CreateMissingToken(SyntaxKind expected, SyntaxKind actual, bool reportError)\n {\n // should we eat the current ParseToken's leading trivia?\n var token = SyntaxFactory.MissingToken(expected);\n if (reportError)\n {\n token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(expected, actual));\n }\n\n return token;\n }\n\n private SyntaxToken CreateMissingToken(SyntaxKind expected, ErrorCode code, bool reportError)\n {\n // should we eat the current ParseToken's leading trivia?\n var token = SyntaxFactory.MissingToken(expected);\n if (reportError)\n {\n token = AddError(token, code);\n }\n\n return token;\n }\n\n protected SyntaxToken EatToken(SyntaxKind kind, bool reportError)\n {\n if (reportError)\n {\n return EatToken(kind);\n }\n\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n if (this.CurrentToken.Kind != kind)\n {\n // should we eat the current ParseToken's leading trivia?\n return SyntaxFactory.MissingToken(kind);\n }\n else\n {\n return this.EatToken();\n }\n }\n\n protected SyntaxToken EatToken(SyntaxKind kind, ErrorCode code, bool reportError = true)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n if (this.CurrentToken.Kind != kind)\n {\n return CreateMissingToken(kind, code, reportError);\n }\n else\n {\n return this.EatToken();\n }\n }\n\n protected SyntaxToken EatTokenWithPrejudice(SyntaxKind kind)\n {\n var token = this.CurrentToken;\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n if (token.Kind != kind)\n {\n token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(kind, token.Kind));\n }\n\n this.MoveToNextToken();\n return token;\n }\n\n protected SyntaxToken EatTokenWithPrejudice(ErrorCode errorCode, params object[] args)\n {\n var token = this.EatToken();\n token = WithAdditionalDiagnostics(token, MakeError(token.GetLeadingTriviaWidth(), token.Width, errorCode, args));\n return token;\n }\n\n protected SyntaxToken EatContextualToken(SyntaxKind kind, ErrorCode code, bool reportError = true)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n\n if (this.CurrentToken.ContextualKind != kind)\n {\n return CreateMissingToken(kind, code, reportError);\n }\n else\n {\n return ConvertToKeyword(this.EatToken());\n }\n }\n\n protected SyntaxToken EatContextualToken(SyntaxKind kind, bool reportError = true)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n\n var contextualKind = this.CurrentToken.ContextualKind;\n if (contextualKind != kind)\n {\n return CreateMissingToken(kind, contextualKind, reportError);\n }\n else\n {\n return ConvertToKeyword(this.EatToken());\n }\n }\n\n protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int width)\n {\n var code = GetExpectedTokenErrorCode(expected, actual);\n if (code == ErrorCode.ERR_SyntaxError || code == ErrorCode.ERR_IdentifierExpectedKW)\n {\n return new SyntaxDiagnosticInfo(offset, width, code, SyntaxFacts.GetText(expected), SyntaxFacts.GetText(actual));\n }\n else\n {\n return new SyntaxDiagnosticInfo(offset, width, code);\n }\n }\n\n protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual)\n {\n int offset, width;\n this.GetDiagnosticSpanForMissingToken(out offset, out width);\n\n return this.GetExpectedTokenError(expected, actual, offset, width);\n }\n\n private static ErrorCode GetExpectedTokenErrorCode(SyntaxKind expected, SyntaxKind actual)\n {\n switch (expected)\n {\n case SyntaxKind.IdentifierToken:\n if (SyntaxFacts.IsReservedKeyword(actual))\n {\n return ErrorCode.ERR_IdentifierExpectedKW; // A keyword -- use special message.\n }\n else\n {\n return ErrorCode.ERR_IdentifierExpected;\n }\n\n case SyntaxKind.SemicolonToken:\n return ErrorCode.ERR_SemicolonExpected;\n\n // case TokenKind::Colon: iError = ERR_ColonExpected; break;\n // case TokenKind::OpenParen: iError = ERR_LparenExpected; break;\n case SyntaxKind.CloseParenToken:\n return ErrorCode.ERR_CloseParenExpected;\n case SyntaxKind.OpenBraceToken:\n return ErrorCode.ERR_LbraceExpected;\n case SyntaxKind.CloseBraceToken:\n return ErrorCode.ERR_RbraceExpected;\n\n // case TokenKind::CloseSquare: iError = ERR_CloseSquareExpected; break;\n default:\n return ErrorCode.ERR_SyntaxError;\n }\n }\n\n protected void GetDiagnosticSpanForMissingToken(out int offset, out int width)\n {\n // If the previous token has a trailing EndOfLineTrivia,\n // the missing token diagnostic position is moved to the\n // end of line containing the previous token and\n // its width is set to zero.\n // Otherwise the diagnostic offset and width is set\n // to the corresponding values of the current token\n\n var trivia = _prevTokenTrailingTrivia;\n if (trivia != null)\n {\n SyntaxList triviaList = new SyntaxList(trivia);\n bool prevTokenHasEndOfLineTrivia = triviaList.Any((int)SyntaxKind.EndOfLineTrivia);\n if (prevTokenHasEndOfLineTrivia)\n {\n offset = -trivia.FullWidth;\n width = 0;\n return;\n }\n }\n\n SyntaxToken ct = this.CurrentToken;\n offset = ct.GetLeadingTriviaWidth();\n width = ct.Width;\n }\n\n protected virtual TNode WithAdditionalDiagnostics(TNode node, params DiagnosticInfo[] diagnostics) where TNode : GreenNode\n {\n DiagnosticInfo[] existingDiags = node.GetDiagnostics();\n int existingLength = existingDiags.Length;\n if (existingLength == 0)\n {\n return node.WithDiagnosticsGreen(diagnostics);\n }\n else\n {\n DiagnosticInfo[] result = new DiagnosticInfo[existingDiags.Length + diagnostics.Length];\n existingDiags.CopyTo(result, 0);\n diagnostics.CopyTo(result, existingLength);\n return node.WithDiagnosticsGreen(result);\n }\n }\n\n protected TNode AddError(TNode node, ErrorCode code) where TNode : GreenNode\n {\n return AddError(node, code, Array.Empty());\n }\n\n protected TNode AddError(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode\n {\n if (!node.IsMissing)\n {\n return WithAdditionalDiagnostics(node, MakeError(node, code, args));\n }\n\n int offset, width;\n\n SyntaxToken token = node as SyntaxToken;\n if (token != null && token.ContainsSkippedText)\n {\n // This code exists to clean up an anti-pattern:\n // 1) an undesirable token is parsed,\n // 2) a desirable missing token is created and the parsed token is appended as skipped text,\n // 3) an error is attached to the missing token describing the problem.\n // If this occurs, then this.previousTokenTrailingTrivia is still populated with the trivia \n // of the undesirable token (now skipped text). Since the trivia no longer precedes the\n // node to which the error is to be attached, the computed offset will be incorrect.\n\n offset = token.GetLeadingTriviaWidth(); // Should always be zero, but at least we'll do something sensible if it's not.\n Debug.Assert(offset == 0, \"Why are we producing a missing token that has both skipped text and leading trivia?\");\n\n width = 0;\n bool seenSkipped = false;\n foreach (var trivia in token.TrailingTrivia)\n {\n if (trivia.Kind == SyntaxKind.SkippedTokensTrivia)\n {\n seenSkipped = true;\n width += trivia.Width;\n }\n else if (seenSkipped)\n {\n break;\n }\n else\n {\n offset += trivia.Width;\n }\n }\n }\n else\n {\n this.GetDiagnosticSpanForMissingToken(out offset, out width);\n }\n\n return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));\n }\n\n protected TNode AddError(TNode node, int offset, int length, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n return WithAdditionalDiagnostics(node, MakeError(offset, length, code, args));\n }\n\n protected TNode AddError(TNode node, CSharpSyntaxNode location, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n // assumes non-terminals will at most appear once in sub-tree\n int offset;\n FindOffset(node, location, out offset);\n return WithAdditionalDiagnostics(node, MakeError(offset, location.Width, code, args));\n }\n\n protected TNode AddErrorToFirstToken(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode\n {\n var firstToken = node.GetFirstToken();\n return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code));\n }\n\n protected TNode AddErrorToFirstToken(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n var firstToken = node.GetFirstToken();\n return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code, args));\n }\n\n protected TNode AddErrorToLastToken(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode\n {\n int offset;\n int width;\n GetOffsetAndWidthForLastToken(node, out offset, out width);\n return WithAdditionalDiagnostics(node, MakeError(offset, width, code));\n }\n\n protected TNode AddErrorToLastToken(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n int offset;\n int width;\n GetOffsetAndWidthForLastToken(node, out offset, out width);\n return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));\n }\n\n private static void GetOffsetAndWidthForLastToken(TNode node, out int offset, out int width) where TNode : CSharpSyntaxNode\n {\n var lastToken = node.GetLastNonmissingToken();\n offset = node.FullWidth; //advance to end of entire node\n width = 0;\n if (lastToken != null) //will be null if all tokens are missing\n {\n offset -= lastToken.FullWidth; //rewind past last token\n offset += lastToken.GetLeadingTriviaWidth(); //advance past last token leading trivia - now at start of last token\n width += lastToken.Width;\n }\n }\n\n protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code)\n {\n return new SyntaxDiagnosticInfo(offset, width, code);\n }\n\n protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code, params object[] args)\n {\n return new SyntaxDiagnosticInfo(offset, width, code, args);\n }\n\n protected static SyntaxDiagnosticInfo MakeError(GreenNode node, ErrorCode code, params object[] args)\n {\n return new SyntaxDiagnosticInfo(node.GetLeadingTriviaWidth(), node.Width, code, args);\n }\n\n protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args)\n {\n return new SyntaxDiagnosticInfo(code, args);\n }\n\n protected TNode AddLeadingSkippedSyntax(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode\n {\n var oldToken = node as SyntaxToken ?? node.GetFirstToken();\n var newToken = AddSkippedSyntax(oldToken, skippedSyntax, trailing: false);\n return SyntaxFirstTokenReplacer.Replace(node, oldToken, newToken, skippedSyntax.FullWidth);\n }\n\n protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax)\n {\n list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], skippedSyntax);\n }\n\n protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode\n {\n list[list.Count - 1] = AddTrailingSkippedSyntax(list[list.Count - 1], skippedSyntax);\n }\n\n protected TNode AddTrailingSkippedSyntax(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode\n {\n var token = node as SyntaxToken;\n if (token != null)\n {\n return (TNode)(object)AddSkippedSyntax(token, skippedSyntax, trailing: true);\n }\n else\n {\n var lastToken = node.GetLastToken();\n var newToken = AddSkippedSyntax(lastToken, skippedSyntax, trailing: true);\n return SyntaxLastTokenReplacer.Replace(node, newToken);\n }\n }\n\n /// \n /// Converts skippedSyntax node into tokens and adds these as trivia on the target token.\n /// Also adds the first error (in depth-first preorder) found in the skipped syntax tree to the target token.\n /// \n internal SyntaxToken AddSkippedSyntax(SyntaxToken target, GreenNode skippedSyntax, bool trailing)\n {\n var builder = new SyntaxListBuilder(4);\n\n // the error in we'll attach to the node\n SyntaxDiagnosticInfo diagnostic = null;\n\n // the position of the error within the skippedSyntax node full tree\n int diagnosticOffset = 0;\n\n int currentOffset = 0;\n foreach (var node in skippedSyntax.EnumerateNodes())\n {\n SyntaxToken token = node as SyntaxToken;\n if (token != null)\n {\n builder.Add(token.GetLeadingTrivia());\n\n if (token.Width > 0)\n {\n // separate trivia from the tokens\n SyntaxToken tk = token.TokenWithLeadingTrivia(null).TokenWithTrailingTrivia(null);\n\n // adjust relative offsets of diagnostics attached to the token:\n int leadingWidth = token.GetLeadingTriviaWidth();\n if (leadingWidth > 0)\n {\n var tokenDiagnostics = tk.GetDiagnostics();\n for (int i = 0; i < tokenDiagnostics.Length; i++)\n {\n var d = (SyntaxDiagnosticInfo)tokenDiagnostics[i];\n tokenDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset - leadingWidth, d.Width, (ErrorCode)d.Code, d.Arguments);\n }\n }\n\n builder.Add(SyntaxFactory.SkippedTokensTrivia(tk));\n }\n else\n {\n // do not create zero-width structured trivia, GetStructure doesn't work well for them\n var existing = (SyntaxDiagnosticInfo)token.GetDiagnostics().FirstOrDefault();\n if (existing != null)\n {\n diagnostic = existing;\n diagnosticOffset = currentOffset;\n }\n }\n builder.Add(token.GetTrailingTrivia());\n\n currentOffset += token.FullWidth;\n }\n else if (node.ContainsDiagnostics && diagnostic == null)\n {\n // only propagate the first error to reduce noise:\n var existing = (SyntaxDiagnosticInfo)node.GetDiagnostics().FirstOrDefault();\n if (existing != null)\n {\n diagnostic = existing;\n diagnosticOffset = currentOffset;\n }\n }\n }\n\n int triviaWidth = currentOffset;\n var trivia = builder.ToListNode();\n\n // total width of everything preceding the added trivia\n int triviaOffset;\n if (trailing)\n {\n var trailingTrivia = target.GetTrailingTrivia();\n triviaOffset = target.FullWidth; //added trivia is full width (before addition)\n target = target.TokenWithTrailingTrivia(SyntaxList.Concat(trailingTrivia, trivia));\n }\n else\n {\n // Since we're adding triviaWidth before the token, we have to add that much to\n // the offset of each of its diagnostics.\n if (triviaWidth > 0)\n {\n var targetDiagnostics = target.GetDiagnostics();\n for (int i = 0; i < targetDiagnostics.Length; i++)\n {\n var d = (SyntaxDiagnosticInfo)targetDiagnostics[i];\n targetDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset + triviaWidth, d.Width, (ErrorCode)d.Code, d.Arguments);\n }\n }\n\n var leadingTrivia = target.GetLeadingTrivia();\n target = target.TokenWithLeadingTrivia(SyntaxList.Concat(trivia, leadingTrivia));\n triviaOffset = 0; //added trivia is first, so offset is zero\n }\n\n if (diagnostic != null)\n {\n int newOffset = triviaOffset + diagnosticOffset + diagnostic.Offset;\n\n target = WithAdditionalDiagnostics(target,\n new SyntaxDiagnosticInfo(newOffset, diagnostic.Width, (ErrorCode)diagnostic.Code, diagnostic.Arguments)\n );\n }\n\n return target;\n }\n\n /// \n /// This function searches for the given location node within the subtree rooted at root node. \n /// If it finds it, the function computes the offset span of that child node within the root and returns true, \n /// otherwise it returns false.\n /// \n /// Root node\n /// Node to search in the subtree rooted at root node\n /// Offset of the location node within the subtree rooted at child\n /// \n private bool FindOffset(GreenNode root, CSharpSyntaxNode location, out int offset)\n {\n int currentOffset = 0;\n offset = 0;\n if (root != null)\n {\n for (int i = 0, n = root.SlotCount; i < n; i++)\n {\n var child = root.GetSlot(i);\n if (child == null)\n {\n // ignore null slots\n continue;\n }\n\n // check if the child node is the location node\n if (child == location)\n {\n // Found the location node in the subtree\n // Initialize offset with the offset of the location node within its parent\n // and walk up the stack of recursive calls adding the offset of each node\n // within its parent\n offset = currentOffset;\n return true;\n }\n\n // search for the location node in the subtree rooted at child node\n if (this.FindOffset(child, location, out offset))\n {\n // Found the location node in child's subtree\n // Add the offset of child node within its parent to offset\n // and continue walking up the stack\n offset += child.GetLeadingTriviaWidth() + currentOffset;\n return true;\n }\n\n // We didn't find the location node in the subtree rooted at child\n // Move on to the next child\n currentOffset += child.FullWidth;\n }\n }\n\n // We didn't find the location node within the subtree rooted at root node\n return false;\n }\n\n protected static SyntaxToken ConvertToKeyword(SyntaxToken token)\n {\n if (token.Kind != token.ContextualKind)\n {\n var kw = token.IsMissing\n ? SyntaxFactory.MissingToken(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node)\n : SyntaxFactory.Token(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node);\n var d = token.GetDiagnostics();\n if (d != null && d.Length > 0)\n {\n kw = kw.WithDiagnosticsGreen(d);\n }\n\n return kw;\n }\n\n return token;\n }\n\n protected static SyntaxToken ConvertToIdentifier(SyntaxToken token)\n {\n Debug.Assert(!token.IsMissing);\n return SyntaxToken.Identifier(token.Kind, token.LeadingTrivia.Node, token.Text, token.ValueText, token.TrailingTrivia.Node);\n }\n\n internal DirectiveStack Directives\n {\n get { return lexer.Directives; }\n }\n\n#nullable enable\n /// \n /// NOTE: we are specifically diverging from dev11 to improve the user experience.\n /// Since treating the \"async\" keyword as an identifier in older language\n /// versions can never result in a correct program, we instead accept it as a\n /// keyword regardless of the language version and produce an error if the version\n /// is insufficient.\n /// \n protected TNode CheckFeatureAvailability(TNode node, MessageID feature, bool forceWarning = false)\n where TNode : GreenNode\n {\n LanguageVersion availableVersion = this.Options.LanguageVersion;\n LanguageVersion requiredVersion = feature.RequiredVersion();\n\n // There are special error codes for some features, so handle those separately.\n switch (feature)\n {\n case MessageID.IDS_FeatureModuleAttrLoc:\n return availableVersion >= LanguageVersion.CSharp2\n ? node\n : this.AddError(node, ErrorCode.WRN_NonECMAFeature, feature.Localize());\n\n case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings:\n return availableVersion >= requiredVersion\n ? node\n : this.AddError(node, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable,\n new CSharpRequiredLanguageVersion(requiredVersion));\n }\n\n var info = feature.GetFeatureAvailabilityDiagnosticInfo(this.Options);\n if (info != null)\n {\n if (forceWarning)\n {\n return AddError(node, ErrorCode.WRN_ErrorOverride, info, (int)info.Code);\n }\n\n return AddError(node, info.Code, info.Arguments);\n }\n\n return node;\n }\n#nullable disable\n\n protected bool IsFeatureEnabled(MessageID feature)\n {\n return this.Options.IsFeatureEnabled(feature);\n }\n\n /// \n /// Whenever parsing in a while (true) loop and a bug could prevent the loop from making progress,\n /// this method can prevent the parsing from hanging.\n /// Use as:\n /// int tokenProgress = -1;\n /// while (IsMakingProgress(ref tokenProgress))\n /// It should be used as a guardrail, not as a crutch, so it asserts if no progress was made.\n /// \n protected bool IsMakingProgress(ref int lastTokenPosition, bool assertIfFalse = true)\n {\n var pos = CurrentTokenPosition;\n if (pos > lastTokenPosition)\n {\n lastTokenPosition = pos;\n return true;\n }\n\n Debug.Assert(!assertIfFalse);\n return false;\n }\n\n private int CurrentTokenPosition => _firstToken + _tokenOffset;\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax\n{\n using Microsoft.CodeAnalysis.Syntax.InternalSyntax;\n\n internal abstract partial class SyntaxParser : IDisposable\n {\n protected readonly Lexer lexer;\n private readonly bool _isIncremental;\n private readonly bool _allowModeReset;\n protected readonly CancellationToken cancellationToken;\n\n private LexerMode _mode;\n private Blender _firstBlender;\n private BlendedNode _currentNode;\n private SyntaxToken _currentToken;\n private ArrayElement[] _lexedTokens;\n private GreenNode _prevTokenTrailingTrivia;\n private int _firstToken; // The position of _lexedTokens[0] (or _blendedTokens[0]).\n private int _tokenOffset; // The index of the current token within _lexedTokens or _blendedTokens.\n private int _tokenCount;\n private int _resetCount;\n private int _resetStart;\n\n private static readonly ObjectPool s_blendedNodesPool = new ObjectPool(() => new BlendedNode[32], 2);\n\n private BlendedNode[] _blendedTokens;\n\n protected SyntaxParser(\n Lexer lexer,\n LexerMode mode,\n CSharp.CSharpSyntaxNode oldTree,\n IEnumerable changes,\n bool allowModeReset,\n bool preLexIfNotIncremental = false,\n CancellationToken cancellationToken = default(CancellationToken))\n {\n this.lexer = lexer;\n _mode = mode;\n _allowModeReset = allowModeReset;\n this.cancellationToken = cancellationToken;\n _currentNode = default(BlendedNode);\n _isIncremental = oldTree != null;\n\n if (this.IsIncremental || allowModeReset)\n {\n _firstBlender = new Blender(lexer, oldTree, changes);\n _blendedTokens = s_blendedNodesPool.Allocate();\n }\n else\n {\n _firstBlender = default(Blender);\n _lexedTokens = new ArrayElement[32];\n }\n\n // PreLex is not cancellable. \n // If we may cancel why would we aggressively lex ahead?\n // Cancellations in a constructor make disposing complicated\n //\n // So, if we have a real cancellation token, do not do prelexing.\n if (preLexIfNotIncremental && !this.IsIncremental && !cancellationToken.CanBeCanceled)\n {\n this.PreLex();\n }\n }\n\n public void Dispose()\n {\n var blendedTokens = _blendedTokens;\n if (blendedTokens != null)\n {\n _blendedTokens = null;\n if (blendedTokens.Length < 4096)\n {\n Array.Clear(blendedTokens, 0, blendedTokens.Length);\n s_blendedNodesPool.Free(blendedTokens);\n }\n else\n {\n s_blendedNodesPool.ForgetTrackedObject(blendedTokens);\n }\n }\n }\n\n protected void ReInitialize()\n {\n _firstToken = 0;\n _tokenOffset = 0;\n _tokenCount = 0;\n _resetCount = 0;\n _resetStart = 0;\n _currentToken = null;\n _prevTokenTrailingTrivia = null;\n if (this.IsIncremental || _allowModeReset)\n {\n _firstBlender = new Blender(this.lexer, null, null);\n }\n }\n\n protected bool IsIncremental\n {\n get\n {\n return _isIncremental;\n }\n }\n\n private void PreLex()\n {\n // NOTE: Do not cancel in this method. It is called from the constructor.\n var size = Math.Min(4096, Math.Max(32, this.lexer.TextWindow.Text.Length / 2));\n _lexedTokens = new ArrayElement[size];\n var lexer = this.lexer;\n var mode = _mode;\n\n for (int i = 0; i < size; i++)\n {\n var token = lexer.Lex(mode);\n this.AddLexedToken(token);\n if (token.Kind == SyntaxKind.EndOfFileToken)\n {\n break;\n }\n }\n }\n\n protected ResetPoint GetResetPoint()\n {\n var pos = CurrentTokenPosition;\n if (_resetCount == 0)\n {\n _resetStart = pos; // low water mark\n }\n\n _resetCount++;\n return new ResetPoint(_resetCount, _mode, pos, _prevTokenTrailingTrivia);\n }\n\n protected void Reset(ref ResetPoint point)\n {\n var offset = point.Position - _firstToken;\n Debug.Assert(offset >= 0);\n\n if (offset >= _tokenCount)\n {\n // Re-fetch tokens to the position in the reset point\n PeekToken(offset - _tokenOffset);\n\n // Re-calculate new offset in case tokens got shifted to the left while we were peeking. \n offset = point.Position - _firstToken;\n }\n\n _mode = point.Mode;\n Debug.Assert(offset >= 0 && offset < _tokenCount);\n _tokenOffset = offset;\n _currentToken = null;\n _currentNode = default(BlendedNode);\n _prevTokenTrailingTrivia = point.PrevTokenTrailingTrivia;\n if (_blendedTokens != null)\n {\n // look forward for slots not holding a token\n for (int i = _tokenOffset; i < _tokenCount; i++)\n {\n if (_blendedTokens[i].Token == null)\n {\n // forget anything after and including any slot not holding a token\n _tokenCount = i;\n if (_tokenCount == _tokenOffset)\n {\n FetchCurrentToken();\n }\n break;\n }\n }\n }\n }\n\n protected void Release(ref ResetPoint point)\n {\n Debug.Assert(_resetCount == point.ResetCount);\n _resetCount--;\n if (_resetCount == 0)\n {\n _resetStart = -1;\n }\n }\n\n public CSharpParseOptions Options\n {\n get { return this.lexer.Options; }\n }\n\n public bool IsScript\n {\n get { return Options.Kind == SourceCodeKind.Script; }\n }\n\n protected LexerMode Mode\n {\n get\n {\n return _mode;\n }\n\n set\n {\n if (_mode != value)\n {\n Debug.Assert(_allowModeReset);\n\n _mode = value;\n _currentToken = null;\n _currentNode = default(BlendedNode);\n _tokenCount = _tokenOffset;\n }\n }\n }\n\n protected CSharp.CSharpSyntaxNode CurrentNode\n {\n get\n {\n // we will fail anyways. Assert is just to catch that earlier.\n Debug.Assert(_blendedTokens != null);\n\n //PERF: currentNode is a BlendedNode, which is a fairly large struct.\n // the following code tries not to pull the whole struct into a local\n // we only need .Node\n var node = _currentNode.Node;\n if (node != null)\n {\n return node;\n }\n\n this.ReadCurrentNode();\n return _currentNode.Node;\n }\n }\n\n protected SyntaxKind CurrentNodeKind\n {\n get\n {\n var cn = this.CurrentNode;\n return cn != null ? cn.Kind() : SyntaxKind.None;\n }\n }\n\n private void ReadCurrentNode()\n {\n if (_tokenOffset == 0)\n {\n _currentNode = _firstBlender.ReadNode(_mode);\n }\n else\n {\n _currentNode = _blendedTokens[_tokenOffset - 1].Blender.ReadNode(_mode);\n }\n }\n\n protected GreenNode EatNode()\n {\n // we will fail anyways. Assert is just to catch that earlier.\n Debug.Assert(_blendedTokens != null);\n\n // remember result\n var result = CurrentNode.Green;\n\n // store possible non-token in token sequence \n if (_tokenOffset >= _blendedTokens.Length)\n {\n this.AddTokenSlot();\n }\n\n _blendedTokens[_tokenOffset++] = _currentNode;\n _tokenCount = _tokenOffset; // forget anything after this slot\n\n // erase current state\n _currentNode = default(BlendedNode);\n _currentToken = null;\n\n return result;\n }\n\n protected SyntaxToken CurrentToken\n {\n get\n {\n return _currentToken ?? (_currentToken = this.FetchCurrentToken());\n }\n }\n\n private SyntaxToken FetchCurrentToken()\n {\n if (_tokenOffset >= _tokenCount)\n {\n this.AddNewToken();\n }\n\n if (_blendedTokens != null)\n {\n return _blendedTokens[_tokenOffset].Token;\n }\n else\n {\n return _lexedTokens[_tokenOffset];\n }\n }\n\n private void AddNewToken()\n {\n if (_blendedTokens != null)\n {\n if (_tokenCount > 0)\n {\n this.AddToken(_blendedTokens[_tokenCount - 1].Blender.ReadToken(_mode));\n }\n else\n {\n if (_currentNode.Token != null)\n {\n this.AddToken(_currentNode);\n }\n else\n {\n this.AddToken(_firstBlender.ReadToken(_mode));\n }\n }\n }\n else\n {\n this.AddLexedToken(this.lexer.Lex(_mode));\n }\n }\n\n // adds token to end of current token array\n private void AddToken(in BlendedNode tokenResult)\n {\n Debug.Assert(tokenResult.Token != null);\n if (_tokenCount >= _blendedTokens.Length)\n {\n this.AddTokenSlot();\n }\n\n _blendedTokens[_tokenCount] = tokenResult;\n _tokenCount++;\n }\n\n private void AddLexedToken(SyntaxToken token)\n {\n Debug.Assert(token != null);\n if (_tokenCount >= _lexedTokens.Length)\n {\n this.AddLexedTokenSlot();\n }\n\n _lexedTokens[_tokenCount].Value = token;\n _tokenCount++;\n }\n\n private void AddTokenSlot()\n {\n // shift tokens to left if we are far to the right\n // don't shift if reset points have fixed locked the starting point at the token in the window\n if (_tokenOffset > (_blendedTokens.Length >> 1)\n && (_resetStart == -1 || _resetStart > _firstToken))\n {\n int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;\n int shiftCount = _tokenCount - shiftOffset;\n Debug.Assert(shiftOffset > 0);\n _firstBlender = _blendedTokens[shiftOffset - 1].Blender;\n if (shiftCount > 0)\n {\n Array.Copy(_blendedTokens, shiftOffset, _blendedTokens, 0, shiftCount);\n }\n\n _firstToken += shiftOffset;\n _tokenCount -= shiftOffset;\n _tokenOffset -= shiftOffset;\n }\n else\n {\n var old = _blendedTokens;\n Array.Resize(ref _blendedTokens, _blendedTokens.Length * 2);\n s_blendedNodesPool.ForgetTrackedObject(old, replacement: _blendedTokens);\n }\n }\n\n private void AddLexedTokenSlot()\n {\n // shift tokens to left if we are far to the right\n // don't shift if reset points have fixed locked the starting point at the token in the window\n if (_tokenOffset > (_lexedTokens.Length >> 1)\n && (_resetStart == -1 || _resetStart > _firstToken))\n {\n int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;\n int shiftCount = _tokenCount - shiftOffset;\n Debug.Assert(shiftOffset > 0);\n if (shiftCount > 0)\n {\n Array.Copy(_lexedTokens, shiftOffset, _lexedTokens, 0, shiftCount);\n }\n\n _firstToken += shiftOffset;\n _tokenCount -= shiftOffset;\n _tokenOffset -= shiftOffset;\n }\n else\n {\n var tmp = new ArrayElement[_lexedTokens.Length * 2];\n Array.Copy(_lexedTokens, tmp, _lexedTokens.Length);\n _lexedTokens = tmp;\n }\n }\n\n protected SyntaxToken PeekToken(int n)\n {\n Debug.Assert(n >= 0);\n while (_tokenOffset + n >= _tokenCount)\n {\n this.AddNewToken();\n }\n\n if (_blendedTokens != null)\n {\n return _blendedTokens[_tokenOffset + n].Token;\n }\n else\n {\n return _lexedTokens[_tokenOffset + n];\n }\n }\n\n //this method is called very frequently\n //we should keep it simple so that it can be inlined.\n protected SyntaxToken EatToken()\n {\n var ct = this.CurrentToken;\n MoveToNextToken();\n return ct;\n }\n\n /// \n /// Returns and consumes the current token if it has the requested .\n /// Otherwise, returns .\n /// \n protected SyntaxToken TryEatToken(SyntaxKind kind)\n => this.CurrentToken.Kind == kind ? this.EatToken() : null;\n\n private void MoveToNextToken()\n {\n _prevTokenTrailingTrivia = _currentToken.GetTrailingTrivia();\n\n _currentToken = null;\n\n if (_blendedTokens != null)\n {\n _currentNode = default(BlendedNode);\n }\n\n _tokenOffset++;\n }\n\n protected void ForceEndOfFile()\n {\n _currentToken = SyntaxFactory.Token(SyntaxKind.EndOfFileToken);\n }\n\n //this method is called very frequently\n //we should keep it simple so that it can be inlined.\n protected SyntaxToken EatToken(SyntaxKind kind)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n\n var ct = this.CurrentToken;\n if (ct.Kind == kind)\n {\n MoveToNextToken();\n return ct;\n }\n\n //slow part of EatToken(SyntaxKind kind)\n return CreateMissingToken(kind, this.CurrentToken.Kind, reportError: true);\n }\n\n // Consume a token if it is the right kind. Otherwise skip a token and replace it with one of the correct kind.\n protected SyntaxToken EatTokenAsKind(SyntaxKind expected)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(expected));\n\n var ct = this.CurrentToken;\n if (ct.Kind == expected)\n {\n MoveToNextToken();\n return ct;\n }\n\n var replacement = CreateMissingToken(expected, this.CurrentToken.Kind, reportError: true);\n return AddTrailingSkippedSyntax(replacement, this.EatToken());\n }\n\n private SyntaxToken CreateMissingToken(SyntaxKind expected, SyntaxKind actual, bool reportError)\n {\n // should we eat the current ParseToken's leading trivia?\n var token = SyntaxFactory.MissingToken(expected);\n if (reportError)\n {\n token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(expected, actual));\n }\n\n return token;\n }\n\n private SyntaxToken CreateMissingToken(SyntaxKind expected, ErrorCode code, bool reportError)\n {\n // should we eat the current ParseToken's leading trivia?\n var token = SyntaxFactory.MissingToken(expected);\n if (reportError)\n {\n token = AddError(token, code);\n }\n\n return token;\n }\n\n protected SyntaxToken EatToken(SyntaxKind kind, bool reportError)\n {\n if (reportError)\n {\n return EatToken(kind);\n }\n\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n if (this.CurrentToken.Kind != kind)\n {\n // should we eat the current ParseToken's leading trivia?\n return SyntaxFactory.MissingToken(kind);\n }\n else\n {\n return this.EatToken();\n }\n }\n\n protected SyntaxToken EatToken(SyntaxKind kind, ErrorCode code, bool reportError = true)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n if (this.CurrentToken.Kind != kind)\n {\n return CreateMissingToken(kind, code, reportError);\n }\n else\n {\n return this.EatToken();\n }\n }\n\n protected SyntaxToken EatTokenWithPrejudice(SyntaxKind kind)\n {\n var token = this.CurrentToken;\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n if (token.Kind != kind)\n {\n token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(kind, token.Kind));\n }\n\n this.MoveToNextToken();\n return token;\n }\n\n protected SyntaxToken EatTokenWithPrejudice(ErrorCode errorCode, params object[] args)\n {\n var token = this.EatToken();\n token = WithAdditionalDiagnostics(token, MakeError(token.GetLeadingTriviaWidth(), token.Width, errorCode, args));\n return token;\n }\n\n protected SyntaxToken EatContextualToken(SyntaxKind kind, ErrorCode code, bool reportError = true)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n\n if (this.CurrentToken.ContextualKind != kind)\n {\n return CreateMissingToken(kind, code, reportError);\n }\n else\n {\n return ConvertToKeyword(this.EatToken());\n }\n }\n\n protected SyntaxToken EatContextualToken(SyntaxKind kind, bool reportError = true)\n {\n Debug.Assert(SyntaxFacts.IsAnyToken(kind));\n\n var contextualKind = this.CurrentToken.ContextualKind;\n if (contextualKind != kind)\n {\n return CreateMissingToken(kind, contextualKind, reportError);\n }\n else\n {\n return ConvertToKeyword(this.EatToken());\n }\n }\n\n protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int width)\n {\n var code = GetExpectedTokenErrorCode(expected, actual);\n if (code == ErrorCode.ERR_SyntaxError || code == ErrorCode.ERR_IdentifierExpectedKW)\n {\n return new SyntaxDiagnosticInfo(offset, width, code, SyntaxFacts.GetText(expected), SyntaxFacts.GetText(actual));\n }\n else\n {\n return new SyntaxDiagnosticInfo(offset, width, code);\n }\n }\n\n protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual)\n {\n int offset, width;\n this.GetDiagnosticSpanForMissingToken(out offset, out width);\n\n return this.GetExpectedTokenError(expected, actual, offset, width);\n }\n\n private static ErrorCode GetExpectedTokenErrorCode(SyntaxKind expected, SyntaxKind actual)\n {\n switch (expected)\n {\n case SyntaxKind.IdentifierToken:\n if (SyntaxFacts.IsReservedKeyword(actual))\n {\n return ErrorCode.ERR_IdentifierExpectedKW; // A keyword -- use special message.\n }\n else\n {\n return ErrorCode.ERR_IdentifierExpected;\n }\n\n case SyntaxKind.SemicolonToken:\n return ErrorCode.ERR_SemicolonExpected;\n\n // case TokenKind::Colon: iError = ERR_ColonExpected; break;\n // case TokenKind::OpenParen: iError = ERR_LparenExpected; break;\n case SyntaxKind.CloseParenToken:\n return ErrorCode.ERR_CloseParenExpected;\n case SyntaxKind.OpenBraceToken:\n return ErrorCode.ERR_LbraceExpected;\n case SyntaxKind.CloseBraceToken:\n return ErrorCode.ERR_RbraceExpected;\n\n // case TokenKind::CloseSquare: iError = ERR_CloseSquareExpected; break;\n default:\n return ErrorCode.ERR_SyntaxError;\n }\n }\n\n protected void GetDiagnosticSpanForMissingToken(out int offset, out int width)\n {\n // If the previous token has a trailing EndOfLineTrivia,\n // the missing token diagnostic position is moved to the\n // end of line containing the previous token and\n // its width is set to zero.\n // Otherwise the diagnostic offset and width is set\n // to the corresponding values of the current token\n\n var trivia = _prevTokenTrailingTrivia;\n if (trivia != null)\n {\n SyntaxList triviaList = new SyntaxList(trivia);\n bool prevTokenHasEndOfLineTrivia = triviaList.Any((int)SyntaxKind.EndOfLineTrivia);\n if (prevTokenHasEndOfLineTrivia)\n {\n offset = -trivia.FullWidth;\n width = 0;\n return;\n }\n }\n\n SyntaxToken ct = this.CurrentToken;\n offset = ct.GetLeadingTriviaWidth();\n width = ct.Width;\n }\n\n protected virtual TNode WithAdditionalDiagnostics(TNode node, params DiagnosticInfo[] diagnostics) where TNode : GreenNode\n {\n DiagnosticInfo[] existingDiags = node.GetDiagnostics();\n int existingLength = existingDiags.Length;\n if (existingLength == 0)\n {\n return node.WithDiagnosticsGreen(diagnostics);\n }\n else\n {\n DiagnosticInfo[] result = new DiagnosticInfo[existingDiags.Length + diagnostics.Length];\n existingDiags.CopyTo(result, 0);\n diagnostics.CopyTo(result, existingLength);\n return node.WithDiagnosticsGreen(result);\n }\n }\n\n protected TNode AddError(TNode node, ErrorCode code) where TNode : GreenNode\n {\n return AddError(node, code, Array.Empty());\n }\n\n protected TNode AddError(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode\n {\n if (!node.IsMissing)\n {\n return WithAdditionalDiagnostics(node, MakeError(node, code, args));\n }\n\n int offset, width;\n\n SyntaxToken token = node as SyntaxToken;\n if (token != null && token.ContainsSkippedText)\n {\n // This code exists to clean up an anti-pattern:\n // 1) an undesirable token is parsed,\n // 2) a desirable missing token is created and the parsed token is appended as skipped text,\n // 3) an error is attached to the missing token describing the problem.\n // If this occurs, then this.previousTokenTrailingTrivia is still populated with the trivia \n // of the undesirable token (now skipped text). Since the trivia no longer precedes the\n // node to which the error is to be attached, the computed offset will be incorrect.\n\n offset = token.GetLeadingTriviaWidth(); // Should always be zero, but at least we'll do something sensible if it's not.\n Debug.Assert(offset == 0, \"Why are we producing a missing token that has both skipped text and leading trivia?\");\n\n width = 0;\n bool seenSkipped = false;\n foreach (var trivia in token.TrailingTrivia)\n {\n if (trivia.Kind == SyntaxKind.SkippedTokensTrivia)\n {\n seenSkipped = true;\n width += trivia.Width;\n }\n else if (seenSkipped)\n {\n break;\n }\n else\n {\n offset += trivia.Width;\n }\n }\n }\n else\n {\n this.GetDiagnosticSpanForMissingToken(out offset, out width);\n }\n\n return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));\n }\n\n protected TNode AddError(TNode node, int offset, int length, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n return WithAdditionalDiagnostics(node, MakeError(offset, length, code, args));\n }\n\n protected TNode AddError(TNode node, CSharpSyntaxNode location, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n // assumes non-terminals will at most appear once in sub-tree\n int offset;\n FindOffset(node, location, out offset);\n return WithAdditionalDiagnostics(node, MakeError(offset, location.Width, code, args));\n }\n\n protected TNode AddErrorToFirstToken(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode\n {\n var firstToken = node.GetFirstToken();\n return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code));\n }\n\n protected TNode AddErrorToFirstToken(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n var firstToken = node.GetFirstToken();\n return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code, args));\n }\n\n protected TNode AddErrorToLastToken(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode\n {\n int offset;\n int width;\n GetOffsetAndWidthForLastToken(node, out offset, out width);\n return WithAdditionalDiagnostics(node, MakeError(offset, width, code));\n }\n\n protected TNode AddErrorToLastToken(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode\n {\n int offset;\n int width;\n GetOffsetAndWidthForLastToken(node, out offset, out width);\n return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));\n }\n\n private static void GetOffsetAndWidthForLastToken(TNode node, out int offset, out int width) where TNode : CSharpSyntaxNode\n {\n var lastToken = node.GetLastNonmissingToken();\n offset = node.FullWidth; //advance to end of entire node\n width = 0;\n if (lastToken != null) //will be null if all tokens are missing\n {\n offset -= lastToken.FullWidth; //rewind past last token\n offset += lastToken.GetLeadingTriviaWidth(); //advance past last token leading trivia - now at start of last token\n width += lastToken.Width;\n }\n }\n\n protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code)\n {\n return new SyntaxDiagnosticInfo(offset, width, code);\n }\n\n protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code, params object[] args)\n {\n return new SyntaxDiagnosticInfo(offset, width, code, args);\n }\n\n protected static SyntaxDiagnosticInfo MakeError(GreenNode node, ErrorCode code, params object[] args)\n {\n return new SyntaxDiagnosticInfo(node.GetLeadingTriviaWidth(), node.Width, code, args);\n }\n\n protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args)\n {\n return new SyntaxDiagnosticInfo(code, args);\n }\n\n protected TNode AddLeadingSkippedSyntax(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode\n {\n var oldToken = node as SyntaxToken ?? node.GetFirstToken();\n var newToken = AddSkippedSyntax(oldToken, skippedSyntax, trailing: false);\n return SyntaxFirstTokenReplacer.Replace(node, oldToken, newToken, skippedSyntax.FullWidth);\n }\n\n protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax)\n {\n list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], skippedSyntax);\n }\n\n protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode\n {\n list[list.Count - 1] = AddTrailingSkippedSyntax(list[list.Count - 1], skippedSyntax);\n }\n\n protected TNode AddTrailingSkippedSyntax(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode\n {\n var token = node as SyntaxToken;\n if (token != null)\n {\n return (TNode)(object)AddSkippedSyntax(token, skippedSyntax, trailing: true);\n }\n else\n {\n var lastToken = node.GetLastToken();\n var newToken = AddSkippedSyntax(lastToken, skippedSyntax, trailing: true);\n return SyntaxLastTokenReplacer.Replace(node, newToken);\n }\n }\n\n /// \n /// Converts skippedSyntax node into tokens and adds these as trivia on the target token.\n /// Also adds the first error (in depth-first preorder) found in the skipped syntax tree to the target token.\n /// \n internal SyntaxToken AddSkippedSyntax(SyntaxToken target, GreenNode skippedSyntax, bool trailing)\n {\n var builder = new SyntaxListBuilder(4);\n\n // the error in we'll attach to the node\n SyntaxDiagnosticInfo diagnostic = null;\n\n // the position of the error within the skippedSyntax node full tree\n int diagnosticOffset = 0;\n\n int currentOffset = 0;\n foreach (var node in skippedSyntax.EnumerateNodes())\n {\n SyntaxToken token = node as SyntaxToken;\n if (token != null)\n {\n builder.Add(token.GetLeadingTrivia());\n\n if (token.Width > 0)\n {\n // separate trivia from the tokens\n SyntaxToken tk = token.TokenWithLeadingTrivia(null).TokenWithTrailingTrivia(null);\n\n // adjust relative offsets of diagnostics attached to the token:\n int leadingWidth = token.GetLeadingTriviaWidth();\n if (leadingWidth > 0)\n {\n var tokenDiagnostics = tk.GetDiagnostics();\n for (int i = 0; i < tokenDiagnostics.Length; i++)\n {\n var d = (SyntaxDiagnosticInfo)tokenDiagnostics[i];\n tokenDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset - leadingWidth, d.Width, (ErrorCode)d.Code, d.Arguments);\n }\n }\n\n builder.Add(SyntaxFactory.SkippedTokensTrivia(tk));\n }\n else\n {\n // do not create zero-width structured trivia, GetStructure doesn't work well for them\n var existing = (SyntaxDiagnosticInfo)token.GetDiagnostics().FirstOrDefault();\n if (existing != null)\n {\n diagnostic = existing;\n diagnosticOffset = currentOffset;\n }\n }\n builder.Add(token.GetTrailingTrivia());\n\n currentOffset += token.FullWidth;\n }\n else if (node.ContainsDiagnostics && diagnostic == null)\n {\n // only propagate the first error to reduce noise:\n var existing = (SyntaxDiagnosticInfo)node.GetDiagnostics().FirstOrDefault();\n if (existing != null)\n {\n diagnostic = existing;\n diagnosticOffset = currentOffset;\n }\n }\n }\n\n int triviaWidth = currentOffset;\n var trivia = builder.ToListNode();\n\n // total width of everything preceding the added trivia\n int triviaOffset;\n if (trailing)\n {\n var trailingTrivia = target.GetTrailingTrivia();\n triviaOffset = target.FullWidth; //added trivia is full width (before addition)\n target = target.TokenWithTrailingTrivia(SyntaxList.Concat(trailingTrivia, trivia));\n }\n else\n {\n // Since we're adding triviaWidth before the token, we have to add that much to\n // the offset of each of its diagnostics.\n if (triviaWidth > 0)\n {\n var targetDiagnostics = target.GetDiagnostics();\n for (int i = 0; i < targetDiagnostics.Length; i++)\n {\n var d = (SyntaxDiagnosticInfo)targetDiagnostics[i];\n targetDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset + triviaWidth, d.Width, (ErrorCode)d.Code, d.Arguments);\n }\n }\n\n var leadingTrivia = target.GetLeadingTrivia();\n target = target.TokenWithLeadingTrivia(SyntaxList.Concat(trivia, leadingTrivia));\n triviaOffset = 0; //added trivia is first, so offset is zero\n }\n\n if (diagnostic != null)\n {\n int newOffset = triviaOffset + diagnosticOffset + diagnostic.Offset;\n\n target = WithAdditionalDiagnostics(target,\n new SyntaxDiagnosticInfo(newOffset, diagnostic.Width, (ErrorCode)diagnostic.Code, diagnostic.Arguments)\n );\n }\n\n return target;\n }\n\n /// \n /// This function searches for the given location node within the subtree rooted at root node. \n /// If it finds it, the function computes the offset span of that child node within the root and returns true, \n /// otherwise it returns false.\n /// \n /// Root node\n /// Node to search in the subtree rooted at root node\n /// Offset of the location node within the subtree rooted at child\n /// \n private bool FindOffset(GreenNode root, CSharpSyntaxNode location, out int offset)\n {\n int currentOffset = 0;\n offset = 0;\n if (root != null)\n {\n for (int i = 0, n = root.SlotCount; i < n; i++)\n {\n var child = root.GetSlot(i);\n if (child == null)\n {\n // ignore null slots\n continue;\n }\n\n // check if the child node is the location node\n if (child == location)\n {\n // Found the location node in the subtree\n // Initialize offset with the offset of the location node within its parent\n // and walk up the stack of recursive calls adding the offset of each node\n // within its parent\n offset = currentOffset;\n return true;\n }\n\n // search for the location node in the subtree rooted at child node\n if (this.FindOffset(child, location, out offset))\n {\n // Found the location node in child's subtree\n // Add the offset of child node within its parent to offset\n // and continue walking up the stack\n offset += child.GetLeadingTriviaWidth() + currentOffset;\n return true;\n }\n\n // We didn't find the location node in the subtree rooted at child\n // Move on to the next child\n currentOffset += child.FullWidth;\n }\n }\n\n // We didn't find the location node within the subtree rooted at root node\n return false;\n }\n\n protected static SyntaxToken ConvertToKeyword(SyntaxToken token)\n {\n if (token.Kind != token.ContextualKind)\n {\n var kw = token.IsMissing\n ? SyntaxFactory.MissingToken(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node)\n : SyntaxFactory.Token(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node);\n var d = token.GetDiagnostics();\n if (d != null && d.Length > 0)\n {\n kw = kw.WithDiagnosticsGreen(d);\n }\n\n return kw;\n }\n\n return token;\n }\n\n protected static SyntaxToken ConvertToIdentifier(SyntaxToken token)\n {\n Debug.Assert(!token.IsMissing);\n return SyntaxToken.Identifier(token.Kind, token.LeadingTrivia.Node, token.Text, token.ValueText, token.TrailingTrivia.Node);\n }\n\n internal DirectiveStack Directives\n {\n get { return lexer.Directives; }\n }\n\n#nullable enable\n /// \n /// NOTE: we are specifically diverging from dev11 to improve the user experience.\n /// Since treating the \"async\" keyword as an identifier in older language\n /// versions can never result in a correct program, we instead accept it as a\n /// keyword regardless of the language version and produce an error if the version\n /// is insufficient.\n /// \n protected TNode CheckFeatureAvailability(TNode node, MessageID feature, bool forceWarning = false)\n where TNode : GreenNode\n {\n LanguageVersion availableVersion = this.Options.LanguageVersion;\n LanguageVersion requiredVersion = feature.RequiredVersion();\n\n // There are special error codes for some features, so handle those separately.\n switch (feature)\n {\n case MessageID.IDS_FeatureModuleAttrLoc:\n return availableVersion >= LanguageVersion.CSharp2\n ? node\n : this.AddError(node, ErrorCode.WRN_NonECMAFeature, feature.Localize());\n\n case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings:\n return availableVersion >= requiredVersion\n ? node\n : this.AddError(node, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable,\n new CSharpRequiredLanguageVersion(requiredVersion));\n }\n\n var info = feature.GetFeatureAvailabilityDiagnosticInfo(this.Options);\n if (info != null)\n {\n if (forceWarning)\n {\n return AddError(node, ErrorCode.WRN_ErrorOverride, info, (int)info.Code);\n }\n\n return AddError(node, info.Code, info.Arguments);\n }\n\n return node;\n }\n#nullable disable\n\n protected bool IsFeatureEnabled(MessageID feature)\n {\n return this.Options.IsFeatureEnabled(feature);\n }\n\n /// \n /// Whenever parsing in a while (true) loop and a bug could prevent the loop from making progress,\n /// this method can prevent the parsing from hanging.\n /// Use as:\n /// int tokenProgress = -1;\n /// while (IsMakingProgress(ref tokenProgress))\n /// It should be used as a guardrail, not as a crutch, so it asserts if no progress was made.\n /// \n protected bool IsMakingProgress(ref int lastTokenPosition, bool assertIfFalse = true)\n {\n var pos = CurrentTokenPosition;\n if (pos > lastTokenPosition)\n {\n lastTokenPosition = pos;\n return true;\n }\n\n Debug.Assert(!assertIfFalse);\n return false;\n }\n\n private int CurrentTokenPosition => _firstToken + _tokenOffset;\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":464,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/WithPrefer32Bit.csproj"},"before_content":{"kind":"string","value":"\n\n\n \n \n Debug\n AnyCPU\n AnyCPU\n {9705A8E6-C854-4FD3-8CEA-EDBDD54C7FD8}\n Exe\n Properties\n ConsoleApplication62\n ConsoleApplication62\n v4.7.2\n 512\n \n \n AnyCPU\n true\n full\n false\n bin\\Debug\\\n DEBUG;TRACE\n prompt\n 4\n \n \n AnyCPU\n pdbonly\n true\n bin\\Release\\\n TRACE\n prompt\n 4\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n"},"after_content":{"kind":"string","value":"\n\n\n \n \n Debug\n AnyCPU\n AnyCPU\n {9705A8E6-C854-4FD3-8CEA-EDBDD54C7FD8}\n Exe\n Properties\n ConsoleApplication62\n ConsoleApplication62\n v4.7.2\n 512\n \n \n AnyCPU\n true\n full\n false\n bin\\Debug\\\n DEBUG;TRACE\n prompt\n 4\n \n \n AnyCPU\n pdbonly\n true\n bin\\Release\\\n TRACE\n prompt\n 4\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":465,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/Symbols/Source/IndexedTypeParameterSymbol.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Symbols\n{\n /// \n /// Indexed type parameters are used in place of type parameters for method signatures. There is\n /// a unique mapping from index to a single IndexedTypeParameterSymbol. \n /// \n /// They don't have a containing symbol or locations.\n /// \n /// They do not have constraints, variance, or attributes. \n /// \n internal sealed class IndexedTypeParameterSymbol : TypeParameterSymbol\n {\n private static TypeParameterSymbol[] s_parameterPool = Array.Empty();\n\n private readonly int _index;\n\n private IndexedTypeParameterSymbol(int index)\n {\n _index = index;\n }\n\n public override TypeParameterKind TypeParameterKind\n {\n get\n {\n return TypeParameterKind.Method;\n }\n }\n\n internal static TypeParameterSymbol GetTypeParameter(int index)\n {\n if (index >= s_parameterPool.Length)\n {\n GrowPool(index + 1);\n }\n\n return s_parameterPool[index];\n }\n\n private static void GrowPool(int count)\n {\n var initialPool = s_parameterPool;\n while (count > initialPool.Length)\n {\n var newPoolSize = ((count + 0x0F) & ~0xF); // grow in increments of 16\n var newPool = new TypeParameterSymbol[newPoolSize];\n\n Array.Copy(initialPool, newPool, initialPool.Length);\n\n for (int i = initialPool.Length; i < newPool.Length; i++)\n {\n newPool[i] = new IndexedTypeParameterSymbol(i);\n }\n\n Interlocked.CompareExchange(ref s_parameterPool, newPool, initialPool);\n\n // repeat if race condition occurred and someone else resized the pool before us\n // and the new pool is still too small\n initialPool = s_parameterPool;\n }\n }\n\n /// \n /// Create a vector of n dummy type parameters. Always reuses the same type parameter symbol\n /// for the same position.\n /// \n /// \n /// \n internal static ImmutableArray TakeSymbols(int count)\n {\n if (count > s_parameterPool.Length)\n {\n GrowPool(count);\n }\n\n ArrayBuilder builder = ArrayBuilder.GetInstance();\n\n for (int i = 0; i < count; i++)\n {\n builder.Add(GetTypeParameter(i));\n }\n\n return builder.ToImmutableAndFree();\n }\n\n internal static ImmutableArray Take(int count)\n {\n if (count > s_parameterPool.Length)\n {\n GrowPool(count);\n }\n\n var builder = ArrayBuilder.GetInstance();\n\n for (int i = 0; i < count; i++)\n {\n builder.Add(TypeWithAnnotations.Create(GetTypeParameter(i), NullableAnnotation.Ignored));\n }\n\n return builder.ToImmutableAndFree();\n }\n\n public override int Ordinal\n {\n get { return _index; }\n }\n\n // These object are unique (per index).\n internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison)\n {\n return ReferenceEquals(this, t2);\n }\n\n public override int GetHashCode()\n {\n return _index;\n }\n\n public override VarianceKind Variance\n {\n get { return VarianceKind.None; }\n }\n\n public override bool HasValueTypeConstraint\n {\n get { return false; }\n }\n\n public override bool IsValueTypeFromConstraintTypes\n {\n get { return false; }\n }\n\n public override bool HasReferenceTypeConstraint\n {\n get { return false; }\n }\n\n public override bool IsReferenceTypeFromConstraintTypes\n {\n get { return false; }\n }\n\n internal override bool? ReferenceTypeConstraintIsNullable\n {\n get { return false; }\n }\n\n public override bool HasNotNullConstraint => false;\n\n internal override bool? IsNotNullable => null;\n\n public override bool HasUnmanagedTypeConstraint\n {\n get { return false; }\n }\n\n public override bool HasConstructorConstraint\n {\n get { return false; }\n }\n\n public override Symbol ContainingSymbol\n {\n get\n {\n return null;\n }\n }\n\n public override ImmutableArray Locations\n {\n get\n {\n return ImmutableArray.Empty;\n }\n }\n\n public override ImmutableArray DeclaringSyntaxReferences\n {\n get\n {\n return ImmutableArray.Empty;\n }\n }\n\n internal override void EnsureAllConstraintsAreResolved()\n {\n }\n\n internal override ImmutableArray GetConstraintTypes(ConsList inProgress)\n {\n return ImmutableArray.Empty;\n }\n\n internal override ImmutableArray GetInterfaces(ConsList inProgress)\n {\n return ImmutableArray.Empty;\n }\n\n internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress)\n {\n return null;\n }\n\n internal override TypeSymbol GetDeducedBaseType(ConsList inProgress)\n {\n return null;\n }\n\n public override bool IsImplicitlyDeclared\n {\n get { return true; }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Symbols\n{\n /// \n /// Indexed type parameters are used in place of type parameters for method signatures. There is\n /// a unique mapping from index to a single IndexedTypeParameterSymbol. \n /// \n /// They don't have a containing symbol or locations.\n /// \n /// They do not have constraints, variance, or attributes. \n /// \n internal sealed class IndexedTypeParameterSymbol : TypeParameterSymbol\n {\n private static TypeParameterSymbol[] s_parameterPool = Array.Empty();\n\n private readonly int _index;\n\n private IndexedTypeParameterSymbol(int index)\n {\n _index = index;\n }\n\n public override TypeParameterKind TypeParameterKind\n {\n get\n {\n return TypeParameterKind.Method;\n }\n }\n\n internal static TypeParameterSymbol GetTypeParameter(int index)\n {\n if (index >= s_parameterPool.Length)\n {\n GrowPool(index + 1);\n }\n\n return s_parameterPool[index];\n }\n\n private static void GrowPool(int count)\n {\n var initialPool = s_parameterPool;\n while (count > initialPool.Length)\n {\n var newPoolSize = ((count + 0x0F) & ~0xF); // grow in increments of 16\n var newPool = new TypeParameterSymbol[newPoolSize];\n\n Array.Copy(initialPool, newPool, initialPool.Length);\n\n for (int i = initialPool.Length; i < newPool.Length; i++)\n {\n newPool[i] = new IndexedTypeParameterSymbol(i);\n }\n\n Interlocked.CompareExchange(ref s_parameterPool, newPool, initialPool);\n\n // repeat if race condition occurred and someone else resized the pool before us\n // and the new pool is still too small\n initialPool = s_parameterPool;\n }\n }\n\n /// \n /// Create a vector of n dummy type parameters. Always reuses the same type parameter symbol\n /// for the same position.\n /// \n /// \n /// \n internal static ImmutableArray TakeSymbols(int count)\n {\n if (count > s_parameterPool.Length)\n {\n GrowPool(count);\n }\n\n ArrayBuilder builder = ArrayBuilder.GetInstance();\n\n for (int i = 0; i < count; i++)\n {\n builder.Add(GetTypeParameter(i));\n }\n\n return builder.ToImmutableAndFree();\n }\n\n internal static ImmutableArray Take(int count)\n {\n if (count > s_parameterPool.Length)\n {\n GrowPool(count);\n }\n\n var builder = ArrayBuilder.GetInstance();\n\n for (int i = 0; i < count; i++)\n {\n builder.Add(TypeWithAnnotations.Create(GetTypeParameter(i), NullableAnnotation.Ignored));\n }\n\n return builder.ToImmutableAndFree();\n }\n\n public override int Ordinal\n {\n get { return _index; }\n }\n\n // These object are unique (per index).\n internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison)\n {\n return ReferenceEquals(this, t2);\n }\n\n public override int GetHashCode()\n {\n return _index;\n }\n\n public override VarianceKind Variance\n {\n get { return VarianceKind.None; }\n }\n\n public override bool HasValueTypeConstraint\n {\n get { return false; }\n }\n\n public override bool IsValueTypeFromConstraintTypes\n {\n get { return false; }\n }\n\n public override bool HasReferenceTypeConstraint\n {\n get { return false; }\n }\n\n public override bool IsReferenceTypeFromConstraintTypes\n {\n get { return false; }\n }\n\n internal override bool? ReferenceTypeConstraintIsNullable\n {\n get { return false; }\n }\n\n public override bool HasNotNullConstraint => false;\n\n internal override bool? IsNotNullable => null;\n\n public override bool HasUnmanagedTypeConstraint\n {\n get { return false; }\n }\n\n public override bool HasConstructorConstraint\n {\n get { return false; }\n }\n\n public override Symbol ContainingSymbol\n {\n get\n {\n return null;\n }\n }\n\n public override ImmutableArray Locations\n {\n get\n {\n return ImmutableArray.Empty;\n }\n }\n\n public override ImmutableArray DeclaringSyntaxReferences\n {\n get\n {\n return ImmutableArray.Empty;\n }\n }\n\n internal override void EnsureAllConstraintsAreResolved()\n {\n }\n\n internal override ImmutableArray GetConstraintTypes(ConsList inProgress)\n {\n return ImmutableArray.Empty;\n }\n\n internal override ImmutableArray GetInterfaces(ConsList inProgress)\n {\n return ImmutableArray.Empty;\n }\n\n internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList inProgress)\n {\n return null;\n }\n\n internal override TypeSymbol GetDeducedBaseType(ConsList inProgress)\n {\n return null;\n }\n\n public override bool IsImplicitlyDeclared\n {\n get { return true; }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":466,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/Text/TextChangeRange.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Text\n{\n /// \n /// Represents the change to a span of text.\n /// \n [DebuggerDisplay(\"{GetDebuggerDisplay(),nq}\")]\n public readonly struct TextChangeRange : IEquatable\n {\n /// \n /// The span of text before the edit which is being changed\n /// \n public TextSpan Span { get; }\n\n /// \n /// Width of the span after the edit. A 0 here would represent a delete\n /// \n public int NewLength { get; }\n\n internal int NewEnd => Span.Start + NewLength;\n\n /// \n /// Initializes a new instance of .\n /// \n /// \n /// \n public TextChangeRange(TextSpan span, int newLength)\n : this()\n {\n if (newLength < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(newLength));\n }\n\n this.Span = span;\n this.NewLength = newLength;\n }\n\n /// \n /// Compares current instance of to another.\n /// \n public bool Equals(TextChangeRange other)\n {\n return\n other.Span == this.Span &&\n other.NewLength == this.NewLength;\n }\n\n /// \n /// Compares current instance of to another.\n /// \n public override bool Equals(object? obj)\n {\n return obj is TextChangeRange range && Equals(range);\n }\n\n /// \n /// Provides hash code for current instance of .\n /// \n /// \n public override int GetHashCode()\n {\n return Hash.Combine(this.NewLength, this.Span.GetHashCode());\n }\n\n /// \n /// Determines if two instances of are same.\n /// \n public static bool operator ==(TextChangeRange left, TextChangeRange right)\n {\n return left.Equals(right);\n }\n\n /// \n /// Determines if two instances of are different.\n /// \n public static bool operator !=(TextChangeRange left, TextChangeRange right)\n {\n return !(left == right);\n }\n\n /// \n /// An empty set of changes.\n /// \n public static IReadOnlyList NoChanges => SpecializedCollections.EmptyReadOnlyList();\n\n /// \n /// Collapse a set of s into a single encompassing range. If\n /// the set of ranges provided is empty, an empty range is returned.\n /// \n public static TextChangeRange Collapse(IEnumerable changes)\n {\n var diff = 0;\n var start = int.MaxValue;\n var end = 0;\n\n foreach (var change in changes)\n {\n diff += change.NewLength - change.Span.Length;\n\n if (change.Span.Start < start)\n {\n start = change.Span.Start;\n }\n\n if (change.Span.End > end)\n {\n end = change.Span.End;\n }\n }\n\n if (start > end)\n {\n // there were no changes.\n return default(TextChangeRange);\n }\n\n var combined = TextSpan.FromBounds(start, end);\n var newLen = combined.Length + diff;\n\n return new TextChangeRange(combined, newLen);\n }\n\n private string GetDebuggerDisplay()\n {\n return $\"new TextChangeRange(new TextSpan({Span.Start}, {Span.Length}), {NewLength})\";\n }\n\n public override string ToString()\n {\n return $\"TextChangeRange(Span={Span}, NewLength={NewLength})\";\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Text\n{\n /// \n /// Represents the change to a span of text.\n /// \n [DebuggerDisplay(\"{GetDebuggerDisplay(),nq}\")]\n public readonly struct TextChangeRange : IEquatable\n {\n /// \n /// The span of text before the edit which is being changed\n /// \n public TextSpan Span { get; }\n\n /// \n /// Width of the span after the edit. A 0 here would represent a delete\n /// \n public int NewLength { get; }\n\n internal int NewEnd => Span.Start + NewLength;\n\n /// \n /// Initializes a new instance of .\n /// \n /// \n /// \n public TextChangeRange(TextSpan span, int newLength)\n : this()\n {\n if (newLength < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(newLength));\n }\n\n this.Span = span;\n this.NewLength = newLength;\n }\n\n /// \n /// Compares current instance of to another.\n /// \n public bool Equals(TextChangeRange other)\n {\n return\n other.Span == this.Span &&\n other.NewLength == this.NewLength;\n }\n\n /// \n /// Compares current instance of to another.\n /// \n public override bool Equals(object? obj)\n {\n return obj is TextChangeRange range && Equals(range);\n }\n\n /// \n /// Provides hash code for current instance of .\n /// \n /// \n public override int GetHashCode()\n {\n return Hash.Combine(this.NewLength, this.Span.GetHashCode());\n }\n\n /// \n /// Determines if two instances of are same.\n /// \n public static bool operator ==(TextChangeRange left, TextChangeRange right)\n {\n return left.Equals(right);\n }\n\n /// \n /// Determines if two instances of are different.\n /// \n public static bool operator !=(TextChangeRange left, TextChangeRange right)\n {\n return !(left == right);\n }\n\n /// \n /// An empty set of changes.\n /// \n public static IReadOnlyList NoChanges => SpecializedCollections.EmptyReadOnlyList();\n\n /// \n /// Collapse a set of s into a single encompassing range. If\n /// the set of ranges provided is empty, an empty range is returned.\n /// \n public static TextChangeRange Collapse(IEnumerable changes)\n {\n var diff = 0;\n var start = int.MaxValue;\n var end = 0;\n\n foreach (var change in changes)\n {\n diff += change.NewLength - change.Span.Length;\n\n if (change.Span.Start < start)\n {\n start = change.Span.Start;\n }\n\n if (change.Span.End > end)\n {\n end = change.Span.End;\n }\n }\n\n if (start > end)\n {\n // there were no changes.\n return default(TextChangeRange);\n }\n\n var combined = TextSpan.FromBounds(start, end);\n var newLen = combined.Length + diff;\n\n return new TextChangeRange(combined, newLen);\n }\n\n private string GetDebuggerDisplay()\n {\n return $\"new TextChangeRange(new TextSpan({Span.Start}, {Span.Length}), {NewLength})\";\n }\n\n public override string ToString()\n {\n return $\"TextChangeRange(Span={Span}, NewLength={NewLength})\";\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":467,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Scanner.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Roslyn.Utilities;\nusing System;\nusing System.Diagnostics;\n\nnamespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator\n{\n internal sealed partial class MemberSignatureParser\n {\n private enum TokenKind\n {\n OpenParen = '(',\n CloseParen = ')',\n Dot = '.',\n Comma = ',',\n QuestionMark = '?',\n\n Start = char.MaxValue + 1,\n End,\n Identifier,\n Keyword,\n }\n\n [DebuggerDisplay(\"{GetDebuggerDisplay(), nq}\")]\n private struct Token\n {\n internal readonly TokenKind Kind;\n internal readonly string Text;\n internal readonly SyntaxKind KeywordKind;\n\n internal Token(TokenKind kind, string text = null, SyntaxKind keywordKind = SyntaxKind.None)\n {\n Kind = kind;\n Text = text;\n KeywordKind = keywordKind;\n }\n\n private string GetDebuggerDisplay()\n {\n return (Text == null) ?\n Kind.ToString() :\n $\"{Kind}: \\\"{Text}\\\"\";\n }\n }\n\n private sealed class Scanner\n {\n private readonly string _text;\n private int _offset;\n private Token _currentToken;\n\n internal Scanner(string text)\n {\n _text = text;\n _offset = 0;\n _currentToken = default(Token);\n }\n\n internal Token CurrentToken\n {\n get\n {\n if (_currentToken.Kind == TokenKind.Start)\n {\n throw new InvalidOperationException();\n }\n return _currentToken;\n }\n }\n\n internal void MoveNext()\n {\n _currentToken = Scan();\n }\n\n private Token Scan()\n {\n int length = _text.Length;\n while (_offset < length && char.IsWhiteSpace(_text[_offset]))\n {\n _offset++;\n }\n\n if (_offset == length)\n {\n return new Token(TokenKind.End);\n }\n\n int n = ScanIdentifier();\n if (n > 0)\n {\n var text = _text.Substring(_offset, n);\n _offset += n;\n if (Keywords.Contains(text))\n {\n var keywordKind = SyntaxKind.None;\n KeywordKinds.TryGetValue(text, out keywordKind);\n return new Token(TokenKind.Keyword, text, keywordKind);\n }\n return new Token(TokenKind.Identifier, text);\n }\n\n var c = _text[_offset++];\n if (c == '[')\n {\n n = ScanIdentifier();\n if (n > 0 && _offset + n < length && _text[_offset + n] == ']')\n {\n // A verbatim identifier. Treat the '[' and ']' as part\n // of the token, but not part of the text.\n var text = _text.Substring(_offset, n);\n _offset += n + 1;\n return new Token(TokenKind.Identifier, text);\n }\n }\n\n return new Token((TokenKind)c);\n }\n\n // Returns the number of characters in the\n // identifier starting at the current offset.\n private int ScanIdentifier()\n {\n int length = _text.Length - _offset;\n if (length > 0 && UnicodeCharacterUtilities.IsIdentifierStartCharacter(_text[_offset]))\n {\n int n = 1;\n while (n < length && UnicodeCharacterUtilities.IsIdentifierPartCharacter(_text[_offset + n]))\n {\n n++;\n }\n return n;\n }\n return 0;\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Roslyn.Utilities;\nusing System;\nusing System.Diagnostics;\n\nnamespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator\n{\n internal sealed partial class MemberSignatureParser\n {\n private enum TokenKind\n {\n OpenParen = '(',\n CloseParen = ')',\n Dot = '.',\n Comma = ',',\n QuestionMark = '?',\n\n Start = char.MaxValue + 1,\n End,\n Identifier,\n Keyword,\n }\n\n [DebuggerDisplay(\"{GetDebuggerDisplay(), nq}\")]\n private struct Token\n {\n internal readonly TokenKind Kind;\n internal readonly string Text;\n internal readonly SyntaxKind KeywordKind;\n\n internal Token(TokenKind kind, string text = null, SyntaxKind keywordKind = SyntaxKind.None)\n {\n Kind = kind;\n Text = text;\n KeywordKind = keywordKind;\n }\n\n private string GetDebuggerDisplay()\n {\n return (Text == null) ?\n Kind.ToString() :\n $\"{Kind}: \\\"{Text}\\\"\";\n }\n }\n\n private sealed class Scanner\n {\n private readonly string _text;\n private int _offset;\n private Token _currentToken;\n\n internal Scanner(string text)\n {\n _text = text;\n _offset = 0;\n _currentToken = default(Token);\n }\n\n internal Token CurrentToken\n {\n get\n {\n if (_currentToken.Kind == TokenKind.Start)\n {\n throw new InvalidOperationException();\n }\n return _currentToken;\n }\n }\n\n internal void MoveNext()\n {\n _currentToken = Scan();\n }\n\n private Token Scan()\n {\n int length = _text.Length;\n while (_offset < length && char.IsWhiteSpace(_text[_offset]))\n {\n _offset++;\n }\n\n if (_offset == length)\n {\n return new Token(TokenKind.End);\n }\n\n int n = ScanIdentifier();\n if (n > 0)\n {\n var text = _text.Substring(_offset, n);\n _offset += n;\n if (Keywords.Contains(text))\n {\n var keywordKind = SyntaxKind.None;\n KeywordKinds.TryGetValue(text, out keywordKind);\n return new Token(TokenKind.Keyword, text, keywordKind);\n }\n return new Token(TokenKind.Identifier, text);\n }\n\n var c = _text[_offset++];\n if (c == '[')\n {\n n = ScanIdentifier();\n if (n > 0 && _offset + n < length && _text[_offset + n] == ']')\n {\n // A verbatim identifier. Treat the '[' and ']' as part\n // of the token, but not part of the text.\n var text = _text.Substring(_offset, n);\n _offset += n + 1;\n return new Token(TokenKind.Identifier, text);\n }\n }\n\n return new Token((TokenKind)c);\n }\n\n // Returns the number of characters in the\n // identifier starting at the current offset.\n private int ScanIdentifier()\n {\n int length = _text.Length - _offset;\n if (length > 0 && UnicodeCharacterUtilities.IsIdentifierStartCharacter(_text[_offset]))\n {\n int n = 1;\n while (n < length && UnicodeCharacterUtilities.IsIdentifierPartCharacter(_text[_offset + n]))\n {\n n++;\n }\n return n;\n }\n return 0;\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":468,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/Placeholders.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis.CSharp;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal static class GreenNode\n {\n /// \n /// Required by .\n /// \n public const int ListKind = 1;\n }\n}\n\n// This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed.\nnamespace System.Runtime.CompilerServices\n{\n [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]\n internal class ExtensionAttribute : Attribute\n {\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing Microsoft.CodeAnalysis.CSharp;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal static class GreenNode\n {\n /// \n /// Required by .\n /// \n public const int ListKind = 1;\n }\n}\n\n// This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed.\nnamespace System.Runtime.CompilerServices\n{\n [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]\n internal class ExtensionAttribute : Attribute\n {\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":469,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/ExtractMethod/MethodExtractor.TriviaResult.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ExtractMethod\n{\n internal abstract partial class MethodExtractor\n {\n protected abstract class TriviaResult\n {\n private readonly int _endOfLineKind;\n private readonly int _whitespaceKind;\n\n private readonly ITriviaSavedResult _result;\n\n public TriviaResult(SemanticDocument document, ITriviaSavedResult result, int endOfLineKind, int whitespaceKind)\n {\n SemanticDocument = document;\n\n _result = result;\n _endOfLineKind = endOfLineKind;\n _whitespaceKind = whitespaceKind;\n }\n\n protected abstract AnnotationResolver GetAnnotationResolver(SyntaxNode callsite, SyntaxNode methodDefinition);\n protected abstract TriviaResolver GetTriviaResolver(SyntaxNode methodDefinition);\n\n public SemanticDocument SemanticDocument { get; }\n\n public async Task> ApplyAsync(GeneratedCode generatedCode, CancellationToken cancellationToken)\n {\n var document = generatedCode.SemanticDocument;\n var root = document.Root;\n\n var callsiteAnnotation = generatedCode.CallSiteAnnotation;\n var methodDefinitionAnnotation = generatedCode.MethodDefinitionAnnotation;\n\n var callsite = root.GetAnnotatedNodesAndTokens(callsiteAnnotation).SingleOrDefault().AsNode();\n var method = root.GetAnnotatedNodesAndTokens(methodDefinitionAnnotation).SingleOrDefault().AsNode();\n\n var annotationResolver = GetAnnotationResolver(callsite, method);\n var triviaResolver = GetTriviaResolver(method);\n if (annotationResolver == null || triviaResolver == null)\n {\n // bug # 6644\n // this could happen in malformed code. return as it was.\n var status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.can_t_not_construct_final_tree);\n return status.With(document);\n }\n\n return OperationStatus.Succeeded.With(\n await document.WithSyntaxRootAsync(_result.RestoreTrivia(root, annotationResolver, triviaResolver), cancellationToken).ConfigureAwait(false));\n }\n\n protected IEnumerable FilterTriviaList(IEnumerable list)\n {\n // has noisy token\n if (list.Any(t => t.RawKind != _endOfLineKind && t.RawKind != _whitespaceKind))\n {\n return RemoveLeadingElasticBeforeEndOfLine(list);\n }\n\n // whitespace only\n return MergeLineBreaks(list);\n }\n\n protected IEnumerable RemoveBlankLines(IEnumerable list)\n {\n // remove any blank line at the beginning\n var currentLine = new List();\n var result = new List();\n\n var seenFirstEndOfLine = false;\n var i = 0;\n\n foreach (var trivia in list)\n {\n i++;\n\n if (trivia.RawKind == _endOfLineKind)\n {\n if (seenFirstEndOfLine)\n {\n // empty line. remove it\n if (currentLine.All(t => t.RawKind == _endOfLineKind || t.RawKind == _whitespaceKind))\n {\n continue;\n }\n\n // non empty line after the first end of line.\n // return now\n return result.Concat(currentLine).Concat(list.Skip(i - 1));\n }\n else\n {\n seenFirstEndOfLine = true;\n\n result.AddRange(currentLine);\n result.Add(trivia);\n currentLine.Clear();\n\n continue;\n }\n }\n\n currentLine.Add(trivia);\n }\n\n return result.Concat(currentLine);\n }\n\n protected IEnumerable RemoveLeadingElasticBeforeEndOfLine(IEnumerable list)\n {\n var trivia = list.FirstOrDefault();\n if (!trivia.IsElastic())\n {\n return list;\n }\n\n var listWithoutHead = list.Skip(1);\n trivia = listWithoutHead.FirstOrDefault();\n if (trivia.RawKind == _endOfLineKind)\n {\n return listWithoutHead;\n }\n\n if (trivia.IsElastic())\n {\n return RemoveLeadingElasticBeforeEndOfLine(listWithoutHead);\n }\n\n return list;\n }\n\n protected IEnumerable MergeLineBreaks(IEnumerable list)\n {\n // this will make sure that it doesn't have more than two subsequent end of line\n // trivia without any noisy trivia\n var stack = new Stack();\n var numberOfEndOfLinesWithoutAnyNoisyTrivia = 0;\n\n foreach (var trivia in list)\n {\n if (trivia.IsElastic())\n {\n stack.Push(trivia);\n continue;\n }\n\n if (trivia.RawKind == _endOfLineKind)\n {\n numberOfEndOfLinesWithoutAnyNoisyTrivia++;\n\n if (numberOfEndOfLinesWithoutAnyNoisyTrivia > 2)\n {\n // get rid of any whitespace trivia from stack\n var top = stack.Peek();\n while (!top.IsElastic() && top.RawKind == _whitespaceKind)\n {\n stack.Pop();\n top = stack.Peek();\n }\n\n continue;\n }\n }\n\n stack.Push(trivia);\n }\n\n return stack.Reverse();\n }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.ExtractMethod\n{\n internal abstract partial class MethodExtractor\n {\n protected abstract class TriviaResult\n {\n private readonly int _endOfLineKind;\n private readonly int _whitespaceKind;\n\n private readonly ITriviaSavedResult _result;\n\n public TriviaResult(SemanticDocument document, ITriviaSavedResult result, int endOfLineKind, int whitespaceKind)\n {\n SemanticDocument = document;\n\n _result = result;\n _endOfLineKind = endOfLineKind;\n _whitespaceKind = whitespaceKind;\n }\n\n protected abstract AnnotationResolver GetAnnotationResolver(SyntaxNode callsite, SyntaxNode methodDefinition);\n protected abstract TriviaResolver GetTriviaResolver(SyntaxNode methodDefinition);\n\n public SemanticDocument SemanticDocument { get; }\n\n public async Task> ApplyAsync(GeneratedCode generatedCode, CancellationToken cancellationToken)\n {\n var document = generatedCode.SemanticDocument;\n var root = document.Root;\n\n var callsiteAnnotation = generatedCode.CallSiteAnnotation;\n var methodDefinitionAnnotation = generatedCode.MethodDefinitionAnnotation;\n\n var callsite = root.GetAnnotatedNodesAndTokens(callsiteAnnotation).SingleOrDefault().AsNode();\n var method = root.GetAnnotatedNodesAndTokens(methodDefinitionAnnotation).SingleOrDefault().AsNode();\n\n var annotationResolver = GetAnnotationResolver(callsite, method);\n var triviaResolver = GetTriviaResolver(method);\n if (annotationResolver == null || triviaResolver == null)\n {\n // bug # 6644\n // this could happen in malformed code. return as it was.\n var status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.can_t_not_construct_final_tree);\n return status.With(document);\n }\n\n return OperationStatus.Succeeded.With(\n await document.WithSyntaxRootAsync(_result.RestoreTrivia(root, annotationResolver, triviaResolver), cancellationToken).ConfigureAwait(false));\n }\n\n protected IEnumerable FilterTriviaList(IEnumerable list)\n {\n // has noisy token\n if (list.Any(t => t.RawKind != _endOfLineKind && t.RawKind != _whitespaceKind))\n {\n return RemoveLeadingElasticBeforeEndOfLine(list);\n }\n\n // whitespace only\n return MergeLineBreaks(list);\n }\n\n protected IEnumerable RemoveBlankLines(IEnumerable list)\n {\n // remove any blank line at the beginning\n var currentLine = new List();\n var result = new List();\n\n var seenFirstEndOfLine = false;\n var i = 0;\n\n foreach (var trivia in list)\n {\n i++;\n\n if (trivia.RawKind == _endOfLineKind)\n {\n if (seenFirstEndOfLine)\n {\n // empty line. remove it\n if (currentLine.All(t => t.RawKind == _endOfLineKind || t.RawKind == _whitespaceKind))\n {\n continue;\n }\n\n // non empty line after the first end of line.\n // return now\n return result.Concat(currentLine).Concat(list.Skip(i - 1));\n }\n else\n {\n seenFirstEndOfLine = true;\n\n result.AddRange(currentLine);\n result.Add(trivia);\n currentLine.Clear();\n\n continue;\n }\n }\n\n currentLine.Add(trivia);\n }\n\n return result.Concat(currentLine);\n }\n\n protected IEnumerable RemoveLeadingElasticBeforeEndOfLine(IEnumerable list)\n {\n var trivia = list.FirstOrDefault();\n if (!trivia.IsElastic())\n {\n return list;\n }\n\n var listWithoutHead = list.Skip(1);\n trivia = listWithoutHead.FirstOrDefault();\n if (trivia.RawKind == _endOfLineKind)\n {\n return listWithoutHead;\n }\n\n if (trivia.IsElastic())\n {\n return RemoveLeadingElasticBeforeEndOfLine(listWithoutHead);\n }\n\n return list;\n }\n\n protected IEnumerable MergeLineBreaks(IEnumerable list)\n {\n // this will make sure that it doesn't have more than two subsequent end of line\n // trivia without any noisy trivia\n var stack = new Stack();\n var numberOfEndOfLinesWithoutAnyNoisyTrivia = 0;\n\n foreach (var trivia in list)\n {\n if (trivia.IsElastic())\n {\n stack.Push(trivia);\n continue;\n }\n\n if (trivia.RawKind == _endOfLineKind)\n {\n numberOfEndOfLinesWithoutAnyNoisyTrivia++;\n\n if (numberOfEndOfLinesWithoutAnyNoisyTrivia > 2)\n {\n // get rid of any whitespace trivia from stack\n var top = stack.Peek();\n while (!top.IsElastic() && top.RawKind == _whitespaceKind)\n {\n stack.Pop();\n top = stack.Peek();\n }\n\n continue;\n }\n }\n\n stack.Push(trivia);\n }\n\n return stack.Reverse();\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":470,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56471,"string":"56,471"},"pr_title":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction"},"pr_description":{"kind":"string","value":"This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-17T01:20:35Z","string":"2021-09-17T01:20:35Z"},"date_merged":{"kind":"timestamp","value":"2021-09-20T18:04:19Z","string":"2021-09-20T18:04:19Z"},"previous_commit":{"kind":"string","value":"28ede84feaf2dfee3ca77d0e05ee80bd7374e49f"},"pr_commit":{"kind":"string","value":"f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f"},"query":{"kind":"string","value":"Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with.\r\n\r\n* Move Inheritance Margin context menu to a separate control (lazily initialized)\r\n* Initialize Inheritance Margin glyphs in code; eliminate BAML parsing\r\n* Optimize one-way bindings for Inheritance Margin glyphs"},"filepath":{"kind":"string","value":"./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.SymbolSearch.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing Microsoft.CodeAnalysis.SymbolSearch;\n\nnamespace Microsoft.VisualStudio.LanguageServices.CSharp.Options\n{\n public partial class AutomationObject\n {\n public int AddImport_SuggestForTypesInReferenceAssemblies\n {\n get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); }\n set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); }\n }\n\n public int AddImport_SuggestForTypesInNuGetPackages\n {\n get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); }\n set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value); }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing Microsoft.CodeAnalysis.SymbolSearch;\n\nnamespace Microsoft.VisualStudio.LanguageServices.CSharp.Options\n{\n public partial class AutomationObject\n {\n public int AddImport_SuggestForTypesInReferenceAssemblies\n {\n get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); }\n set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); }\n }\n\n public int AddImport_SuggestForTypesInNuGetPackages\n {\n get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); }\n set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value); }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":471,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj"},"before_content":{"kind":"string","value":"\n\n\n \n 14.0\n Library\n Microsoft.CodeAnalysis.BuildTasks\n en-US\n netcoreapp3.1;net472\n true\n \n \n $(NoWarn);CA1819\n \n \n true\n Microsoft.CodeAnalysis.Build.Tasks\n\n \n The build task and targets used by MSBuild to run the C# and VB compilers.\n Supports using VBCSCompiler on Windows.\n \n true\n \n\n \n \n PreserveNewest\n true\n None\n true\n contentFiles\\any\\any\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},"after_content":{"kind":"string","value":"\n\n\n \n 14.0\n Library\n Microsoft.CodeAnalysis.BuildTasks\n en-US\n netcoreapp3.1;net472\n true\n \n \n $(NoWarn);CA1819\n \n \n true\n Microsoft.CodeAnalysis.Build.Tasks\n\n \n The build task and targets used by MSBuild to run the C# and VB compilers.\n Supports using VBCSCompiler on Windows.\n \n true\n \n\n \n \n PreserveNewest\n true\n None\n true\n contentFiles\\any\\any\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n $(IntermediateOutputPath)Microsoft.Managed.Core.CurrentVersions.targets\n \n\n \n \n \n PreserveNewest\n true\n None\n true\n contentFiles\\any\\any\n \n \n \n\n \n\n \n $([System.Version]::Parse($(VersionPrefix)).Major).$([System.Version]::Parse($(VersionPrefix)).Minor)\n \n\n \n roslyn$(CompilerApiVersion)\n \n]]>\n \n \n\n \n \n\n \n\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":472,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Compilers/Core/MSBuildTask/Microsoft.Managed.Core.targets"},"before_content":{"kind":"string","value":"\n\n\n \n \n\n \n \n \n \n \n \n\n \n\n \n \n \n \n \n\n \n \n false\n \n\n \n \n \n \n \n\n \n true\n \n \n\n \n \n\n \n \n \n <_SkipAnalyzers>\n <_ImplicitlySkipAnalyzers>\n \n\n \n \n <_SkipAnalyzers>true\n \n\n \n \n <_ImplicitlySkipAnalyzers>true\n <_SkipAnalyzers>true\n run-nullable-analysis=never;$(Features)\n \n\n \n \n\n \n \n <_LastBuildWithSkipAnalyzers>$(IntermediateOutputPath)$(MSBuildProjectFile).BuildWithSkipAnalyzers\n \n\n \n \n \n \n \n \n\n \n \n \n \n\n \n \n <_AllDirectoriesAbove Include=\"@(Compile->GetPathsOfAllDirectoriesAbove())\" Condition=\"'$(DiscoverEditorConfigFiles)' != 'false' or '$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'\" />\n \n '%(FullPath)'->Distinct()->Combine('.editorconfig'))\" Condition=\"'$(DiscoverEditorConfigFiles)' != 'false'\" />\n Exists())\" Condition=\"'$(DiscoverEditorConfigFiles)' != 'false'\" />\n \n '%(FullPath)'->Distinct()->Combine('.globalconfig'))\" Condition=\"'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'\" />\n Exists())\" Condition=\"'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'\" />\n \n\n \n \n\n \n\n \n \n $(IntermediateOutputPath)$(MSBuildProjectName).GeneratedMSBuildEditorConfig.editorconfig\n true\n <_GeneratedEditorConfigHasItems Condition=\"'@(CompilerVisibleItemMetadata->Count())' != '0'\">true\n <_GeneratedEditorConfigShouldRun Condition=\"'$(GenerateMSBuildEditorConfigFile)' == 'true' and ('$(_GeneratedEditorConfigHasItems)' == 'true' or '@(CompilerVisibleProperty->Count())' != '0')\">true\n \n \n\n \n\n \n \n <_GeneratedEditorConfigProperty Include=\"@(CompilerVisibleProperty)\">\n $(%(CompilerVisibleProperty.Identity))\n \n\n \n <_GeneratedEditorConfigMetadata Include=\"@(%(CompilerVisibleItemMetadata.Identity))\" Condition=\"'$(_GeneratedEditorConfigHasItems)' == 'true'\">\n %(Identity)\n %(CompilerVisibleItemMetadata.MetadataName)\n \n\n \n \n \n \n\n \n \n \n\n \n\n \n \n true\n \n\n \n\n \n\n \n <_MappedSourceRoot Remove=\"@(_MappedSourceRoot)\" />\n \n\n \n \n \n\n \n \n \n \n \n\n \n \n true\n \n\n \n \n\n \n\n \n\n \n <_TopLevelSourceRoot Include=\"@(SourceRoot)\" Condition=\"'%(SourceRoot.NestedRoot)' == ''\">\n $([MSBuild]::ValueOrDefault('%(Identity)', '').Replace(',', ',,').Replace('=', '=='))\n $([MSBuild]::ValueOrDefault('%(MappedPath)', '').Replace(',', ',,').Replace('=', '=='))\n \n \n\n \n \n @(_TopLevelSourceRoot->'%(EscapedKey)=%(EscapedValue)', ','),$(PathMap)\n \n \n\n \n\n \n \n \n \n \n\n \n \n false\n \n $(IntermediateOutputPath)/generated\n \n\n \n\n \n \n \n \n\n \n \n \n \n\n"},"after_content":{"kind":"string","value":"\n\n\n \n \n\n \n\n \n \n \n \n \n \n\n \n\n \n \n \n \n \n\n \n \n false\n \n\n \n \n \n \n \n\n \n true\n \n \n\n \n \n\n \n \n \n <_SkipAnalyzers>\n <_ImplicitlySkipAnalyzers>\n \n\n \n \n <_SkipAnalyzers>true\n \n\n \n \n <_ImplicitlySkipAnalyzers>true\n <_SkipAnalyzers>true\n run-nullable-analysis=never;$(Features)\n \n\n \n \n\n \n \n <_LastBuildWithSkipAnalyzers>$(IntermediateOutputPath)$(MSBuildProjectFile).BuildWithSkipAnalyzers\n \n\n \n \n \n \n \n \n\n \n \n \n \n\n \n \n <_AllDirectoriesAbove Include=\"@(Compile->GetPathsOfAllDirectoriesAbove())\" Condition=\"'$(DiscoverEditorConfigFiles)' != 'false' or '$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'\" />\n \n '%(FullPath)'->Distinct()->Combine('.editorconfig'))\" Condition=\"'$(DiscoverEditorConfigFiles)' != 'false'\" />\n Exists())\" Condition=\"'$(DiscoverEditorConfigFiles)' != 'false'\" />\n \n '%(FullPath)'->Distinct()->Combine('.globalconfig'))\" Condition=\"'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'\" />\n Exists())\" Condition=\"'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'\" />\n \n\n \n \n\n \n\n \n \n $(IntermediateOutputPath)$(MSBuildProjectName).GeneratedMSBuildEditorConfig.editorconfig\n true\n <_GeneratedEditorConfigHasItems Condition=\"'@(CompilerVisibleItemMetadata->Count())' != '0'\">true\n <_GeneratedEditorConfigShouldRun Condition=\"'$(GenerateMSBuildEditorConfigFile)' == 'true' and ('$(_GeneratedEditorConfigHasItems)' == 'true' or '@(CompilerVisibleProperty->Count())' != '0')\">true\n \n \n\n \n\n \n \n <_GeneratedEditorConfigProperty Include=\"@(CompilerVisibleProperty)\">\n $(%(CompilerVisibleProperty.Identity))\n \n\n \n <_GeneratedEditorConfigMetadata Include=\"@(%(CompilerVisibleItemMetadata.Identity))\" Condition=\"'$(_GeneratedEditorConfigHasItems)' == 'true'\">\n %(Identity)\n %(CompilerVisibleItemMetadata.MetadataName)\n \n\n \n \n \n \n\n \n \n \n\n \n\n \n \n true\n \n\n \n\n \n\n \n <_MappedSourceRoot Remove=\"@(_MappedSourceRoot)\" />\n \n\n \n \n \n\n \n \n \n \n \n\n \n \n true\n \n\n \n \n\n \n\n \n\n \n <_TopLevelSourceRoot Include=\"@(SourceRoot)\" Condition=\"'%(SourceRoot.NestedRoot)' == ''\">\n $([MSBuild]::ValueOrDefault('%(Identity)', '').Replace(',', ',,').Replace('=', '=='))\n $([MSBuild]::ValueOrDefault('%(MappedPath)', '').Replace(',', ',,').Replace('=', '=='))\n \n \n\n \n \n @(_TopLevelSourceRoot->'%(EscapedKey)=%(EscapedValue)', ','),$(PathMap)\n \n \n\n \n\n \n \n \n \n \n\n \n \n false\n \n $(IntermediateOutputPath)/generated\n \n\n \n\n \n \n \n \n\n \n \n \n \n\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":473,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Compilers/Core/MSBuildTaskTests/Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj"},"before_content":{"kind":"string","value":"\n\n\n \n Library\n Microsoft.CodeAnalysis.BuildTasks.UnitTests\n true\n net5.0;net472\n\n \n true\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n <_DotNetSdkVersionFile>$(IntermediateOutputPath)\\DotNetSdkVersion.g.cs\n \n \n \n <_Attribute Include=\"Microsoft.CodeAnalysis.BuildTasks.UnitTests.DotNetSdkVersionAttribute\">\n <_Parameter1>$(NETCoreSdkVersion)\n \n \n \n \n \n \n \n\n"},"after_content":{"kind":"string","value":"\n\n\n \n Library\n Microsoft.CodeAnalysis.BuildTasks.UnitTests\n true\n net5.0;net472\n\n \n true\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n <_DotNetSdkVersionFile>$(IntermediateOutputPath)\\DotNetVersions.g.cs\n \n \n \n <_Attribute Include=\"Microsoft.CodeAnalysis.BuildTasks.UnitTests.DotNetSdkVersionAttribute\">\n <_Parameter1>$(NETCoreSdkVersion)\n \n <_Attribute Include=\"System.Reflection.AssemblyMetadataAttribute\">\n <_Parameter1>CurrentCompilerApiVersion\n <_Parameter2>$([System.Version]::Parse($(VersionPrefix)).Major).$([System.Version]::Parse($(VersionPrefix)).Minor)\n \n \n \n \n \n \n \n\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":474,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Compilers/Core/MSBuildTaskTests/TargetTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n// uncomment the below define to dump binlogs of each test\n//#define DUMP_MSBUILD_BIN_LOG\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Xml;\nusing Roslyn.Test.Utilities;\nusing Microsoft.Build.Evaluation;\nusing Microsoft.Build.Execution;\nusing Microsoft.Build.Framework;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.BuildTasks.UnitTests\n{\n public class TargetTests : TestBase\n {\n [Fact]\n public void GenerateEditorConfigShouldNotRunWhenNoPropertiesOrMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.NotEqual(\"true\", shouldRun);\n Assert.NotEqual(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigShouldRunWhenPropertiesRequested()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.Equal(\"true\", shouldRun);\n Assert.NotEqual(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigShouldRunWhenMetadataRequested()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.Equal(\"true\", shouldRun);\n Assert.Equal(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigShouldRunWhenPropertiesAndMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.Equal(\"true\", shouldRun);\n Assert.Equal(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigCanBeDisabled()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n false\n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.NotEqual(\"true\", shouldRun);\n Assert.Equal(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesProperties()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n abc\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigProperty\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigProperty\", item.ItemType);\n Assert.Single(item.Metadata);\n\n var metadata = item.Metadata.Single();\n Assert.Equal(\"Value\", metadata.Name);\n Assert.Equal(\"abc\", metadata.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesDynamicProperties()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n def\n $(RealValue)\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigProperty\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigProperty\", item.ItemType);\n Assert.Single(item.Metadata);\n\n var metadata = item.Metadata.Single();\n Assert.Equal(\"Value\", metadata.Name);\n Assert.Equal(\"def\", metadata.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreHandlesMissingProperties()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigProperty\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigProperty\", item.ItemType);\n Assert.Single(item.Metadata);\n\n var metadata = item.Metadata.Single();\n Assert.Equal(\"Value\", metadata.Name);\n Assert.Equal(\"\", metadata.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"CustomMeta\", metaName.EvaluatedValue);\n\n var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue);\n AssertEx.NotNull(customMeta);\n Assert.Equal(\"abc\", customMeta.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesDynamicMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n abc\n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"CustomMeta\", metaName.EvaluatedValue);\n\n var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue);\n AssertEx.NotNull(customMeta);\n Assert.Equal(\"abc\", customMeta.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreHandlesMissingMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"CustomMeta\", metaName.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreHandlesMalformedCompilerVisibleItemMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"\", metaName.EvaluatedValue);\n }\n\n [Theory]\n [InlineData(\".NETFramework\", \"4.5\", \"7.3\")]\n [InlineData(\".NETFramework\", \"4.7.2\", \"7.3\")]\n [InlineData(\".NETFramework\", \"4.8\", \"7.3\")]\n\n [InlineData(\".NETCoreApp\", \"1.0\", \"7.3\")]\n [InlineData(\".NETCoreApp\", \"2.0\", \"7.3\")]\n [InlineData(\".NETCoreApp\", \"2.1\", \"7.3\")]\n [InlineData(\".NETCoreApp\", \"3.0\", \"8.0\")]\n [InlineData(\".NETCoreApp\", \"3.1\", \"8.0\")]\n [InlineData(\".NETCoreApp\", \"5.0\", \"9.0\")]\n [InlineData(\".NETCoreApp\", \"6.0\", \"10.0\")]\n [InlineData(\".NETCoreApp\", \"7.0\", \"\")]\n\n [InlineData(\".NETStandard\", \"1.0\", \"7.3\")]\n [InlineData(\".NETStandard\", \"1.5\", \"7.3\")]\n [InlineData(\".NETStandard\", \"2.0\", \"7.3\")]\n [InlineData(\".NETStandard\", \"2.1\", \"8.0\")]\n\n [InlineData(\"UnknownTFM\", \"0.0\", \"7.3\")]\n [InlineData(\"UnknownTFM\", \"5.0\", \"7.3\")]\n [InlineData(\"UnknownTFM\", \"6.0\", \"7.3\")]\n public void LanguageVersionGivenTargetFramework(string tfi, string tfv, string expectedVersion)\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n {tfi}\n <_TargetFrameworkVersionWithoutV>{tfv}\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n\n Assert.Equal(expectedVersion, langVersion);\n Assert.Equal(expectedVersion, maxLangVersion);\n\n // This will fail whenever the current language version is updated.\n // Ensure you update the target files to select the correct CSharp version for the newest target framework\n // and add to the theory data above to cover it, before changing this version to make the test pass again.\n Assert.Equal(CSharp.LanguageVersion.CSharp10, CSharp.LanguageVersionFacts.CurrentVersion);\n }\n\n [Fact]\n public void ExplicitLangVersion()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n .NETCoreApp\n <_TargetFrameworkVersionWithoutV>2.0\n 55.0\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n\n Assert.Equal(\"55.0\", langVersion);\n Assert.Equal(\"7.3\", maxLangVersion);\n }\n\n [Fact]\n public void MaxSupportedLangVersionIsReadable()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n .NETCoreApp\n <_TargetFrameworkVersionWithoutV>2.0\n 9.0\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n var publicMaxLangVersion = instance.GetPropertyValue(\"MaxSupportedLangVersion\");\n\n Assert.Equal(\"9.0\", langVersion);\n Assert.Equal(\"7.3\", maxLangVersion);\n Assert.Equal(\"7.3\", publicMaxLangVersion);\n }\n\n [Fact]\n public void MaxSupportedLangVersionIsnotWriteable()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n .NETCoreApp\n <_TargetFrameworkVersionWithoutV>2.0\n 9.0 \n 9.0\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n var publicMaxLangVersion = instance.GetPropertyValue(\"MaxSupportedLangVersion\");\n\n Assert.Equal(\"9.0\", langVersion);\n Assert.Equal(\"7.3\", maxLangVersion);\n Assert.Equal(\"7.3\", publicMaxLangVersion);\n }\n\n [Fact]\n public void GenerateEditorConfigIsPassedToTheCompiler()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"EditorConfigFiles\");\n Assert.Single(items);\n }\n\n [Fact]\n public void AdditionalFilesAreAddedToNoneWhenCopied()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n \n\n\"));\n var instance = CreateProjectInstance(xmlReader);\n bool runSuccess = instance.Build(target: \"CopyAdditionalFiles\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var noneItems = instance.GetItems(\"None\").ToArray();\n Assert.Equal(3, noneItems.Length);\n\n Assert.Equal(\"file1.cs\", noneItems[0].EvaluatedInclude);\n Assert.Equal(\"Always\", noneItems[0].GetMetadataValue(\"CopyToOutputDirectory\"));\n\n Assert.Equal(\"file2.cs\", noneItems[1].EvaluatedInclude);\n Assert.Equal(\"PreserveNewest\", noneItems[1].GetMetadataValue(\"CopyToOutputDirectory\"));\n\n Assert.Equal(\"file3.cs\", noneItems[2].EvaluatedInclude);\n Assert.Equal(\"Never\", noneItems[2].GetMetadataValue(\"CopyToOutputDirectory\"));\n }\n\n [Fact]\n public void GeneratedFilesOutputPathHasDefaults()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(\"false\", emit);\n Assert.Equal(string.Empty, dir);\n }\n\n [Fact]\n public void GeneratedFilesOutputPathDefaultsToIntermediateOutputPathWhenSet()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n fallbackDirectory\n true\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"CreateCompilerGeneratedFilesOutputPath\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(\"true\", emit);\n Assert.Equal(\"fallbackDirectory/generated\", dir);\n }\n\n [Fact]\n public void GeneratedFilesOutputPathDefaultsIsEmptyWhenEmitDisable()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n false\n fallbackDirectory\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(\"false\", emit);\n Assert.Equal(string.Empty, dir);\n }\n\n [Theory]\n [InlineData(true, \"generatedDirectory\")]\n [InlineData(true, null)]\n [InlineData(false, \"generatedDirectory\")]\n [InlineData(false, null)]\n public void GeneratedFilesOutputPathCanBeSetAndSuppressed(bool emitGeneratedFiles, string? generatedFilesDir)\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n {(emitGeneratedFiles.ToString().ToLower())}\n {generatedFilesDir}\n fallbackDirectory\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"CreateCompilerGeneratedFilesOutputPath\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(emitGeneratedFiles.ToString().ToLower(), emit);\n if (emitGeneratedFiles)\n {\n string expectedDir = generatedFilesDir ?? \"fallbackDirectory/generated\";\n Assert.Equal(expectedDir, dir);\n }\n else\n {\n Assert.Equal(string.Empty, dir);\n }\n }\n\n [Theory, CombinatorialData]\n [WorkItem(40926, \"https://github.com/dotnet/roslyn/issues/40926\")]\n public void TestSkipAnalyzers(\n [CombinatorialValues(true, false, null)] bool? runAnalyzers,\n [CombinatorialValues(true, false, null)] bool? runAnalyzersDuringBuild)\n {\n var runAnalyzersPropertyGroupString = getPropertyGroup(\"RunAnalyzers\", runAnalyzers);\n var runAnalyzersDuringBuildPropertyGroupString = getPropertyGroup(\"RunAnalyzersDuringBuild\", runAnalyzersDuringBuild);\n\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n{runAnalyzersPropertyGroupString}\n{runAnalyzersDuringBuildPropertyGroupString}\n\n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"_ComputeSkipAnalyzers\", GetTestLoggers());\n Assert.True(runSuccess);\n\n // Verify \"RunAnalyzers\" overrides \"RunAnalyzersDuringBuild\".\n // If neither properties are set, analyzers are enabled by default.\n var analyzersEnabled = runAnalyzers ?? runAnalyzersDuringBuild ?? true;\n\n var expectedSkipAnalyzersValue = !analyzersEnabled ? \"true\" : \"\";\n var actualSkipAnalyzersValue = instance.GetPropertyValue(\"_SkipAnalyzers\");\n Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue);\n return;\n\n static string getPropertyGroup(string propertyName, bool? propertyValue)\n {\n if (!propertyValue.HasValue)\n {\n return string.Empty;\n }\n\n return $@\"\n \n <{propertyName}>{propertyValue.Value}\n \";\n }\n }\n\n [Theory, CombinatorialData]\n [WorkItem(1337109, \"https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109\")]\n public void TestImplicitlySkipAnalyzers(\n [CombinatorialValues(true, false, null)] bool? runAnalyzers,\n [CombinatorialValues(true, false, null)] bool? implicitBuild,\n [CombinatorialValues(true, false, null)] bool? treatWarningsAsErrors,\n [CombinatorialValues(true, false, null)] bool? optimizeImplicitBuild,\n [CombinatorialValues(true, null)] bool? sdkStyleProject)\n {\n var runAnalyzersPropertyGroupString = getPropertyGroup(\"RunAnalyzers\", runAnalyzers);\n var implicitBuildPropertyGroupString = getPropertyGroup(\"IsImplicitlyTriggeredBuild\", implicitBuild);\n var treatWarningsAsErrorsPropertyGroupString = getPropertyGroup(\"TreatWarningsAsErrors\", treatWarningsAsErrors);\n var optimizeImplicitBuildPropertyGroupString = getPropertyGroup(\"OptimizeImplicitlyTriggeredBuild\", optimizeImplicitBuild);\n var sdkStyleProjectPropertyGroupString = getPropertyGroup(\"UsingMicrosoftNETSdk\", sdkStyleProject);\n\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n{runAnalyzersPropertyGroupString}\n{implicitBuildPropertyGroupString}\n{treatWarningsAsErrorsPropertyGroupString}\n{optimizeImplicitBuildPropertyGroupString}\n{sdkStyleProjectPropertyGroupString}\n\n\n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"_ComputeSkipAnalyzers\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var analyzersEnabled = runAnalyzers ?? true;\n var expectedImplicitlySkippedAnalyzers = analyzersEnabled &&\n implicitBuild == true &&\n sdkStyleProject == true &&\n (treatWarningsAsErrors != true || optimizeImplicitBuild == true);\n var expectedImplicitlySkippedAnalyzersValue = expectedImplicitlySkippedAnalyzers ? \"true\" : \"\";\n var actualImplicitlySkippedAnalyzersValue = instance.GetPropertyValue(\"_ImplicitlySkipAnalyzers\");\n Assert.Equal(expectedImplicitlySkippedAnalyzersValue, actualImplicitlySkippedAnalyzersValue);\n\n var expectedSkipAnalyzersValue = !analyzersEnabled || expectedImplicitlySkippedAnalyzers ? \"true\" : \"\";\n var actualSkipAnalyzersValue = instance.GetPropertyValue(\"_SkipAnalyzers\");\n Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue);\n\n var expectedFeaturesValue = expectedImplicitlySkippedAnalyzers ? \"run-nullable-analysis=never;\" : \"\";\n var actualFeaturesValue = instance.GetPropertyValue(\"Features\");\n Assert.Equal(expectedFeaturesValue, actualFeaturesValue);\n return;\n\n static string getPropertyGroup(string propertyName, bool? propertyValue)\n {\n if (!propertyValue.HasValue)\n {\n return string.Empty;\n }\n\n return $@\"\n \n <{propertyName}>{propertyValue.Value}\n \";\n }\n }\n\n [Theory, CombinatorialData]\n [WorkItem(1337109, \"https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109\")]\n public void TestLastBuildWithSkipAnalyzers(\n [CombinatorialValues(true, false, null)] bool? runAnalyzers,\n bool lastBuildWithSkipAnalyzersFileExists)\n {\n var runAnalyzersPropertyGroupString = getPropertyGroup(\"RunAnalyzers\", runAnalyzers);\n var intermediatePathDir = Temp.CreateDirectory();\n var intermediatePath = intermediatePathDir + Path.DirectorySeparatorChar.ToString();\n\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n{runAnalyzersPropertyGroupString}\n\n \n {intermediatePath}\n \n\n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n var msbuildProjectFileName = instance.GetPropertyValue(\"MSBuildProjectFile\");\n var expectedLastBuildWithSkipAnalyzers = intermediatePath + msbuildProjectFileName + \".BuildWithSkipAnalyzers\";\n if (lastBuildWithSkipAnalyzersFileExists)\n {\n _ = intermediatePathDir.CreateFile(msbuildProjectFileName + \".BuildWithSkipAnalyzers\");\n }\n\n bool runSuccess = instance.Build(target: \"_ComputeSkipAnalyzers\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var actualLastBuildWithSkipAnalyzers = instance.GetPropertyValue(\"_LastBuildWithSkipAnalyzers\");\n Assert.Equal(expectedLastBuildWithSkipAnalyzers, actualLastBuildWithSkipAnalyzers);\n\n var skipAnalyzers = !(runAnalyzers ?? true);\n var expectedCustomAdditionalCompileInput = lastBuildWithSkipAnalyzersFileExists && !skipAnalyzers;\n\n var items = instance.GetItems(\"CustomAdditionalCompileInputs\");\n var expectedItemCount = expectedCustomAdditionalCompileInput ? 1 : 0;\n Assert.Equal(expectedItemCount, items.Count);\n if (expectedCustomAdditionalCompileInput)\n {\n Assert.Equal(expectedLastBuildWithSkipAnalyzers, items.Single().EvaluatedInclude);\n }\n\n var expectedUpToDateCheckInput = lastBuildWithSkipAnalyzersFileExists;\n items = instance.GetItems(\"UpToDateCheckInput\");\n expectedItemCount = expectedUpToDateCheckInput ? 1 : 0;\n Assert.Equal(expectedItemCount, items.Count);\n if (expectedUpToDateCheckInput)\n {\n var item = items.Single();\n Assert.Equal(expectedLastBuildWithSkipAnalyzers, item.EvaluatedInclude);\n Assert.Equal(\"ImplicitBuild\", item.GetMetadataValue(\"Kind\"));\n }\n\n return;\n\n static string getPropertyGroup(string propertyName, bool? propertyValue)\n {\n if (!propertyValue.HasValue)\n {\n return string.Empty;\n }\n\n return $@\"\n \n <{propertyName}>{propertyValue.Value}\n \";\n }\n }\n\n [Fact]\n public void ProjectCapabilityIsNotAddedWhenRoslynComponentIsUnspecified()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n var caps = instance.GetItems(\"ProjectCapability\").Select(c => c.EvaluatedInclude);\n Assert.DoesNotContain(\"RoslynComponent\", caps);\n }\n\n [Fact]\n public void ProjectCapabilityIsAddedWhenRoslynComponentSpecified()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n true\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n var caps = instance.GetItems(\"ProjectCapability\").Select(c => c.EvaluatedInclude);\n Assert.Contains(\"RoslynComponent\", caps);\n }\n\n private static ProjectInstance CreateProjectInstance(XmlReader reader)\n {\n Project proj = new Project(reader);\n\n // add a dummy prepare for build target\n proj.Xml.AddTarget(\"PrepareForBuild\");\n\n // create a dummy WriteLinesToFile task\n addTask(proj, \"WriteLinesToFile\", new()\n {\n { \"Lines\", \"System.String[]\" },\n { \"File\", \"System.String\" },\n { \"Overwrite\", \"System.Boolean\" },\n { \"WriteOnlyWhenDifferent\", \"System.Boolean\" }\n });\n\n // dummy makeDir task\n addTask(proj, \"MakeDir\", new()\n {\n { \"Directories\", \"System.String[]\" }\n });\n\n // dummy Message task\n addTask(proj, \"Message\", new()\n {\n { \"Text\", \"System.String\" },\n { \"Importance\", \"System.String\" }\n });\n\n // create an instance and return it\n return proj.CreateProjectInstance();\n\n static void addTask(Project proj, string taskName, Dictionary parameters)\n {\n var task = proj.Xml.AddUsingTask(taskName, string.Empty, Assembly.GetExecutingAssembly().FullName);\n task.TaskFactory = nameof(DummyTaskFactory);\n\n var taskParams = task.AddParameterGroup();\n foreach (var kvp in parameters)\n {\n taskParams.AddParameter(kvp.Key, string.Empty, string.Empty, kvp.Value);\n }\n\n }\n }\n\n private static ILogger[] GetTestLoggers([CallerMemberName] string callerName = \"\")\n {\n#if DUMP_MSBUILD_BIN_LOG\n return new ILogger[]\n {\n new Build.Logging.BinaryLogger()\n {\n Parameters = callerName + \".binlog\"\n }\n };\n#else\n return Array.Empty();\n#endif\n }\n }\n\n /// \n /// Task factory that creates empty tasks for testing\n /// \n /// \n /// Replace any task with a dummy task by adding a UsingTask\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// You can specify the parameters the task should have via a ParameterGroup\n /// These should match the task you are replacing.\n /// \n public sealed class DummyTaskFactory : ITaskFactory\n {\n public string FactoryName { get => \"DummyTaskFactory\"; }\n\n public Type TaskType { get => typeof(DummyTaskFactory); }\n\n private TaskPropertyInfo[]? _props;\n\n public void CleanupTask(ITask task) { }\n\n public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new DummyTask();\n\n public TaskPropertyInfo[]? GetTaskParameters() => _props;\n\n public bool Initialize(string taskName, IDictionary parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)\n {\n _props = parameterGroup.Values.ToArray();\n return true;\n }\n\n private class DummyTask : IGeneratedTask\n {\n public IBuildEngine? BuildEngine { get; set; }\n\n public ITaskHost? HostObject { get; set; }\n\n public bool Execute() => true;\n\n public object GetPropertyValue(TaskPropertyInfo property) => null!;\n\n public void SetPropertyValue(TaskPropertyInfo property, object value) { }\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n// uncomment the below define to dump binlogs of each test\n//#define DUMP_MSBUILD_BIN_LOG\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Xml;\nusing Roslyn.Test.Utilities;\nusing Microsoft.Build.Evaluation;\nusing Microsoft.Build.Execution;\nusing Microsoft.Build.Framework;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.BuildTasks.UnitTests\n{\n public class TargetTests : TestBase\n {\n [Fact]\n public void GenerateEditorConfigShouldNotRunWhenNoPropertiesOrMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.NotEqual(\"true\", shouldRun);\n Assert.NotEqual(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigShouldRunWhenPropertiesRequested()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.Equal(\"true\", shouldRun);\n Assert.NotEqual(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigShouldRunWhenMetadataRequested()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.Equal(\"true\", shouldRun);\n Assert.Equal(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigShouldRunWhenPropertiesAndMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.Equal(\"true\", shouldRun);\n Assert.Equal(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigCanBeDisabled()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n false\n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFileShouldRun\", GetTestLoggers());\n var shouldRun = instance.GetPropertyValue(\"_GeneratedEditorConfigShouldRun\");\n var hasItems = instance.GetPropertyValue(\"_GeneratedEditorConfigHasItems\");\n\n Assert.True(runSuccess);\n Assert.NotEqual(\"true\", shouldRun);\n Assert.Equal(\"true\", hasItems);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesProperties()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n abc\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigProperty\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigProperty\", item.ItemType);\n Assert.Single(item.Metadata);\n\n var metadata = item.Metadata.Single();\n Assert.Equal(\"Value\", metadata.Name);\n Assert.Equal(\"abc\", metadata.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesDynamicProperties()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n def\n $(RealValue)\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigProperty\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigProperty\", item.ItemType);\n Assert.Single(item.Metadata);\n\n var metadata = item.Metadata.Single();\n Assert.Equal(\"Value\", metadata.Name);\n Assert.Equal(\"def\", metadata.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreHandlesMissingProperties()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigProperty\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigProperty\", item.ItemType);\n Assert.Single(item.Metadata);\n\n var metadata = item.Metadata.Single();\n Assert.Equal(\"Value\", metadata.Name);\n Assert.Equal(\"\", metadata.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"CustomMeta\", metaName.EvaluatedValue);\n\n var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue);\n AssertEx.NotNull(customMeta);\n Assert.Equal(\"abc\", customMeta.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreEvaluatesDynamicMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n abc\n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"CustomMeta\", metaName.EvaluatedValue);\n\n var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue);\n AssertEx.NotNull(customMeta);\n Assert.Equal(\"abc\", customMeta.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreHandlesMissingMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"CustomMeta\", metaName.EvaluatedValue);\n }\n\n [Fact]\n public void GenerateEditorConfigCoreHandlesMalformedCompilerVisibleItemMetadata()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"_GeneratedEditorConfigMetadata\");\n Assert.Single(items);\n\n var item = items.Single();\n Assert.Equal(\"_GeneratedEditorConfigMetadata\", item.ItemType);\n\n var itemType = item.Metadata.SingleOrDefault(m => m.Name == \"ItemType\");\n AssertEx.NotNull(itemType);\n Assert.Equal(\"Compile\", itemType.EvaluatedValue);\n\n var metaName = item.Metadata.SingleOrDefault(m => m.Name == \"MetadataName\");\n AssertEx.NotNull(metaName);\n Assert.Equal(\"\", metaName.EvaluatedValue);\n }\n\n [Theory]\n [InlineData(\".NETFramework\", \"4.5\", \"7.3\")]\n [InlineData(\".NETFramework\", \"4.7.2\", \"7.3\")]\n [InlineData(\".NETFramework\", \"4.8\", \"7.3\")]\n\n [InlineData(\".NETCoreApp\", \"1.0\", \"7.3\")]\n [InlineData(\".NETCoreApp\", \"2.0\", \"7.3\")]\n [InlineData(\".NETCoreApp\", \"2.1\", \"7.3\")]\n [InlineData(\".NETCoreApp\", \"3.0\", \"8.0\")]\n [InlineData(\".NETCoreApp\", \"3.1\", \"8.0\")]\n [InlineData(\".NETCoreApp\", \"5.0\", \"9.0\")]\n [InlineData(\".NETCoreApp\", \"6.0\", \"10.0\")]\n [InlineData(\".NETCoreApp\", \"7.0\", \"\")]\n\n [InlineData(\".NETStandard\", \"1.0\", \"7.3\")]\n [InlineData(\".NETStandard\", \"1.5\", \"7.3\")]\n [InlineData(\".NETStandard\", \"2.0\", \"7.3\")]\n [InlineData(\".NETStandard\", \"2.1\", \"8.0\")]\n\n [InlineData(\"UnknownTFM\", \"0.0\", \"7.3\")]\n [InlineData(\"UnknownTFM\", \"5.0\", \"7.3\")]\n [InlineData(\"UnknownTFM\", \"6.0\", \"7.3\")]\n public void LanguageVersionGivenTargetFramework(string tfi, string tfv, string expectedVersion)\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n {tfi}\n <_TargetFrameworkVersionWithoutV>{tfv}\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n\n Assert.Equal(expectedVersion, langVersion);\n Assert.Equal(expectedVersion, maxLangVersion);\n\n // This will fail whenever the current language version is updated.\n // Ensure you update the target files to select the correct CSharp version for the newest target framework\n // and add to the theory data above to cover it, before changing this version to make the test pass again.\n Assert.Equal(CSharp.LanguageVersion.CSharp10, CSharp.LanguageVersionFacts.CurrentVersion);\n }\n\n [Fact]\n public void ExplicitLangVersion()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n .NETCoreApp\n <_TargetFrameworkVersionWithoutV>2.0\n 55.0\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n\n Assert.Equal(\"55.0\", langVersion);\n Assert.Equal(\"7.3\", maxLangVersion);\n }\n\n [Fact]\n public void MaxSupportedLangVersionIsReadable()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n .NETCoreApp\n <_TargetFrameworkVersionWithoutV>2.0\n 9.0\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n var publicMaxLangVersion = instance.GetPropertyValue(\"MaxSupportedLangVersion\");\n\n Assert.Equal(\"9.0\", langVersion);\n Assert.Equal(\"7.3\", maxLangVersion);\n Assert.Equal(\"7.3\", publicMaxLangVersion);\n }\n\n [Fact]\n public void MaxSupportedLangVersionIsnotWriteable()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n .NETCoreApp\n <_TargetFrameworkVersionWithoutV>2.0\n 9.0 \n 9.0\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n instance.Build(GetTestLoggers());\n\n var langVersion = instance.GetPropertyValue(\"LangVersion\");\n var maxLangVersion = instance.GetPropertyValue(\"_MaxSupportedLangVersion\");\n var publicMaxLangVersion = instance.GetPropertyValue(\"MaxSupportedLangVersion\");\n\n Assert.Equal(\"9.0\", langVersion);\n Assert.Equal(\"7.3\", maxLangVersion);\n Assert.Equal(\"7.3\", publicMaxLangVersion);\n }\n\n [Fact]\n public void GenerateEditorConfigIsPassedToTheCompiler()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n \n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"GenerateMSBuildEditorConfigFile\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var items = instance.GetItems(\"EditorConfigFiles\");\n Assert.Single(items);\n }\n\n [Fact]\n public void AdditionalFilesAreAddedToNoneWhenCopied()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n \n \n \n \n \n \n \n\n\"));\n var instance = CreateProjectInstance(xmlReader);\n bool runSuccess = instance.Build(target: \"CopyAdditionalFiles\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var noneItems = instance.GetItems(\"None\").ToArray();\n Assert.Equal(3, noneItems.Length);\n\n Assert.Equal(\"file1.cs\", noneItems[0].EvaluatedInclude);\n Assert.Equal(\"Always\", noneItems[0].GetMetadataValue(\"CopyToOutputDirectory\"));\n\n Assert.Equal(\"file2.cs\", noneItems[1].EvaluatedInclude);\n Assert.Equal(\"PreserveNewest\", noneItems[1].GetMetadataValue(\"CopyToOutputDirectory\"));\n\n Assert.Equal(\"file3.cs\", noneItems[2].EvaluatedInclude);\n Assert.Equal(\"Never\", noneItems[2].GetMetadataValue(\"CopyToOutputDirectory\"));\n }\n\n [Fact]\n public void GeneratedFilesOutputPathHasDefaults()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(\"false\", emit);\n Assert.Equal(string.Empty, dir);\n }\n\n [Fact]\n public void GeneratedFilesOutputPathDefaultsToIntermediateOutputPathWhenSet()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n fallbackDirectory\n true\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"CreateCompilerGeneratedFilesOutputPath\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(\"true\", emit);\n Assert.Equal(\"fallbackDirectory/generated\", dir);\n }\n\n [Fact]\n public void GeneratedFilesOutputPathDefaultsIsEmptyWhenEmitDisable()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n false\n fallbackDirectory\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(\"false\", emit);\n Assert.Equal(string.Empty, dir);\n }\n\n [Theory]\n [InlineData(true, \"generatedDirectory\")]\n [InlineData(true, null)]\n [InlineData(false, \"generatedDirectory\")]\n [InlineData(false, null)]\n public void GeneratedFilesOutputPathCanBeSetAndSuppressed(bool emitGeneratedFiles, string? generatedFilesDir)\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n {(emitGeneratedFiles.ToString().ToLower())}\n {generatedFilesDir}\n fallbackDirectory\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"CreateCompilerGeneratedFilesOutputPath\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var emit = instance.GetPropertyValue(\"EmitCompilerGeneratedFiles\");\n var dir = instance.GetPropertyValue(\"CompilerGeneratedFilesOutputPath\");\n\n Assert.Equal(emitGeneratedFiles.ToString().ToLower(), emit);\n if (emitGeneratedFiles)\n {\n string expectedDir = generatedFilesDir ?? \"fallbackDirectory/generated\";\n Assert.Equal(expectedDir, dir);\n }\n else\n {\n Assert.Equal(string.Empty, dir);\n }\n }\n\n [Theory, CombinatorialData]\n [WorkItem(40926, \"https://github.com/dotnet/roslyn/issues/40926\")]\n public void TestSkipAnalyzers(\n [CombinatorialValues(true, false, null)] bool? runAnalyzers,\n [CombinatorialValues(true, false, null)] bool? runAnalyzersDuringBuild)\n {\n var runAnalyzersPropertyGroupString = getPropertyGroup(\"RunAnalyzers\", runAnalyzers);\n var runAnalyzersDuringBuildPropertyGroupString = getPropertyGroup(\"RunAnalyzersDuringBuild\", runAnalyzersDuringBuild);\n\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n{runAnalyzersPropertyGroupString}\n{runAnalyzersDuringBuildPropertyGroupString}\n\n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"_ComputeSkipAnalyzers\", GetTestLoggers());\n Assert.True(runSuccess);\n\n // Verify \"RunAnalyzers\" overrides \"RunAnalyzersDuringBuild\".\n // If neither properties are set, analyzers are enabled by default.\n var analyzersEnabled = runAnalyzers ?? runAnalyzersDuringBuild ?? true;\n\n var expectedSkipAnalyzersValue = !analyzersEnabled ? \"true\" : \"\";\n var actualSkipAnalyzersValue = instance.GetPropertyValue(\"_SkipAnalyzers\");\n Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue);\n return;\n\n static string getPropertyGroup(string propertyName, bool? propertyValue)\n {\n if (!propertyValue.HasValue)\n {\n return string.Empty;\n }\n\n return $@\"\n \n <{propertyName}>{propertyValue.Value}\n \";\n }\n }\n\n [Theory, CombinatorialData]\n [WorkItem(1337109, \"https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109\")]\n public void TestImplicitlySkipAnalyzers(\n [CombinatorialValues(true, false, null)] bool? runAnalyzers,\n [CombinatorialValues(true, false, null)] bool? implicitBuild,\n [CombinatorialValues(true, false, null)] bool? treatWarningsAsErrors,\n [CombinatorialValues(true, false, null)] bool? optimizeImplicitBuild,\n [CombinatorialValues(true, null)] bool? sdkStyleProject)\n {\n var runAnalyzersPropertyGroupString = getPropertyGroup(\"RunAnalyzers\", runAnalyzers);\n var implicitBuildPropertyGroupString = getPropertyGroup(\"IsImplicitlyTriggeredBuild\", implicitBuild);\n var treatWarningsAsErrorsPropertyGroupString = getPropertyGroup(\"TreatWarningsAsErrors\", treatWarningsAsErrors);\n var optimizeImplicitBuildPropertyGroupString = getPropertyGroup(\"OptimizeImplicitlyTriggeredBuild\", optimizeImplicitBuild);\n var sdkStyleProjectPropertyGroupString = getPropertyGroup(\"UsingMicrosoftNETSdk\", sdkStyleProject);\n\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n{runAnalyzersPropertyGroupString}\n{implicitBuildPropertyGroupString}\n{treatWarningsAsErrorsPropertyGroupString}\n{optimizeImplicitBuildPropertyGroupString}\n{sdkStyleProjectPropertyGroupString}\n\n\n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n bool runSuccess = instance.Build(target: \"_ComputeSkipAnalyzers\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var analyzersEnabled = runAnalyzers ?? true;\n var expectedImplicitlySkippedAnalyzers = analyzersEnabled &&\n implicitBuild == true &&\n sdkStyleProject == true &&\n (treatWarningsAsErrors != true || optimizeImplicitBuild == true);\n var expectedImplicitlySkippedAnalyzersValue = expectedImplicitlySkippedAnalyzers ? \"true\" : \"\";\n var actualImplicitlySkippedAnalyzersValue = instance.GetPropertyValue(\"_ImplicitlySkipAnalyzers\");\n Assert.Equal(expectedImplicitlySkippedAnalyzersValue, actualImplicitlySkippedAnalyzersValue);\n\n var expectedSkipAnalyzersValue = !analyzersEnabled || expectedImplicitlySkippedAnalyzers ? \"true\" : \"\";\n var actualSkipAnalyzersValue = instance.GetPropertyValue(\"_SkipAnalyzers\");\n Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue);\n\n var expectedFeaturesValue = expectedImplicitlySkippedAnalyzers ? \"run-nullable-analysis=never;\" : \"\";\n var actualFeaturesValue = instance.GetPropertyValue(\"Features\");\n Assert.Equal(expectedFeaturesValue, actualFeaturesValue);\n return;\n\n static string getPropertyGroup(string propertyName, bool? propertyValue)\n {\n if (!propertyValue.HasValue)\n {\n return string.Empty;\n }\n\n return $@\"\n \n <{propertyName}>{propertyValue.Value}\n \";\n }\n }\n\n [Theory, CombinatorialData]\n [WorkItem(1337109, \"https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109\")]\n public void TestLastBuildWithSkipAnalyzers(\n [CombinatorialValues(true, false, null)] bool? runAnalyzers,\n bool lastBuildWithSkipAnalyzersFileExists)\n {\n var runAnalyzersPropertyGroupString = getPropertyGroup(\"RunAnalyzers\", runAnalyzers);\n var intermediatePathDir = Temp.CreateDirectory();\n var intermediatePath = intermediatePathDir + Path.DirectorySeparatorChar.ToString();\n\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n{runAnalyzersPropertyGroupString}\n\n \n {intermediatePath}\n \n\n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n var msbuildProjectFileName = instance.GetPropertyValue(\"MSBuildProjectFile\");\n var expectedLastBuildWithSkipAnalyzers = intermediatePath + msbuildProjectFileName + \".BuildWithSkipAnalyzers\";\n if (lastBuildWithSkipAnalyzersFileExists)\n {\n _ = intermediatePathDir.CreateFile(msbuildProjectFileName + \".BuildWithSkipAnalyzers\");\n }\n\n bool runSuccess = instance.Build(target: \"_ComputeSkipAnalyzers\", GetTestLoggers());\n Assert.True(runSuccess);\n\n var actualLastBuildWithSkipAnalyzers = instance.GetPropertyValue(\"_LastBuildWithSkipAnalyzers\");\n Assert.Equal(expectedLastBuildWithSkipAnalyzers, actualLastBuildWithSkipAnalyzers);\n\n var skipAnalyzers = !(runAnalyzers ?? true);\n var expectedCustomAdditionalCompileInput = lastBuildWithSkipAnalyzersFileExists && !skipAnalyzers;\n\n var items = instance.GetItems(\"CustomAdditionalCompileInputs\");\n var expectedItemCount = expectedCustomAdditionalCompileInput ? 1 : 0;\n Assert.Equal(expectedItemCount, items.Count);\n if (expectedCustomAdditionalCompileInput)\n {\n Assert.Equal(expectedLastBuildWithSkipAnalyzers, items.Single().EvaluatedInclude);\n }\n\n var expectedUpToDateCheckInput = lastBuildWithSkipAnalyzersFileExists;\n items = instance.GetItems(\"UpToDateCheckInput\");\n expectedItemCount = expectedUpToDateCheckInput ? 1 : 0;\n Assert.Equal(expectedItemCount, items.Count);\n if (expectedUpToDateCheckInput)\n {\n var item = items.Single();\n Assert.Equal(expectedLastBuildWithSkipAnalyzers, item.EvaluatedInclude);\n Assert.Equal(\"ImplicitBuild\", item.GetMetadataValue(\"Kind\"));\n }\n\n return;\n\n static string getPropertyGroup(string propertyName, bool? propertyValue)\n {\n if (!propertyValue.HasValue)\n {\n return string.Empty;\n }\n\n return $@\"\n \n <{propertyName}>{propertyValue.Value}\n \";\n }\n }\n\n [Fact]\n public void ProjectCapabilityIsNotAddedWhenRoslynComponentIsUnspecified()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n var caps = instance.GetItems(\"ProjectCapability\").Select(c => c.EvaluatedInclude);\n Assert.DoesNotContain(\"RoslynComponent\", caps);\n }\n\n [Fact]\n public void ProjectCapabilityIsAddedWhenRoslynComponentSpecified()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n true\n \n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n var caps = instance.GetItems(\"ProjectCapability\").Select(c => c.EvaluatedInclude);\n Assert.Contains(\"RoslynComponent\", caps);\n }\n\n [Fact]\n public void CompilerApiVersionIsSet()\n {\n XmlReader xmlReader = XmlReader.Create(new StringReader($@\"\n\n \n\n\"));\n\n var instance = CreateProjectInstance(xmlReader);\n\n var compilerApiVersionString = instance.GetPropertyValue(\"CompilerApiVersion\");\n Assert.StartsWith(\"roslyn\", compilerApiVersionString);\n\n var compilerApiVersion = Version.Parse(compilerApiVersionString.Substring(\"roslyn\".Length));\n\n var expectedVersionString = GetType().Assembly.GetCustomAttributes()\n .Single(a => a.Key == \"CurrentCompilerApiVersion\")\n .Value ?? string.Empty;\n var expectedVersion = Version.Parse(expectedVersionString);\n\n Assert.Equal(expectedVersion, compilerApiVersion);\n }\n\n private static ProjectInstance CreateProjectInstance(XmlReader reader)\n {\n Project proj = new Project(reader);\n\n // add a dummy prepare for build target\n proj.Xml.AddTarget(\"PrepareForBuild\");\n\n // create a dummy WriteLinesToFile task\n addTask(proj, \"WriteLinesToFile\", new()\n {\n { \"Lines\", \"System.String[]\" },\n { \"File\", \"System.String\" },\n { \"Overwrite\", \"System.Boolean\" },\n { \"WriteOnlyWhenDifferent\", \"System.Boolean\" }\n });\n\n // dummy makeDir task\n addTask(proj, \"MakeDir\", new()\n {\n { \"Directories\", \"System.String[]\" }\n });\n\n // dummy Message task\n addTask(proj, \"Message\", new()\n {\n { \"Text\", \"System.String\" },\n { \"Importance\", \"System.String\" }\n });\n\n // create an instance and return it\n return proj.CreateProjectInstance();\n\n static void addTask(Project proj, string taskName, Dictionary parameters)\n {\n var task = proj.Xml.AddUsingTask(taskName, string.Empty, Assembly.GetExecutingAssembly().FullName);\n task.TaskFactory = nameof(DummyTaskFactory);\n\n var taskParams = task.AddParameterGroup();\n foreach (var kvp in parameters)\n {\n taskParams.AddParameter(kvp.Key, string.Empty, string.Empty, kvp.Value);\n }\n\n }\n }\n\n private static ILogger[] GetTestLoggers([CallerMemberName] string callerName = \"\")\n {\n#if DUMP_MSBUILD_BIN_LOG\n return new ILogger[]\n {\n new Build.Logging.BinaryLogger()\n {\n Parameters = callerName + \".binlog\"\n }\n };\n#else\n return Array.Empty();\n#endif\n }\n }\n\n /// \n /// Task factory that creates empty tasks for testing\n /// \n /// \n /// Replace any task with a dummy task by adding a UsingTask\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// \n /// You can specify the parameters the task should have via a ParameterGroup\n /// These should match the task you are replacing.\n /// \n public sealed class DummyTaskFactory : ITaskFactory\n {\n public string FactoryName { get => \"DummyTaskFactory\"; }\n\n public Type TaskType { get => typeof(DummyTaskFactory); }\n\n private TaskPropertyInfo[]? _props;\n\n public void CleanupTask(ITask task) { }\n\n public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new DummyTask();\n\n public TaskPropertyInfo[]? GetTaskParameters() => _props;\n\n public bool Initialize(string taskName, IDictionary parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)\n {\n _props = parameterGroup.Values.ToArray();\n return true;\n }\n\n private class DummyTask : IGeneratedTask\n {\n public IBuildEngine? BuildEngine { get; set; }\n\n public ITaskHost? HostObject { get; set; }\n\n public bool Execute() => true;\n\n public object GetPropertyValue(TaskPropertyInfo property) => null!;\n\n public void SetPropertyValue(TaskPropertyInfo property, object value) { }\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":475,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/NuGet/Microsoft.Net.Compilers.Toolset/DesktopCompilerArtifacts.targets"},"before_content":{"kind":"string","value":"\n\n\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Threading.Tasks.Extensions.dll\"/>\n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Buffers.dll\"/>\n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Memory.dll\"/>\n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Numerics.Vectors.dll\"/> \n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Text.Encoding.CodePages.dll\"/>\n \n \n <_NoNGen Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Numerics.Vectors.dll\"/>\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n\n \n \n\n"},"after_content":{"kind":"string","value":"\n\n\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Threading.Tasks.Extensions.dll\"/>\n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Buffers.dll\"/>\n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Memory.dll\"/>\n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Numerics.Vectors.dll\"/> \n <_NoOptimizationData Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Text.Encoding.CodePages.dll\"/>\n \n \n <_NoNGen Include=\"$(ArtifactsBinDir)csi\\$(Configuration)\\net472\\System.Numerics.Vectors.dll\"/>\n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n\n \n \n\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":476,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Features/CSharp/Portable/Organizing/Organizers/IndexerDeclarationOrganizer.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Composition;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Organizing.Organizers;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers\n{\n [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]\n internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public IndexerDeclarationOrganizer()\n {\n }\n\n protected override IndexerDeclarationSyntax Organize(\n IndexerDeclarationSyntax syntax,\n CancellationToken cancellationToken)\n {\n return syntax.Update(\n attributeLists: syntax.AttributeLists,\n modifiers: ModifiersOrganizer.Organize(syntax.Modifiers),\n type: syntax.Type,\n explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier,\n thisKeyword: syntax.ThisKeyword,\n parameterList: syntax.ParameterList,\n accessorList: syntax.AccessorList,\n expressionBody: syntax.ExpressionBody,\n semicolonToken: syntax.SemicolonToken);\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Composition;\nusing System.Threading;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Organizing.Organizers;\n\nnamespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers\n{\n [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]\n internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public IndexerDeclarationOrganizer()\n {\n }\n\n protected override IndexerDeclarationSyntax Organize(\n IndexerDeclarationSyntax syntax,\n CancellationToken cancellationToken)\n {\n return syntax.Update(\n attributeLists: syntax.AttributeLists,\n modifiers: ModifiersOrganizer.Organize(syntax.Modifiers),\n type: syntax.Type,\n explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier,\n thisKeyword: syntax.ThisKeyword,\n parameterList: syntax.ParameterList,\n accessorList: syntax.AccessorList,\n expressionBody: syntax.ExpressionBody,\n semicolonToken: syntax.SemicolonToken);\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":477,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.CallbackDispatcher.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Remote;\nusing Microsoft.CodeAnalysis.Text;\n\nnamespace Microsoft.CodeAnalysis.FindSymbols\n{\n public static partial class SymbolFinder\n {\n [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteSymbolFinderService)), Shared]\n internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteSymbolFinderService.ICallback\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public CallbackDispatcher()\n {\n }\n\n private FindLiteralsServerCallback GetFindLiteralsCallback(RemoteServiceCallbackId callbackId)\n => (FindLiteralsServerCallback)GetCallback(callbackId);\n\n private FindReferencesServerCallback GetFindReferencesCallback(RemoteServiceCallbackId callbackId)\n => (FindReferencesServerCallback)GetCallback(callbackId);\n\n // references\n\n public ValueTask AddReferenceItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).AddItemsAsync(count, cancellationToken);\n\n public ValueTask ReferenceItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).ItemCompletedAsync(cancellationToken);\n\n public ValueTask OnCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnCompletedAsync(cancellationToken);\n\n public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnDefinitionFoundAsync(symbolGroup, cancellationToken);\n\n public ValueTask OnFindInDocumentCompletedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnFindInDocumentCompletedAsync(documentId, cancellationToken);\n\n public ValueTask OnFindInDocumentStartedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnFindInDocumentStartedAsync(documentId, cancellationToken);\n\n public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnReferenceFoundAsync(symbolGroup, definition, reference, cancellationToken);\n\n public ValueTask OnStartedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnStartedAsync(cancellationToken);\n\n // literals\n\n public ValueTask AddLiteralItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken)\n => GetFindLiteralsCallback(callbackId).AddItemsAsync(count, cancellationToken);\n\n public ValueTask LiteralItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindLiteralsCallback(callbackId).ItemCompletedAsync(cancellationToken);\n\n public ValueTask OnLiteralReferenceFoundAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, CancellationToken cancellationToken)\n => GetFindLiteralsCallback(callbackId).OnLiteralReferenceFoundAsync(documentId, span, cancellationToken);\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Remote;\nusing Microsoft.CodeAnalysis.Text;\n\nnamespace Microsoft.CodeAnalysis.FindSymbols\n{\n public static partial class SymbolFinder\n {\n [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteSymbolFinderService)), Shared]\n internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteSymbolFinderService.ICallback\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public CallbackDispatcher()\n {\n }\n\n private FindLiteralsServerCallback GetFindLiteralsCallback(RemoteServiceCallbackId callbackId)\n => (FindLiteralsServerCallback)GetCallback(callbackId);\n\n private FindReferencesServerCallback GetFindReferencesCallback(RemoteServiceCallbackId callbackId)\n => (FindReferencesServerCallback)GetCallback(callbackId);\n\n // references\n\n public ValueTask AddReferenceItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).AddItemsAsync(count, cancellationToken);\n\n public ValueTask ReferenceItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).ItemCompletedAsync(cancellationToken);\n\n public ValueTask OnCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnCompletedAsync(cancellationToken);\n\n public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnDefinitionFoundAsync(symbolGroup, cancellationToken);\n\n public ValueTask OnFindInDocumentCompletedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnFindInDocumentCompletedAsync(documentId, cancellationToken);\n\n public ValueTask OnFindInDocumentStartedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnFindInDocumentStartedAsync(documentId, cancellationToken);\n\n public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnReferenceFoundAsync(symbolGroup, definition, reference, cancellationToken);\n\n public ValueTask OnStartedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindReferencesCallback(callbackId).OnStartedAsync(cancellationToken);\n\n // literals\n\n public ValueTask AddLiteralItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken)\n => GetFindLiteralsCallback(callbackId).AddItemsAsync(count, cancellationToken);\n\n public ValueTask LiteralItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)\n => GetFindLiteralsCallback(callbackId).ItemCompletedAsync(cancellationToken);\n\n public ValueTask OnLiteralReferenceFoundAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, CancellationToken cancellationToken)\n => GetFindLiteralsCallback(callbackId).OnLiteralReferenceFoundAsync(documentId, span, cancellationToken);\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":478,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Features/LanguageServer/Protocol/Handler/Formatting/FormatDocumentHandler.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing LSP = Microsoft.VisualStudio.LanguageServer.Protocol;\n\nnamespace Microsoft.CodeAnalysis.LanguageServer.Handler\n{\n [ExportRoslynLanguagesLspRequestHandlerProvider, Shared]\n [ProvidesMethod(LSP.Methods.TextDocumentFormattingName)]\n internal class FormatDocumentHandler : AbstractFormatDocumentHandlerBase\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public FormatDocumentHandler()\n {\n }\n\n public override string Method => LSP.Methods.TextDocumentFormattingName;\n\n public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DocumentFormattingParams request) => request.TextDocument;\n\n public override Task HandleRequestAsync(\n LSP.DocumentFormattingParams request,\n RequestContext context,\n CancellationToken cancellationToken)\n => GetTextEditsAsync(context, request.Options, cancellationToken);\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System;\nusing System.Composition;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing LSP = Microsoft.VisualStudio.LanguageServer.Protocol;\n\nnamespace Microsoft.CodeAnalysis.LanguageServer.Handler\n{\n [ExportRoslynLanguagesLspRequestHandlerProvider, Shared]\n [ProvidesMethod(LSP.Methods.TextDocumentFormattingName)]\n internal class FormatDocumentHandler : AbstractFormatDocumentHandlerBase\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public FormatDocumentHandler()\n {\n }\n\n public override string Method => LSP.Methods.TextDocumentFormattingName;\n\n public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DocumentFormattingParams request) => request.TextDocument;\n\n public override Task HandleRequestAsync(\n LSP.DocumentFormattingParams request,\n RequestContext context,\n CancellationToken cancellationToken)\n => GetTextEditsAsync(context, request.Options, cancellationToken);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":479,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiaSymReader/Writer/SymUnmanagedSequencePointsWriter.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\n\nnamespace Microsoft.DiaSymReader\n{\n internal sealed class SymUnmanagedSequencePointsWriter\n {\n private readonly SymUnmanagedWriter _writer;\n private int _currentDocumentIndex;\n private int _count;\n private int[] _offsets;\n private int[] _startLines;\n private int[] _startColumns;\n private int[] _endLines;\n private int[] _endColumns;\n\n public SymUnmanagedSequencePointsWriter(SymUnmanagedWriter writer, int capacity = 64)\n {\n if (capacity <= 0)\n {\n throw new ArgumentOutOfRangeException(nameof(capacity));\n }\n\n _writer = writer ?? throw new ArgumentNullException(nameof(writer));\n _currentDocumentIndex = -1;\n _offsets = new int[capacity];\n _startLines = new int[capacity];\n _startColumns = new int[capacity];\n _endLines = new int[capacity];\n _endColumns = new int[capacity];\n }\n\n private void EnsureCapacity(int length)\n {\n if (length > _offsets.Length)\n {\n int newLength = Math.Max(length, (_offsets.Length + 1) * 2);\n\n Array.Resize(ref _offsets, newLength);\n Array.Resize(ref _startLines, newLength);\n Array.Resize(ref _startColumns, newLength);\n Array.Resize(ref _endLines, newLength);\n Array.Resize(ref _endColumns, newLength);\n }\n }\n\n private void Clear()\n {\n _currentDocumentIndex = -1;\n _count = 0;\n }\n\n public void Add(int documentIndex, int offset, int startLine, int startColumn, int endLine, int endColumn)\n {\n if (documentIndex < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(documentIndex));\n }\n\n if (_currentDocumentIndex != documentIndex)\n {\n if (_currentDocumentIndex != -1)\n {\n Flush();\n }\n\n _currentDocumentIndex = documentIndex;\n }\n\n int index = _count++;\n\n EnsureCapacity(_count);\n\n _offsets[index] = offset;\n _startLines[index] = startLine;\n _startColumns[index] = startColumn;\n _endLines[index] = endLine;\n _endColumns[index] = endColumn;\n }\n\n public void Flush()\n {\n if (_count > 0)\n {\n _writer.DefineSequencePoints(\n _currentDocumentIndex,\n _count,\n _offsets,\n _startLines,\n _startColumns,\n _endLines,\n _endColumns);\n }\n\n Clear();\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\n\nnamespace Microsoft.DiaSymReader\n{\n internal sealed class SymUnmanagedSequencePointsWriter\n {\n private readonly SymUnmanagedWriter _writer;\n private int _currentDocumentIndex;\n private int _count;\n private int[] _offsets;\n private int[] _startLines;\n private int[] _startColumns;\n private int[] _endLines;\n private int[] _endColumns;\n\n public SymUnmanagedSequencePointsWriter(SymUnmanagedWriter writer, int capacity = 64)\n {\n if (capacity <= 0)\n {\n throw new ArgumentOutOfRangeException(nameof(capacity));\n }\n\n _writer = writer ?? throw new ArgumentNullException(nameof(writer));\n _currentDocumentIndex = -1;\n _offsets = new int[capacity];\n _startLines = new int[capacity];\n _startColumns = new int[capacity];\n _endLines = new int[capacity];\n _endColumns = new int[capacity];\n }\n\n private void EnsureCapacity(int length)\n {\n if (length > _offsets.Length)\n {\n int newLength = Math.Max(length, (_offsets.Length + 1) * 2);\n\n Array.Resize(ref _offsets, newLength);\n Array.Resize(ref _startLines, newLength);\n Array.Resize(ref _startColumns, newLength);\n Array.Resize(ref _endLines, newLength);\n Array.Resize(ref _endColumns, newLength);\n }\n }\n\n private void Clear()\n {\n _currentDocumentIndex = -1;\n _count = 0;\n }\n\n public void Add(int documentIndex, int offset, int startLine, int startColumn, int endLine, int endColumn)\n {\n if (documentIndex < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(documentIndex));\n }\n\n if (_currentDocumentIndex != documentIndex)\n {\n if (_currentDocumentIndex != -1)\n {\n Flush();\n }\n\n _currentDocumentIndex = documentIndex;\n }\n\n int index = _count++;\n\n EnsureCapacity(_count);\n\n _offsets[index] = offset;\n _startLines[index] = startLine;\n _startColumns[index] = startColumn;\n _endLines[index] = endLine;\n _endColumns[index] = endColumn;\n }\n\n public void Flush()\n {\n if (_count > 0)\n {\n _writer.DefineSequencePoints(\n _currentDocumentIndex,\n _count,\n _offsets,\n _startLines,\n _startColumns,\n _endLines,\n _endColumns);\n }\n\n Clear();\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":480,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/EditorFeatures/CSharpTest/CodeActions/AddAwait/AddAwaitTests.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeRefactorings;\nusing Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.AddAwait\n{\n [Trait(Traits.Feature, Traits.Features.AddAwait)]\n public class AddAwaitTests : AbstractCSharpCodeActionTest\n {\n protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)\n => new CSharpAddAwaitCodeRefactoringProvider();\n\n [Fact]\n public async Task Simple()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = GetNumberAsync()[||];\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = GetNumberAsync()[||];\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync().ConfigureAwait(false);\n }\n}\", index: 1);\n }\n\n [Fact]\n public async Task InArgument()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync(int argument)\n {\n var x = GetNumberAsync(arg[||]ument);\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync(int argument)\n {\n var x = await GetNumberAsync(argument);\n }\n}\");\n }\n\n [Fact]\n public async Task InvocationInArgument()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(GetNumberAsync()[||]);\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(await GetNumberAsync());\n }\n}\");\n }\n\n [Fact]\n public async Task InvocationInArgumentWithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(GetNumberAsync()[||]);\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(await GetNumberAsync().ConfigureAwait(false));\n }\n}\", index: 1);\n }\n\n [Fact]\n public async Task AlreadyAwaited()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync()[||];\n }\n}\");\n }\n\n [Fact]\n public async Task AlreadyAwaitedAndConfigured()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync()[||].ConfigureAwait(false);\n }\n}\");\n }\n\n [Fact]\n public async Task AlreadyAwaitedAndConfigured2()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync().ConfigureAwait(false)[||];\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithTrivia()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n GetNumberAsync()[||] /* comment */\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n await GetNumberAsync()[||] /* comment */\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithTrivia2()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ GetNumberAsync()[||] // comment\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ await GetNumberAsync()[||] // comment\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithTriviaWithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n GetNumberAsync()[||] /* comment */\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n await GetNumberAsync().ConfigureAwait(false) /* comment */\n }\n}\", index: 1);\n }\n\n [Fact]\n public async Task SimpleWithTrivia2WithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ GetNumberAsync()[||] // comment\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ await GetNumberAsync().ConfigureAwait(false) // comment\n }\n}\", index: 1);\n }\n\n [Fact]\n [WorkItem(35525, \"https://github.com/dotnet/roslyn/issues/35525\")]\n public async Task OnSemiColon()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = GetNumberAsync();[||]\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n [WorkItem(35525, \"https://github.com/dotnet/roslyn/issues/35525\")]\n public async Task Selection()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = [|GetNumberAsync()|];\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n [WorkItem(35525, \"https://github.com/dotnet/roslyn/issues/35525\")]\n public async Task Selection2()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n [|var x = GetNumberAsync();|]\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n public async Task ChainedInvocation()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n Task GetNumberAsync() => throw null;\n async void M()\n {\n var x = GetNumberAsync()[||].ToString();\n }\n}\");\n }\n\n [Fact]\n public async Task ChainedInvocation_ExpressionOfInvalidInvocation()\n {\n await TestInRegularAndScript1Async(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n Task GetNumberAsync() => throw null;\n async void M()\n {\n var x = GetNumberAsync()[||].Invalid();\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n Task GetNumberAsync() => throw null;\n async void M()\n {\n var x = (await GetNumberAsync()).Invalid();\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand1()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return [|Test()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return await Test();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_WithLeadingTrivia1()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return\n // Useful comment\n [|Test()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return\n // Useful comment\n await Test();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|true ? Test() /* true */ : Test()|] /* false */;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (true ? Test() /* true */ : Test()) /* false */;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|true ? Test() // aaa\n : Test()|] // bbb\n ;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (true ? Test() // aaa\n : Test()) // bbb\n ;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|null /* 0 */ ?? Test()|] /* 1 */;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (null /* 0 */ ?? Test()) /* 1 */;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|null // aaa\n ?? Test()|] // bbb\n ;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (null // aaa\n ?? Test()) // bbb\n ;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test2()\n {\n return [|null /* 0 */ as Task|] /* 1 */;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test2()\n {\n return await (null /* 0 */ as Task) /* 1 */;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|null // aaa\n as Task|] // bbb\n ;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (null // aaa\n as Task) // bbb\n ;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TaskNotAwaited()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n [|Task.Delay(3)|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n await Task.Delay(3);\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TaskNotAwaited_WithLeadingTrivia()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n\n // Useful comment\n [|Task.Delay(3)|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n\n // Useful comment\n await Task.Delay(3);\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task FunctionNotAwaited()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n [|AwaitableFunction()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n await AwaitableFunction();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task FunctionNotAwaited_WithLeadingTrivia()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n\n // Useful comment\n [|AwaitableFunction()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n\n // Useful comment\n await AwaitableFunction();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task FunctionNotAwaited_WithLeadingTrivia1()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n var i = 0;\n\n [|AwaitableFunction()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n var i = 0;\n\n await AwaitableFunction();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression()\n {\n await TestInRegularAndScriptAsync(\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n int myInt = [|MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n int myInt = await MyIntMethodAsync();\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpressionWithConversion()\n {\n await TestInRegularAndScriptAsync(\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = [|MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = await MyIntMethodAsync();\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction()\n {\n\n await TestMissingAsync(@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private Task MyTestMethod1Async()\n {\n long myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpressionWithConversionInAsyncFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = [|MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(new object());\n }\n}\",\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = [|await MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(new object());\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression2()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression3()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = () => {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression3_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = await MyIntMethodAsync();\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression4()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression4_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression5()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression6()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression7()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression7_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression8()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = delegate {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression8_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = [|await MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestTernaryOperator()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return [|true ? Task.FromResult(0) : Task.FromResult(1)|];\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return await (true ? Task.FromResult(0) : Task.FromResult(1));\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestNullCoalescingOperator()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return [|null ?? Task.FromResult(1)|]; }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return await (null ?? Task.FromResult(1)); }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAsExpression()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return [|null as Task|]; }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return await (null as Task); }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n [WorkItem(1345322, \"https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1345322\")]\n public async Task TestOnTaskTypeItself()\n {\n await TestMissingAsync(\n@\"using System.Threading.Tasks;\n\nclass Program\n{\n static async [||]Task Main(string[] args)\n {\n }\n}\n\");\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis.CodeRefactorings;\nusing Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.AddAwait\n{\n [Trait(Traits.Feature, Traits.Features.AddAwait)]\n public class AddAwaitTests : AbstractCSharpCodeActionTest\n {\n protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)\n => new CSharpAddAwaitCodeRefactoringProvider();\n\n [Fact]\n public async Task Simple()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = GetNumberAsync()[||];\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = GetNumberAsync()[||];\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync().ConfigureAwait(false);\n }\n}\", index: 1);\n }\n\n [Fact]\n public async Task InArgument()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync(int argument)\n {\n var x = GetNumberAsync(arg[||]ument);\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync(int argument)\n {\n var x = await GetNumberAsync(argument);\n }\n}\");\n }\n\n [Fact]\n public async Task InvocationInArgument()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(GetNumberAsync()[||]);\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(await GetNumberAsync());\n }\n}\");\n }\n\n [Fact]\n public async Task InvocationInArgumentWithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(GetNumberAsync()[||]);\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n M(await GetNumberAsync().ConfigureAwait(false));\n }\n}\", index: 1);\n }\n\n [Fact]\n public async Task AlreadyAwaited()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync()[||];\n }\n}\");\n }\n\n [Fact]\n public async Task AlreadyAwaitedAndConfigured()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync()[||].ConfigureAwait(false);\n }\n}\");\n }\n\n [Fact]\n public async Task AlreadyAwaitedAndConfigured2()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync().ConfigureAwait(false)[||];\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithTrivia()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n GetNumberAsync()[||] /* comment */\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n await GetNumberAsync()[||] /* comment */\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithTrivia2()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ GetNumberAsync()[||] // comment\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ await GetNumberAsync()[||] // comment\n }\n}\");\n }\n\n [Fact]\n public async Task SimpleWithTriviaWithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n GetNumberAsync()[||] /* comment */\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = // comment\n await GetNumberAsync().ConfigureAwait(false) /* comment */\n }\n}\", index: 1);\n }\n\n [Fact]\n public async Task SimpleWithTrivia2WithConfigureAwait()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ GetNumberAsync()[||] // comment\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = /* comment */ await GetNumberAsync().ConfigureAwait(false) // comment\n }\n}\", index: 1);\n }\n\n [Fact]\n [WorkItem(35525, \"https://github.com/dotnet/roslyn/issues/35525\")]\n public async Task OnSemiColon()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = GetNumberAsync();[||]\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n [WorkItem(35525, \"https://github.com/dotnet/roslyn/issues/35525\")]\n public async Task Selection()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = [|GetNumberAsync()|];\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n [WorkItem(35525, \"https://github.com/dotnet/roslyn/issues/35525\")]\n public async Task Selection2()\n {\n await TestInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n [|var x = GetNumberAsync();|]\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n async Task GetNumberAsync()\n {\n var x = await GetNumberAsync();\n }\n}\");\n }\n\n [Fact]\n public async Task ChainedInvocation()\n {\n await TestMissingInRegularAndScriptAsync(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n Task GetNumberAsync() => throw null;\n async void M()\n {\n var x = GetNumberAsync()[||].ToString();\n }\n}\");\n }\n\n [Fact]\n public async Task ChainedInvocation_ExpressionOfInvalidInvocation()\n {\n await TestInRegularAndScript1Async(@\"\nusing System.Threading.Tasks;\nclass Program\n{\n Task GetNumberAsync() => throw null;\n async void M()\n {\n var x = GetNumberAsync()[||].Invalid();\n }\n}\", @\"\nusing System.Threading.Tasks;\nclass Program\n{\n Task GetNumberAsync() => throw null;\n async void M()\n {\n var x = (await GetNumberAsync()).Invalid();\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand1()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return [|Test()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return await Test();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_WithLeadingTrivia1()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return\n // Useful comment\n [|Test()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test()\n {\n return 3;\n }\n\n async Task Test2()\n {\n return\n // Useful comment\n await Test();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|true ? Test() /* true */ : Test()|] /* false */;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (true ? Test() /* true */ : Test()) /* false */;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|true ? Test() // aaa\n : Test()|] // bbb\n ;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (true ? Test() // aaa\n : Test()) // bbb\n ;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|null /* 0 */ ?? Test()|] /* 1 */;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (null /* 0 */ ?? Test()) /* 1 */;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|null // aaa\n ?? Test()|] // bbb\n ;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (null // aaa\n ?? Test()) // bbb\n ;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test2()\n {\n return [|null /* 0 */ as Task|] /* 1 */;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test2()\n {\n return await (null /* 0 */ as Task) /* 1 */;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return [|null // aaa\n as Task|] // bbb\n ;\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task Test() => 3;\n\n async Task Test2()\n {\n return await (null // aaa\n as Task) // bbb\n ;\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TaskNotAwaited()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n [|Task.Delay(3)|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n await Task.Delay(3);\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TaskNotAwaited_WithLeadingTrivia()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n\n // Useful comment\n [|Task.Delay(3)|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n async void Test()\n {\n\n // Useful comment\n await Task.Delay(3);\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task FunctionNotAwaited()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n [|AwaitableFunction()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n await AwaitableFunction();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task FunctionNotAwaited_WithLeadingTrivia()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n\n // Useful comment\n [|AwaitableFunction()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n\n // Useful comment\n await AwaitableFunction();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task FunctionNotAwaited_WithLeadingTrivia1()\n {\n var initial =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n var i = 0;\n\n [|AwaitableFunction()|];\n }\n}\";\n\n var expected =\n@\"using System;\nusing System.Threading.Tasks;\nclass Program\n{\n Task AwaitableFunction()\n {\n return Task.FromResult(true);\n }\n\n async void Test()\n {\n var i = 0;\n\n await AwaitableFunction();\n }\n}\";\n await TestInRegularAndScriptAsync(initial, expected);\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression()\n {\n await TestInRegularAndScriptAsync(\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n int myInt = [|MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n int myInt = await MyIntMethodAsync();\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpressionWithConversion()\n {\n await TestInRegularAndScriptAsync(\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = [|MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = await MyIntMethodAsync();\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction()\n {\n\n await TestMissingAsync(@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private Task MyTestMethod1Async()\n {\n long myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpressionWithConversionInAsyncFunction()\n {\n await TestInRegularAndScriptAsync(\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = [|MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(new object());\n }\n}\",\n@\"using System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n long myInt = [|await MyIntMethodAsync()|];\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(new object());\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression2()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression3()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = () => {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression3_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func lambda = async () => {\n int myInt = await MyIntMethodAsync();\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression4()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression4_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action lambda = async () => {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression5()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression6()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression7()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression7_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Action @delegate = async delegate {\n int myInt = await MyIntMethodAsync();\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression8()\n {\n await TestMissingAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = delegate {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAssignmentExpression8_1()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = [|MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass TestClass\n{\n private async Task MyTestMethod1Async()\n {\n Func @delegate = async delegate {\n int myInt = [|await MyIntMethodAsync()|];\n return Task.CompletedTask;\n };\n }\n\n private Task MyIntMethodAsync()\n {\n return Task.FromResult(result: 1);\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestTernaryOperator()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return [|true ? Task.FromResult(0) : Task.FromResult(1)|];\n }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return await (true ? Task.FromResult(0) : Task.FromResult(1));\n }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestNullCoalescingOperator()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return [|null ?? Task.FromResult(1)|]; }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return await (null ?? Task.FromResult(1)); }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n public async Task TestAsExpression()\n {\n await TestInRegularAndScriptAsync(\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return [|null as Task|]; }\n}\",\n@\"using System;\nusing System.Threading.Tasks;\n\nclass Program\n{\n async Task A()\n {\n return await (null as Task); }\n}\");\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]\n [WorkItem(1345322, \"https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1345322\")]\n public async Task TestOnTaskTypeItself()\n {\n await TestMissingAsync(\n@\"using System.Threading.Tasks;\n\nclass Program\n{\n static async [||]Task Main(string[] args)\n {\n }\n}\n\");\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":481,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolutionResult.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Text;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp\n{\n internal sealed class BinaryOperatorOverloadResolutionResult\n {\n public readonly ArrayBuilder Results;\n\n private BinaryOperatorOverloadResolutionResult()\n {\n this.Results = new ArrayBuilder(10);\n }\n\n public bool AnyValid()\n {\n foreach (var result in Results)\n {\n if (result.IsValid)\n {\n return true;\n }\n }\n\n return false;\n }\n\n public bool SingleValid()\n {\n bool oneValid = false;\n foreach (var result in Results)\n {\n if (result.IsValid)\n {\n if (oneValid)\n {\n return false;\n }\n\n oneValid = true;\n }\n }\n\n return oneValid;\n }\n\n public BinaryOperatorAnalysisResult Best\n {\n get\n {\n BinaryOperatorAnalysisResult best = default(BinaryOperatorAnalysisResult);\n foreach (var result in Results)\n {\n if (result.IsValid)\n {\n if (best.IsValid)\n {\n // More than one best applicable method\n return default(BinaryOperatorAnalysisResult);\n }\n best = result;\n }\n }\n\n return best;\n }\n }\n\n#if DEBUG\n public string Dump()\n {\n if (Results.Count == 0)\n {\n return \"Overload resolution failed because there were no candidate operators.\";\n }\n\n var sb = new StringBuilder();\n if (this.Best.HasValue)\n {\n sb.AppendLine(\"Overload resolution succeeded and chose \" + this.Best.Signature.ToString());\n }\n else if (CountKind(OperatorAnalysisResultKind.Applicable) > 1)\n {\n sb.AppendLine(\"Overload resolution failed because of ambiguous possible best operators.\");\n }\n else\n {\n sb.AppendLine(\"Overload resolution failed because no operator was applicable.\");\n }\n\n sb.AppendLine(\"Detailed results:\");\n foreach (var result in Results)\n {\n sb.AppendFormat(\"operator: {0} reason: {1}\\n\", result.Signature.ToString(), result.Kind.ToString());\n }\n\n return sb.ToString();\n }\n\n private int CountKind(OperatorAnalysisResultKind kind)\n {\n int count = 0;\n for (int i = 0, n = this.Results.Count; i < n; i++)\n {\n if (this.Results[i].Kind == kind)\n {\n count++;\n }\n }\n\n return count;\n }\n#endif\n\n #region \"Poolable\"\n\n public static BinaryOperatorOverloadResolutionResult GetInstance()\n {\n return Pool.Allocate();\n }\n\n public void Free()\n {\n Clear();\n Pool.Free(this);\n }\n\n public void Clear()\n {\n this.Results.Clear();\n }\n\n public static readonly ObjectPool Pool = CreatePool();\n\n private static ObjectPool CreatePool()\n {\n ObjectPool pool = null;\n pool = new ObjectPool(() => new BinaryOperatorOverloadResolutionResult(), 10);\n return pool;\n }\n\n #endregion\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System.Text;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp\n{\n internal sealed class BinaryOperatorOverloadResolutionResult\n {\n public readonly ArrayBuilder Results;\n\n private BinaryOperatorOverloadResolutionResult()\n {\n this.Results = new ArrayBuilder(10);\n }\n\n public bool AnyValid()\n {\n foreach (var result in Results)\n {\n if (result.IsValid)\n {\n return true;\n }\n }\n\n return false;\n }\n\n public bool SingleValid()\n {\n bool oneValid = false;\n foreach (var result in Results)\n {\n if (result.IsValid)\n {\n if (oneValid)\n {\n return false;\n }\n\n oneValid = true;\n }\n }\n\n return oneValid;\n }\n\n public BinaryOperatorAnalysisResult Best\n {\n get\n {\n BinaryOperatorAnalysisResult best = default(BinaryOperatorAnalysisResult);\n foreach (var result in Results)\n {\n if (result.IsValid)\n {\n if (best.IsValid)\n {\n // More than one best applicable method\n return default(BinaryOperatorAnalysisResult);\n }\n best = result;\n }\n }\n\n return best;\n }\n }\n\n#if DEBUG\n public string Dump()\n {\n if (Results.Count == 0)\n {\n return \"Overload resolution failed because there were no candidate operators.\";\n }\n\n var sb = new StringBuilder();\n if (this.Best.HasValue)\n {\n sb.AppendLine(\"Overload resolution succeeded and chose \" + this.Best.Signature.ToString());\n }\n else if (CountKind(OperatorAnalysisResultKind.Applicable) > 1)\n {\n sb.AppendLine(\"Overload resolution failed because of ambiguous possible best operators.\");\n }\n else\n {\n sb.AppendLine(\"Overload resolution failed because no operator was applicable.\");\n }\n\n sb.AppendLine(\"Detailed results:\");\n foreach (var result in Results)\n {\n sb.AppendFormat(\"operator: {0} reason: {1}\\n\", result.Signature.ToString(), result.Kind.ToString());\n }\n\n return sb.ToString();\n }\n\n private int CountKind(OperatorAnalysisResultKind kind)\n {\n int count = 0;\n for (int i = 0, n = this.Results.Count; i < n; i++)\n {\n if (this.Results[i].Kind == kind)\n {\n count++;\n }\n }\n\n return count;\n }\n#endif\n\n #region \"Poolable\"\n\n public static BinaryOperatorOverloadResolutionResult GetInstance()\n {\n return Pool.Allocate();\n }\n\n public void Free()\n {\n Clear();\n Pool.Free(this);\n }\n\n public void Clear()\n {\n this.Results.Clear();\n }\n\n public static readonly ObjectPool Pool = CreatePool();\n\n private static ObjectPool CreatePool()\n {\n ObjectPool pool = null;\n pool = new ObjectPool(() => new BinaryOperatorOverloadResolutionResult(), 10);\n return pool;\n }\n\n #endregion\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":482,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesProgress.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nnamespace Microsoft.CodeAnalysis.FindSymbols\n{\n /// \n /// A does-nothing version of the . Useful for\n /// clients that have no need to report progress as they work.\n /// \n internal class NoOpFindReferencesProgress : IFindReferencesProgress\n {\n public static readonly IFindReferencesProgress Instance = new NoOpFindReferencesProgress();\n\n private NoOpFindReferencesProgress()\n {\n }\n\n public void ReportProgress(int current, int maximum)\n {\n }\n\n public void OnCompleted()\n {\n }\n\n public void OnStarted()\n {\n }\n\n public void OnDefinitionFound(ISymbol symbol)\n {\n }\n\n public void OnReferenceFound(ISymbol symbol, ReferenceLocation location)\n {\n }\n\n public void OnFindInDocumentStarted(Document document)\n {\n }\n\n public void OnFindInDocumentCompleted(Document document)\n {\n }\n }\n}\n"},"after_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nnamespace Microsoft.CodeAnalysis.FindSymbols\n{\n /// \n /// A does-nothing version of the . Useful for\n /// clients that have no need to report progress as they work.\n /// \n internal class NoOpFindReferencesProgress : IFindReferencesProgress\n {\n public static readonly IFindReferencesProgress Instance = new NoOpFindReferencesProgress();\n\n private NoOpFindReferencesProgress()\n {\n }\n\n public void ReportProgress(int current, int maximum)\n {\n }\n\n public void OnCompleted()\n {\n }\n\n public void OnStarted()\n {\n }\n\n public void OnDefinitionFound(ISymbol symbol)\n {\n }\n\n public void OnReferenceFound(ISymbol symbol, ReferenceLocation location)\n {\n }\n\n public void OnFindInDocumentStarted(Document document)\n {\n }\n\n public void OnFindInDocumentCompleted(Document document)\n {\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":483,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56460,"string":"56,460"},"pr_title":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets"},"pr_description":{"kind":"string","value":"This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"author":{"kind":"string","value":"eerhardt"},"date_created":{"kind":"timestamp","value":"2021-09-16T21:47:36Z","string":"2021-09-16T21:47:36Z"},"date_merged":{"kind":"timestamp","value":"2021-09-22T00:53:07Z","string":"2021-09-22T00:53:07Z"},"previous_commit":{"kind":"string","value":"a10a3720229de8f4227e98736e884d6f926a9950"},"pr_commit":{"kind":"string","value":"aabc2fcbf630ba303e6f17808465349ea9b01a32"},"query":{"kind":"string","value":"Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used.\r\nThis is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets.\r\n\r\nContributes to #52265\r\n\r\nFYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803"},"filepath":{"kind":"string","value":"./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs"},"before_content":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n#nullable disable\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text;\nusing Microsoft.CodeAnalysis.CSharp.Symbols;\nusing Microsoft.CodeAnalysis.CSharp.Syntax;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.CSharp\n{\n /// \n /// An abstract flow pass that takes some shortcuts in analyzing finally blocks, in order to enable\n /// the analysis to take place without tracking exceptions or repeating the analysis of a finally block\n /// for each exit from a try statement. The shortcut results in a slightly less precise\n /// (but still conservative) analysis, but that less precise analysis is all that is required for\n /// the language specification. The most significant shortcut is that we do not track the state\n /// where exceptions can arise. That does not affect the soundness for most analyses, but for those\n /// analyses whose soundness would be affected (e.g. \"data flows out\"), we track \"unassignments\" to keep\n /// the analysis sound.\n /// \n /// \n /// Formally, this is a fairly conventional lattice flow analysis () that moves upward through the operation.\n /// \n internal abstract partial class AbstractFlowPass : BoundTreeVisitor\n where TLocalState : AbstractFlowPass.ILocalState\n where TLocalFunctionState : AbstractFlowPass.AbstractLocalFunctionState\n {\n protected int _recursionDepth;\n\n /// \n /// The compilation in which the analysis is taking place. This is needed to determine which\n /// conditional methods will be compiled and which will be omitted.\n /// \n protected readonly CSharpCompilation compilation;\n\n /// \n /// The method whose body is being analyzed, or the field whose initializer is being analyzed.\n /// May be a top-level member or a lambda or local function. It is used for\n /// references to method parameters. Thus, '_symbol' should not be used directly, but\n /// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used\n /// instead. _symbol is null during speculative binding.\n /// \n protected readonly Symbol _symbol;\n\n /// \n /// Reflects the enclosing member, lambda or local function at the current location (in the bound tree).\n /// \n protected Symbol CurrentSymbol;\n\n /// \n /// The bound node of the method or initializer being analyzed.\n /// \n protected readonly BoundNode methodMainNode;\n\n /// \n /// The flow analysis state at each label, computed by calling on the state from branches to that label with the state\n /// when we fall into the label. Entries are created when the label is encountered. One\n /// case deserves special attention: when the destination of the branch is a label earlier\n /// in the code, it is possible (though rarely occurs in practice) that we are changing the\n /// state at a label that we've already analyzed. In that case we run another pass of the\n /// analysis to allow those changes to propagate. This repeats until no further changes to\n /// the state of these labels occurs. This can result in quadratic performance in unlikely\n /// but possible code such as this: \"int x; if (cond) goto l1; x = 3; l5: print x; l4: goto\n /// l5; l3: goto l4; l2: goto l3; l1: goto l2;\"\n /// \n private readonly PooledDictionary _labels;\n\n /// \n /// Set to true after an analysis scan if the analysis was incomplete due to state changing\n /// after it was used by another analysis component. In this case the caller scans again (until\n /// this is false). Since the analysis proceeds by monotonically changing the state computed\n /// at each label, this must terminate.\n /// \n protected bool stateChangedAfterUse;\n\n /// \n /// All of the labels seen so far in this forward scan of the body\n /// \n private PooledHashSet _labelsSeen;\n\n /// \n /// Pending escapes generated in the current scope (or more deeply nested scopes). When jump\n /// statements (goto, break, continue, return) are processed, they are placed in the\n /// pendingBranches buffer to be processed later by the code handling the destination\n /// statement. As a special case, the processing of try-finally statements might modify the\n /// contents of the pendingBranches buffer to take into account the behavior of\n /// \"intervening\" finally clauses.\n /// \n protected ArrayBuilder PendingBranches { get; private set; }\n\n /// \n /// The definite assignment and/or reachability state at the point currently being analyzed.\n /// \n protected TLocalState State;\n protected TLocalState StateWhenTrue;\n protected TLocalState StateWhenFalse;\n protected bool IsConditionalState;\n\n /// \n /// Indicates that the transfer function for a particular node (the function mapping the\n /// state before the node to the state after the node) is not monotonic, in the sense that\n /// it can change the state in either direction in the lattice. If the transfer function is\n /// monotonic, the transfer function can only change the state toward the . Reachability and definite assignment are monotonic, and\n /// permit a more efficient analysis. Region analysis and nullable analysis are not\n /// monotonic. This is just an optimization; we could treat all of them as nonmonotonic\n /// without much loss of performance. In fact, this only affects the analysis of (relatively\n /// rare) try statements, and is only a slight optimization.\n /// \n private readonly bool _nonMonotonicTransfer;\n\n protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state)\n {\n SetConditionalState(state.whenTrue, state.whenFalse);\n }\n\n protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse)\n {\n IsConditionalState = true;\n State = default(TLocalState);\n StateWhenTrue = whenTrue;\n StateWhenFalse = whenFalse;\n }\n\n protected void SetState(TLocalState newState)\n {\n Debug.Assert(newState != null);\n StateWhenTrue = StateWhenFalse = default(TLocalState);\n IsConditionalState = false;\n State = newState;\n }\n\n protected void Split()\n {\n if (!IsConditionalState)\n {\n SetConditionalState(State, State.Clone());\n }\n }\n\n protected void Unsplit()\n {\n if (IsConditionalState)\n {\n Join(ref StateWhenTrue, ref StateWhenFalse);\n SetState(StateWhenTrue);\n }\n }\n\n /// \n /// Where all diagnostics are deposited.\n /// \n protected DiagnosticBag Diagnostics { get; }\n\n #region Region\n // For region analysis, we maintain some extra data.\n protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region\n protected readonly BoundNode firstInRegion, lastInRegion;\n protected readonly bool TrackingRegions;\n\n /// \n /// A cache of the state at the backward branch point of each loop. This is not needed\n /// during normal flow analysis, but is needed for DataFlowsOut region analysis.\n /// \n private readonly Dictionary _loopHeadState;\n #endregion Region\n\n protected AbstractFlowPass(\n CSharpCompilation compilation,\n Symbol symbol,\n BoundNode node,\n BoundNode firstInRegion = null,\n BoundNode lastInRegion = null,\n bool trackRegions = false,\n bool nonMonotonicTransferFunction = false)\n {\n Debug.Assert(node != null);\n\n if (firstInRegion != null && lastInRegion != null)\n {\n trackRegions = true;\n }\n\n if (trackRegions)\n {\n Debug.Assert(firstInRegion != null);\n Debug.Assert(lastInRegion != null);\n int startLocation = firstInRegion.Syntax.SpanStart;\n int endLocation = lastInRegion.Syntax.Span.End;\n int length = endLocation - startLocation;\n Debug.Assert(length >= 0, \"last comes before first\");\n this.RegionSpan = new TextSpan(startLocation, length);\n }\n\n PendingBranches = ArrayBuilder.GetInstance();\n _labelsSeen = PooledHashSet.GetInstance();\n _labels = PooledDictionary.GetInstance();\n this.Diagnostics = DiagnosticBag.GetInstance();\n this.compilation = compilation;\n _symbol = symbol;\n CurrentSymbol = symbol;\n this.methodMainNode = node;\n this.firstInRegion = firstInRegion;\n this.lastInRegion = lastInRegion;\n _loopHeadState = new Dictionary(ReferenceEqualityComparer.Instance);\n TrackingRegions = trackRegions;\n _nonMonotonicTransfer = nonMonotonicTransferFunction;\n }\n\n protected abstract string Dump(TLocalState state);\n\n protected string Dump()\n {\n return IsConditionalState\n ? $\"true: {Dump(this.StateWhenTrue)} false: {Dump(this.StateWhenFalse)}\"\n : Dump(this.State);\n }\n\n#if DEBUG\n protected string DumpLabels()\n {\n StringBuilder result = new StringBuilder();\n result.Append(\"Labels{\");\n bool first = true;\n foreach (var key in _labels.Keys)\n {\n if (!first)\n {\n result.Append(\", \");\n }\n\n string name = key.Name;\n if (string.IsNullOrEmpty(name))\n {\n name = \"