susnato/csharp_PRs · Datasets at Fast360
{
// 获取包含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 Run Code &Analysis on Selection \n &Uruchom analizę kodu dla zaznaczenia \n \n \n \n &Current Document \n &Bieżący dokument \n \n \n \n AnalysisScopeCurrentDocument \n AnalysisScopeCurrentDocument \n \n \n \n Current Document \n Bieżący dokument \n \n \n \n &Default \n &Domyślny \n \n \n \n AnalysisScopeDefault \n AnalysisScopeDefault \n \n \n \n Default \n Domyślny \n \n \n \n &Entire Solution \n &Całe rozwiązanie \n \n \n \n AnalysisScopeEntireSolution \n AnalysisScopeEntireSolution \n \n \n \n Entire Solution \n Całe rozwiązanie \n \n \n \n &Open Documents \n &Otwórz dokumenty \n \n \n \n AnalysisScopeOpenDocuments \n AnalysisScopeOpenDocuments \n \n \n \n Open Documents \n Otwórz dokumenty \n \n \n \n \n Set Analysis Scope \n Ustaw zakres analizy \n \n \n \n \n Sort &Usings \n Sortuj &użycia \n \n \n \n SortUsings \n SortUsings \n \n \n \n Remove &and Sort \n Usuń &i sortuj \n \n \n \n RemoveAndSort \n RemoveAndSort \n \n \n \n Remove &and Sort \n Usuń &i sortuj \n \n \n \n RemoveAndSort \n RemoveAndSort \n \n \n \n &Default \n &Default \n \n \n \n ErrorListSetSeverityDefault \n ErrorListSetSeverityDefault \n \n \n \n Default \n Default \n \n \n \n &Error \n &Error \n \n \n \n ErrorListSetSeverityError \n ErrorListSetSeverityError \n \n \n \n Error \n Error \n \n \n \n &Silent \n &Silent \n \n \n \n ErrorListSetSeverityHidden \n ErrorListSetSeverityHidden \n \n \n \n Silent \n Silent \n \n \n \n &Suggestion \n &Suggestion \n \n \n \n ErrorListSetSeverityInfo \n ErrorListSetSeverityInfo \n \n \n \n Suggestion \n Suggestion \n \n \n \n &None \n &None \n \n \n \n ErrorListSetSeverityNone \n ErrorListSetSeverityNone \n \n \n \n None \n None \n \n \n \n \n Set severity \n Set severity \n \n \n \n \n &Warning \n &Warning \n \n \n \n ErrorListSetSeverityWarning \n ErrorListSetSeverityWarning \n \n \n \n Warning \n Warning \n \n \n \n &Analyzer... \n &Analizator... \n \n \n \n AddAnalyzer \n AddAnalyzer \n \n \n \n Add &Analyzer... \n Dodaj &analizator... \n \n \n \n AddAnalyzer \n AddAnalyzer \n \n \n \n Add &Analyzer... \n Dodaj &analizator... \n \n \n \n AddAnalyzer \n AddAnalyzer \n \n \n \n Add &Analyzer... \n Dodaj &analizator... \n \n \n \n AddAnalyzer \n AddAnalyzer \n \n \n \n &Remove \n &Usuń \n \n \n \n RemoveAnalyzer \n RemoveAnalyzer \n \n \n \n RemoveAnalyzer \n RemoveAnalyzer \n \n \n \n &Open Active Rule Set \n &Otwórz aktywny zestaw reguł \n \n \n \n OpenActiveRuleSet \n OpenActiveRuleSet \n \n \n \n OpenActiveRuleSet \n OpenActiveRuleSet \n \n \n \n Remove Unused References... \n Usuń nieużywane odwołania... \n \n \n \n RemoveUnusedReferences \n RemoveUnusedReferences \n \n \n \n RemoveUnusedReferences \n RemoveUnusedReferences \n \n \n \n Run C&ode Analysis \n Uru&chom analizę kodu \n \n \n \n RunCodeAnalysisForProject \n RunCodeAnalysisForProject \n \n \n \n RunCodeAnalysisForProject \n RunCodeAnalysisForProject \n \n \n \n &Default \n &Domyślny \n \n \n \n Default \n Domyślny \n \n \n \n SetSeverityDefault \n SetSeverityDefault \n \n \n \n &Error \n &Błąd \n \n \n \n Error \n Błąd \n \n \n \n SetSeverityError \n SetSeverityError \n \n \n \n &Warning \n &Ostrzeżenie \n \n \n \n Warning \n Ostrzeżenie \n \n \n \n SetSeverityWarning \n SetSeverityWarning \n \n \n \n &Suggestion \n &Sugestia \n \n \n \n Suggestion \n Sugestia \n \n \n \n SetSeverityInfo \n SetSeverityInfo \n \n \n \n &Silent \n &Dyskretne \n \n \n \n Silent \n Dyskretne \n \n \n \n SetSeverityHidden \n SetSeverityHidden \n \n \n \n &None \n &Brak \n \n \n \n None \n brak \n \n \n \n SetSeverityNone \n SetSeverityNone \n \n \n \n &View Help... \n &Pokaż pomoc... \n \n \n \n ViewHelp \n ViewHelp \n \n \n \n ViewHelp \n ViewHelp \n \n \n \n &Set as Active Rule Set \n &Ustaw jako aktywny zestaw reguł \n \n \n \n SetAsActiveRuleSet \n SetAsActiveRuleSet \n \n \n \n SetAsActiveRuleSet \n SetAsActiveRuleSet \n \n \n \n Remove& Suppression(s) \n Usuń &pominięcia \n \n \n \n RemoveSuppressions \n RemoveSuppressions \n \n \n \n RemoveSuppressions \n RemoveSuppressions \n \n \n \n In &Source \n W źró&dle \n \n \n \n AddSuppressionsInSource \n AddSuppressionsInSource \n \n \n \n AddSuppressionsInSource \n AddSuppressionsInSource \n \n \n \n In& Suppression File \n W pli&ku pominięć \n \n \n \n AddSuppressionsInSuppressionFile \n AddSuppressionsInSuppressionFile \n \n \n \n AddSuppressionsInSuppressionFile \n AddSuppressionsInSuppressionFile \n \n \n \n Go To Implementation \n Przejdź do implementacji \n \n \n \n GoToImplementation \n GoToImplementation \n \n \n \n Go To Implementation \n Przejdź do implementacji \n \n \n \n Sync &Namespaces \n Synchronizuj &przestrzenie nazw \n \n \n \n SyncNamespaces \n SyncNamespaces \n \n \n \n SyncNamespaces \n SyncNamespaces \n \n \n \n Track Value Source \n Śledź źródło wartości \n \n \n \n ShowValueTrackingCommandName \n ShowValueTrackingCommandName \n \n \n \n ViewEditorConfigSettings \n ViewEditorConfigSettings \n \n \n \n Initialize Interactive with Project \n Inicjuj środowisko interaktywne z projektem \n \n \n \n ResetC#InteractiveFromProject \n ResetC#InteractiveFromProject \n \n \n \n Reset Visual Basic Interactive from Project \n Resetuj środowisko interaktywne z projektu programu Visual Basic \n \n \n \n ResetVisualBasicInteractiveFromProject \n ResetVisualBasicInteractiveFromProject \n \n \n \n \n \n \n \n \n \n \n Set severity \n Ustaw ważność \n \n \n \n \n \n \n S&uppress \n P&omiń \n \n \n \n \n "},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1128,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentCrefBinder_TypeParameters.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 Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\nImports System.Runtime.InteropServices\n\nNamespace Microsoft.CodeAnalysis.VisualBasic\n\n Partial Friend NotInheritable Class DocumentationCommentCrefBinder\n Inherits DocumentationCommentBinder\n\n Private NotInheritable Class TypeParametersBinder\n Inherits Binder\n\n Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)\n\n Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol))\n MyBase.New(containingBinder)\n Me._typeParameters = typeParameters\n End Sub\n\n Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult,\n name As String,\n arity As Integer,\n options As LookupOptions,\n originalBinder As Binder,\n <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol))\n Debug.Assert(lookupResult.IsClear)\n\n Dim typeParameter As CrefTypeParameterSymbol = Nothing\n If Me._typeParameters.TryGetValue(name, typeParameter) Then\n lookupResult.SetFrom(CheckViability(typeParameter,\n arity,\n options Or LookupOptions.IgnoreAccessibility,\n Nothing,\n useSiteInfo))\n End If\n End Sub\n\n Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo,\n options As LookupOptions,\n originalBinder As Binder)\n\n For Each typeParameter In _typeParameters.Values\n If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then\n nameSet.AddSymbol(typeParameter, typeParameter.Name, 0)\n End If\n Next\n End Sub\n End Class\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\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic.Symbols\nImports Microsoft.CodeAnalysis.VisualBasic.Syntax\nImports System.Runtime.InteropServices\n\nNamespace Microsoft.CodeAnalysis.VisualBasic\n\n Partial Friend NotInheritable Class DocumentationCommentCrefBinder\n Inherits DocumentationCommentBinder\n\n Private NotInheritable Class TypeParametersBinder\n Inherits Binder\n\n Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)\n\n Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol))\n MyBase.New(containingBinder)\n Me._typeParameters = typeParameters\n End Sub\n\n Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult,\n name As String,\n arity As Integer,\n options As LookupOptions,\n originalBinder As Binder,\n <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol))\n Debug.Assert(lookupResult.IsClear)\n\n Dim typeParameter As CrefTypeParameterSymbol = Nothing\n If Me._typeParameters.TryGetValue(name, typeParameter) Then\n lookupResult.SetFrom(CheckViability(typeParameter,\n arity,\n options Or LookupOptions.IgnoreAccessibility,\n Nothing,\n useSiteInfo))\n End If\n End Sub\n\n Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo,\n options As LookupOptions,\n originalBinder As Binder)\n\n For Each typeParameter In _typeParameters.Values\n If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then\n nameSet.AddSymbol(typeParameter, typeParameter.Name, 0)\n End If\n Next\n End Sub\n End Class\n\n End Class\n\nEnd Namespace\n\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1129,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Features/CSharp/Portable/Completion/KeywordRecommenders/AndKeywordRecommender.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 AndKeywordRecommender : AbstractSyntacticSingleKeywordRecommender\n {\n public AndKeywordRecommender()\n : base(SyntaxKind.AndKeyword)\n {\n }\n\n protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)\n {\n return context.IsAtEndOfPattern;\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 AndKeywordRecommender : AbstractSyntacticSingleKeywordRecommender\n {\n public AndKeywordRecommender()\n : base(SyntaxKind.AndKeyword)\n {\n }\n\n protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)\n {\n return context.IsAtEndOfPattern;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1130,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.TempPEProject.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.IO\nImports System.Runtime.InteropServices.ComTypes\nImports Microsoft.CodeAnalysis\nImports Microsoft.CodeAnalysis.Host\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic\nImports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop\nImports Microsoft.VisualStudio.Shell.Interop\n\nNamespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim\n Partial Friend Class TempPECompiler\n Private Class TempPEProject\n Implements IVbCompilerProject\n\n Private ReadOnly _compilerHost As IVbCompilerHost\n Private ReadOnly _references As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)\n Private ReadOnly _files As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)\n\n Private _parseOptions As VisualBasicParseOptions\n Private _compilationOptions As VisualBasicCompilationOptions\n Private _outputPath As String\n Private _runtimeLibraries As ImmutableArray(Of String)\n\n Public Sub New(compilerHost As IVbCompilerHost)\n _compilerHost = compilerHost\n End Sub\n\n Public Function CompileAndGetErrorCount(metadataService As IMetadataService) As Integer\n Dim trees = _files.Select(Function(path)\n Using stream = FileUtilities.OpenRead(path)\n Return SyntaxFactory.ParseSyntaxTree(SourceText.From(stream), options:=_parseOptions, path:=path)\n End Using\n End Function)\n\n Dim metadataReferences = _references.Concat(_runtimeLibraries) _\n .Distinct(StringComparer.InvariantCultureIgnoreCase) _\n .Select(Function(path) metadataService.GetReference(path, MetadataReferenceProperties.Assembly))\n\n Dim c = VisualBasicCompilation.Create(\n Path.GetFileName(_outputPath),\n trees,\n metadataReferences,\n _compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default))\n\n Dim emitResult = c.Emit(_outputPath)\n\n Return emitResult.Diagnostics.Where(Function(d) d.Severity = DiagnosticSeverity.Error).Count()\n End Function\n\n Public Sub AddApplicationObjectVariable(wszClassName As String, wszMemberName As String) Implements IVbCompilerProject.AddApplicationObjectVariable\n Throw New NotImplementedException()\n End Sub\n\n Public Sub AddBuffer(wszBuffer As String, dwLen As Integer, wszMkr As String, itemid As UInteger, fAdvise As Boolean, fShowErrorsInTaskList As Boolean) Implements IVbCompilerProject.AddBuffer\n Throw New NotImplementedException()\n End Sub\n\n Public Function AddEmbeddedMetaDataReference(wszFileName As String) As Integer Implements IVbCompilerProject.AddEmbeddedMetaDataReference\n Return VSConstants.E_NOTIMPL\n End Function\n\n Public Sub AddEmbeddedProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddEmbeddedProjectReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub AddFile(wszFileName As String, itemid As UInteger, fAddDuringOpen As Boolean) Implements IVbCompilerProject.AddFile\n ' We are only ever given VSITEMIDs that are Nil because a TempPE project isn't\n ' associated with a IVsHierarchy.\n Contract.ThrowIfFalse(itemid = VSConstants.VSITEMID.Nil)\n\n _files.Add(wszFileName)\n End Sub\n\n Public Sub AddImport(wszImport As String) Implements IVbCompilerProject.AddImport\n Throw New NotImplementedException()\n End Sub\n\n Public Function AddMetaDataReference(wszFileName As String, bAssembly As Boolean) As Integer Implements IVbCompilerProject.AddMetaDataReference\n _references.Add(wszFileName)\n\n Return VSConstants.S_OK\n End Function\n\n Public Sub AddProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddProjectReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub AddResourceReference(wszFileName As String, wszName As String, fPublic As Boolean, fEmbed As Boolean) Implements IVbCompilerProject.AddResourceReference\n Throw New NotImplementedException()\n End Sub\n\n Public Function AdviseBuildStatusCallback(pIVbBuildStatusCallback As IVbBuildStatusCallback) As UInteger Implements IVbCompilerProject.AdviseBuildStatusCallback\n Throw New NotImplementedException()\n End Function\n\n Public Function CreateCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pCodeModel As EnvDTE.CodeModel) As Integer Implements IVbCompilerProject.CreateCodeModel\n Throw New NotImplementedException()\n End Function\n\n Public Function CreateFileCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pFileCodeModel As EnvDTE.FileCodeModel) As Integer Implements IVbCompilerProject.CreateFileCodeModel\n Throw New NotImplementedException()\n End Function\n\n Public Sub DeleteAllImports() Implements IVbCompilerProject.DeleteAllImports\n Throw New NotImplementedException()\n End Sub\n\n Public Sub DeleteAllResourceReferences() Implements IVbCompilerProject.DeleteAllResourceReferences\n Throw New NotImplementedException()\n End Sub\n\n Public Sub DeleteImport(wszImport As String) Implements IVbCompilerProject.DeleteImport\n Throw New NotImplementedException()\n End Sub\n\n Public Sub Disconnect() Implements IVbCompilerProject.Disconnect\n\n End Sub\n\n Public Function ENCRebuild(in_pProgram As Object, ByRef out_ppUpdate As Object) As Integer Implements IVbCompilerProject.ENCRebuild\n Throw New NotImplementedException()\n End Function\n\n Public Sub FinishEdit() Implements IVbCompilerProject.FinishEdit\n ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing\n ' expensive things between each call to one of the Add* methods. But since we're not\n ' doing anything expensive, this can be a no-op.\n End Sub\n\n Public Function GetDefaultReferences(cElements As Integer, ByRef rgbstrReferences() As String, ByVal cActualReferences As IntPtr) As Integer Implements IVbCompilerProject.GetDefaultReferences\n Throw New NotImplementedException()\n End Function\n\n Public Sub GetEntryPointsList(cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr) Implements IVbCompilerProject.GetEntryPointsList\n Throw New NotImplementedException()\n End Sub\n\n Public Sub GetMethodFromLine(itemid As UInteger, iLine As Integer, ByRef pBstrProcName As String, ByRef pBstrClassName As String) Implements IVbCompilerProject.GetMethodFromLine\n Throw New NotImplementedException()\n End Sub\n\n Public Sub GetPEImage(ByRef ppImage As IntPtr) Implements IVbCompilerProject.GetPEImage\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveAllApplicationObjectVariables() Implements IVbCompilerProject.RemoveAllApplicationObjectVariables\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveAllReferences() Implements IVbCompilerProject.RemoveAllReferences\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveFile(wszFileName As String, itemid As UInteger) Implements IVbCompilerProject.RemoveFile\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveFileByName(wszPath As String) Implements IVbCompilerProject.RemoveFileByName\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveMetaDataReference(wszFileName As String) Implements IVbCompilerProject.RemoveMetaDataReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.RemoveProjectReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RenameDefaultNamespace(bstrDefaultNamespace As String) Implements IVbCompilerProject.RenameDefaultNamespace\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RenameFile(wszOldFileName As String, wszNewFileName As String, itemid As UInteger) Implements IVbCompilerProject.RenameFile\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RenameProject(wszNewProjectName As String) Implements IVbCompilerProject.RenameProject\n Throw New NotImplementedException()\n End Sub\n\n Public Sub ResumePostedNotifications() Implements IVbCompilerProject.ResumePostedNotifications\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetBackgroundCompilerPriorityLow() Implements IVbCompilerProject.SetBackgroundCompilerPriorityLow\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetBackgroundCompilerPriorityNormal() Implements IVbCompilerProject.SetBackgroundCompilerPriorityNormal\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetCompilerOptions(ByRef pCompilerOptions As VBCompilerOptions) Implements IVbCompilerProject.SetCompilerOptions\n _runtimeLibraries = VisualBasicProject.OptionsProcessor.GetRuntimeLibraries(_compilerHost, pCompilerOptions)\n _outputPath = PathUtilities.CombinePathsUnchecked(pCompilerOptions.wszOutputPath, pCompilerOptions.wszExeName)\n _parseOptions = VisualBasicProject.OptionsProcessor.ApplyVisualBasicParseOptionsFromCompilerOptions(VisualBasicParseOptions.Default, pCompilerOptions)\n\n ' Note that we pass a \"default\" compilation options with DLL set as output kind; the Apply method will figure out what the right one is and fix it up\n _compilationOptions = VisualBasicProject.OptionsProcessor.ApplyCompilationOptionsFromVBCompilerOptions(\n New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=_parseOptions), pCompilerOptions)\n End Sub\n\n Public Sub SetModuleAssemblyName(wszName As String) Implements IVbCompilerProject.SetModuleAssemblyName\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetStreamForPDB(pStreamPDB As IStream) Implements IVbCompilerProject.SetStreamForPDB\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StartBuild(pVsOutputWindowPane As IVsOutputWindowPane, fRebuildAll As Boolean) Implements IVbCompilerProject.StartBuild\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StartDebugging() Implements IVbCompilerProject.StartDebugging\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StartEdit() Implements IVbCompilerProject.StartEdit\n ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing\n ' expensive things between each call to one of the Add* methods. But since we're not\n ' doing anything expensive, this can be a no-op.\n End Sub\n\n Public Sub StopBuild() Implements IVbCompilerProject.StopBuild\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StopDebugging() Implements IVbCompilerProject.StopDebugging\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SuspendPostedNotifications() Implements IVbCompilerProject.SuspendPostedNotifications\n Throw New NotImplementedException()\n End Sub\n\n Public Sub UnadviseBuildStatusCallback(dwCookie As UInteger) Implements IVbCompilerProject.UnadviseBuildStatusCallback\n Throw New NotImplementedException()\n End Sub\n\n Public Sub WaitUntilBound() Implements IVbCompilerProject.WaitUntilBound\n Throw New NotImplementedException()\n End Sub\n\n End Class\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.IO\nImports System.Runtime.InteropServices.ComTypes\nImports Microsoft.CodeAnalysis\nImports Microsoft.CodeAnalysis.Host\nImports Microsoft.CodeAnalysis.Text\nImports Microsoft.CodeAnalysis.VisualBasic\nImports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop\nImports Microsoft.VisualStudio.Shell.Interop\n\nNamespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim\n Partial Friend Class TempPECompiler\n Private Class TempPEProject\n Implements IVbCompilerProject\n\n Private ReadOnly _compilerHost As IVbCompilerHost\n Private ReadOnly _references As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)\n Private ReadOnly _files As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)\n\n Private _parseOptions As VisualBasicParseOptions\n Private _compilationOptions As VisualBasicCompilationOptions\n Private _outputPath As String\n Private _runtimeLibraries As ImmutableArray(Of String)\n\n Public Sub New(compilerHost As IVbCompilerHost)\n _compilerHost = compilerHost\n End Sub\n\n Public Function CompileAndGetErrorCount(metadataService As IMetadataService) As Integer\n Dim trees = _files.Select(Function(path)\n Using stream = FileUtilities.OpenRead(path)\n Return SyntaxFactory.ParseSyntaxTree(SourceText.From(stream), options:=_parseOptions, path:=path)\n End Using\n End Function)\n\n Dim metadataReferences = _references.Concat(_runtimeLibraries) _\n .Distinct(StringComparer.InvariantCultureIgnoreCase) _\n .Select(Function(path) metadataService.GetReference(path, MetadataReferenceProperties.Assembly))\n\n Dim c = VisualBasicCompilation.Create(\n Path.GetFileName(_outputPath),\n trees,\n metadataReferences,\n _compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default))\n\n Dim emitResult = c.Emit(_outputPath)\n\n Return emitResult.Diagnostics.Where(Function(d) d.Severity = DiagnosticSeverity.Error).Count()\n End Function\n\n Public Sub AddApplicationObjectVariable(wszClassName As String, wszMemberName As String) Implements IVbCompilerProject.AddApplicationObjectVariable\n Throw New NotImplementedException()\n End Sub\n\n Public Sub AddBuffer(wszBuffer As String, dwLen As Integer, wszMkr As String, itemid As UInteger, fAdvise As Boolean, fShowErrorsInTaskList As Boolean) Implements IVbCompilerProject.AddBuffer\n Throw New NotImplementedException()\n End Sub\n\n Public Function AddEmbeddedMetaDataReference(wszFileName As String) As Integer Implements IVbCompilerProject.AddEmbeddedMetaDataReference\n Return VSConstants.E_NOTIMPL\n End Function\n\n Public Sub AddEmbeddedProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddEmbeddedProjectReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub AddFile(wszFileName As String, itemid As UInteger, fAddDuringOpen As Boolean) Implements IVbCompilerProject.AddFile\n ' We are only ever given VSITEMIDs that are Nil because a TempPE project isn't\n ' associated with a IVsHierarchy.\n Contract.ThrowIfFalse(itemid = VSConstants.VSITEMID.Nil)\n\n _files.Add(wszFileName)\n End Sub\n\n Public Sub AddImport(wszImport As String) Implements IVbCompilerProject.AddImport\n Throw New NotImplementedException()\n End Sub\n\n Public Function AddMetaDataReference(wszFileName As String, bAssembly As Boolean) As Integer Implements IVbCompilerProject.AddMetaDataReference\n _references.Add(wszFileName)\n\n Return VSConstants.S_OK\n End Function\n\n Public Sub AddProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddProjectReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub AddResourceReference(wszFileName As String, wszName As String, fPublic As Boolean, fEmbed As Boolean) Implements IVbCompilerProject.AddResourceReference\n Throw New NotImplementedException()\n End Sub\n\n Public Function AdviseBuildStatusCallback(pIVbBuildStatusCallback As IVbBuildStatusCallback) As UInteger Implements IVbCompilerProject.AdviseBuildStatusCallback\n Throw New NotImplementedException()\n End Function\n\n Public Function CreateCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pCodeModel As EnvDTE.CodeModel) As Integer Implements IVbCompilerProject.CreateCodeModel\n Throw New NotImplementedException()\n End Function\n\n Public Function CreateFileCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pFileCodeModel As EnvDTE.FileCodeModel) As Integer Implements IVbCompilerProject.CreateFileCodeModel\n Throw New NotImplementedException()\n End Function\n\n Public Sub DeleteAllImports() Implements IVbCompilerProject.DeleteAllImports\n Throw New NotImplementedException()\n End Sub\n\n Public Sub DeleteAllResourceReferences() Implements IVbCompilerProject.DeleteAllResourceReferences\n Throw New NotImplementedException()\n End Sub\n\n Public Sub DeleteImport(wszImport As String) Implements IVbCompilerProject.DeleteImport\n Throw New NotImplementedException()\n End Sub\n\n Public Sub Disconnect() Implements IVbCompilerProject.Disconnect\n\n End Sub\n\n Public Function ENCRebuild(in_pProgram As Object, ByRef out_ppUpdate As Object) As Integer Implements IVbCompilerProject.ENCRebuild\n Throw New NotImplementedException()\n End Function\n\n Public Sub FinishEdit() Implements IVbCompilerProject.FinishEdit\n ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing\n ' expensive things between each call to one of the Add* methods. But since we're not\n ' doing anything expensive, this can be a no-op.\n End Sub\n\n Public Function GetDefaultReferences(cElements As Integer, ByRef rgbstrReferences() As String, ByVal cActualReferences As IntPtr) As Integer Implements IVbCompilerProject.GetDefaultReferences\n Throw New NotImplementedException()\n End Function\n\n Public Sub GetEntryPointsList(cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr) Implements IVbCompilerProject.GetEntryPointsList\n Throw New NotImplementedException()\n End Sub\n\n Public Sub GetMethodFromLine(itemid As UInteger, iLine As Integer, ByRef pBstrProcName As String, ByRef pBstrClassName As String) Implements IVbCompilerProject.GetMethodFromLine\n Throw New NotImplementedException()\n End Sub\n\n Public Sub GetPEImage(ByRef ppImage As IntPtr) Implements IVbCompilerProject.GetPEImage\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveAllApplicationObjectVariables() Implements IVbCompilerProject.RemoveAllApplicationObjectVariables\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveAllReferences() Implements IVbCompilerProject.RemoveAllReferences\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveFile(wszFileName As String, itemid As UInteger) Implements IVbCompilerProject.RemoveFile\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveFileByName(wszPath As String) Implements IVbCompilerProject.RemoveFileByName\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveMetaDataReference(wszFileName As String) Implements IVbCompilerProject.RemoveMetaDataReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RemoveProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.RemoveProjectReference\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RenameDefaultNamespace(bstrDefaultNamespace As String) Implements IVbCompilerProject.RenameDefaultNamespace\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RenameFile(wszOldFileName As String, wszNewFileName As String, itemid As UInteger) Implements IVbCompilerProject.RenameFile\n Throw New NotImplementedException()\n End Sub\n\n Public Sub RenameProject(wszNewProjectName As String) Implements IVbCompilerProject.RenameProject\n Throw New NotImplementedException()\n End Sub\n\n Public Sub ResumePostedNotifications() Implements IVbCompilerProject.ResumePostedNotifications\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetBackgroundCompilerPriorityLow() Implements IVbCompilerProject.SetBackgroundCompilerPriorityLow\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetBackgroundCompilerPriorityNormal() Implements IVbCompilerProject.SetBackgroundCompilerPriorityNormal\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetCompilerOptions(ByRef pCompilerOptions As VBCompilerOptions) Implements IVbCompilerProject.SetCompilerOptions\n _runtimeLibraries = VisualBasicProject.OptionsProcessor.GetRuntimeLibraries(_compilerHost, pCompilerOptions)\n _outputPath = PathUtilities.CombinePathsUnchecked(pCompilerOptions.wszOutputPath, pCompilerOptions.wszExeName)\n _parseOptions = VisualBasicProject.OptionsProcessor.ApplyVisualBasicParseOptionsFromCompilerOptions(VisualBasicParseOptions.Default, pCompilerOptions)\n\n ' Note that we pass a \"default\" compilation options with DLL set as output kind; the Apply method will figure out what the right one is and fix it up\n _compilationOptions = VisualBasicProject.OptionsProcessor.ApplyCompilationOptionsFromVBCompilerOptions(\n New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=_parseOptions), pCompilerOptions)\n End Sub\n\n Public Sub SetModuleAssemblyName(wszName As String) Implements IVbCompilerProject.SetModuleAssemblyName\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SetStreamForPDB(pStreamPDB As IStream) Implements IVbCompilerProject.SetStreamForPDB\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StartBuild(pVsOutputWindowPane As IVsOutputWindowPane, fRebuildAll As Boolean) Implements IVbCompilerProject.StartBuild\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StartDebugging() Implements IVbCompilerProject.StartDebugging\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StartEdit() Implements IVbCompilerProject.StartEdit\n ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing\n ' expensive things between each call to one of the Add* methods. But since we're not\n ' doing anything expensive, this can be a no-op.\n End Sub\n\n Public Sub StopBuild() Implements IVbCompilerProject.StopBuild\n Throw New NotImplementedException()\n End Sub\n\n Public Sub StopDebugging() Implements IVbCompilerProject.StopDebugging\n Throw New NotImplementedException()\n End Sub\n\n Public Sub SuspendPostedNotifications() Implements IVbCompilerProject.SuspendPostedNotifications\n Throw New NotImplementedException()\n End Sub\n\n Public Sub UnadviseBuildStatusCallback(dwCookie As UInteger) Implements IVbCompilerProject.UnadviseBuildStatusCallback\n Throw New NotImplementedException()\n End Sub\n\n Public Sub WaitUntilBound() Implements IVbCompilerProject.WaitUntilBound\n Throw New NotImplementedException()\n End Sub\n\n End Class\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1131,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/InternalUtilities/ReferenceEqualityComparer.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;\nusing System.Runtime.CompilerServices;\n\nnamespace Roslyn.Utilities\n{\n /// \n /// Compares objects based upon their reference identity.\n /// \n internal class ReferenceEqualityComparer : IEqualityComparer\n {\n public static readonly ReferenceEqualityComparer Instance = new();\n\n private ReferenceEqualityComparer()\n {\n }\n\n bool IEqualityComparer.Equals(object? a, object? b)\n {\n return a == b;\n }\n\n int IEqualityComparer.GetHashCode(object? a)\n {\n return ReferenceEqualityComparer.GetHashCode(a);\n }\n\n public static int GetHashCode(object? a)\n {\n // https://github.com/dotnet/roslyn/issues/41539\n return RuntimeHelpers.GetHashCode(a!);\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.Generic;\nusing System.Runtime.CompilerServices;\n\nnamespace Roslyn.Utilities\n{\n /// \n /// Compares objects based upon their reference identity.\n /// \n internal class ReferenceEqualityComparer : IEqualityComparer\n {\n public static readonly ReferenceEqualityComparer Instance = new();\n\n private ReferenceEqualityComparer()\n {\n }\n\n bool IEqualityComparer.Equals(object? a, object? b)\n {\n return a == b;\n }\n\n int IEqualityComparer.GetHashCode(object? a)\n {\n return ReferenceEqualityComparer.GetHashCode(a);\n }\n\n public static int GetHashCode(object? a)\n {\n // https://github.com/dotnet/roslyn/issues/41539\n return RuntimeHelpers.GetHashCode(a!);\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1132,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedProperty.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.Diagnostics;\nusing Microsoft.CodeAnalysis.CodeGen;\nusing Cci = Microsoft.Cci;\n\nnamespace Microsoft.CodeAnalysis.Emit.NoPia\n{\n internal abstract partial class EmbeddedTypesManager<\n TPEModuleBuilder,\n TModuleCompilationState,\n TEmbeddedTypesManager,\n TSyntaxNode,\n TAttributeData,\n TSymbol,\n TAssemblySymbol,\n TNamedTypeSymbol,\n TFieldSymbol,\n TMethodSymbol,\n TEventSymbol,\n TPropertySymbol,\n TParameterSymbol,\n TTypeParameterSymbol,\n TEmbeddedType,\n TEmbeddedField,\n TEmbeddedMethod,\n TEmbeddedEvent,\n TEmbeddedProperty,\n TEmbeddedParameter,\n TEmbeddedTypeParameter>\n {\n internal abstract class CommonEmbeddedProperty : CommonEmbeddedMember, Cci.IPropertyDefinition\n {\n private readonly ImmutableArray _parameters;\n private readonly TEmbeddedMethod _getter;\n private readonly TEmbeddedMethod _setter;\n\n protected CommonEmbeddedProperty(TPropertySymbol underlyingProperty, TEmbeddedMethod getter, TEmbeddedMethod setter) :\n base(underlyingProperty)\n {\n Debug.Assert(getter != null || setter != null);\n\n _getter = getter;\n _setter = setter;\n _parameters = GetParameters();\n }\n\n internal override TEmbeddedTypesManager TypeManager\n {\n get\n {\n return AnAccessor.TypeManager;\n }\n }\n\n protected abstract ImmutableArray GetParameters();\n protected abstract bool IsRuntimeSpecial { get; }\n protected abstract bool IsSpecialName { get; }\n protected abstract Cci.ISignature UnderlyingPropertySignature { get; }\n protected abstract TEmbeddedType ContainingType { get; }\n protected abstract Cci.TypeMemberVisibility Visibility { get; }\n protected abstract string Name { get; }\n\n public TPropertySymbol UnderlyingProperty\n {\n get\n {\n return this.UnderlyingSymbol;\n }\n }\n\n Cci.IMethodReference Cci.IPropertyDefinition.Getter\n {\n get { return _getter; }\n }\n\n Cci.IMethodReference Cci.IPropertyDefinition.Setter\n {\n get { return _setter; }\n }\n\n IEnumerable Cci.IPropertyDefinition.GetAccessors(EmitContext context)\n {\n if (_getter != null)\n {\n yield return _getter;\n }\n\n if (_setter != null)\n {\n yield return _setter;\n }\n }\n\n bool Cci.IPropertyDefinition.HasDefaultValue\n {\n get { return false; }\n }\n\n MetadataConstant Cci.IPropertyDefinition.DefaultValue\n {\n get { return null; }\n }\n\n bool Cci.IPropertyDefinition.IsRuntimeSpecial\n {\n get { return IsRuntimeSpecial; }\n }\n\n bool Cci.IPropertyDefinition.IsSpecialName\n {\n get\n {\n return IsSpecialName;\n }\n }\n\n ImmutableArray Cci.IPropertyDefinition.Parameters\n {\n get { return StaticCast.From(_parameters); }\n }\n\n Cci.CallingConvention Cci.ISignature.CallingConvention\n {\n get\n {\n return UnderlyingPropertySignature.CallingConvention;\n }\n }\n\n ushort Cci.ISignature.ParameterCount\n {\n get { return (ushort)_parameters.Length; }\n }\n\n ImmutableArray Cci.ISignature.GetParameters(EmitContext context)\n {\n return StaticCast.From(_parameters);\n }\n\n ImmutableArray Cci.ISignature.ReturnValueCustomModifiers\n {\n get\n {\n return UnderlyingPropertySignature.ReturnValueCustomModifiers;\n }\n }\n\n ImmutableArray Cci.ISignature.RefCustomModifiers\n {\n get\n {\n return UnderlyingPropertySignature.RefCustomModifiers;\n }\n }\n\n bool Cci.ISignature.ReturnValueIsByRef\n {\n get\n {\n return UnderlyingPropertySignature.ReturnValueIsByRef;\n }\n }\n\n Cci.ITypeReference Cci.ISignature.GetType(EmitContext context)\n {\n return UnderlyingPropertySignature.GetType(context);\n }\n\n protected TEmbeddedMethod AnAccessor\n {\n get\n {\n return _getter ?? _setter;\n }\n }\n\n Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition\n {\n get { return ContainingType; }\n }\n\n Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility\n {\n get\n {\n return Visibility;\n }\n }\n\n Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)\n {\n return ContainingType;\n }\n\n void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)\n {\n visitor.Visit((Cci.IPropertyDefinition)this);\n }\n\n Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)\n {\n return this;\n }\n\n string Cci.INamedEntity.Name\n {\n get\n {\n return Name;\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.Generic;\nusing System.Collections.Immutable;\nusing System.Diagnostics;\nusing Microsoft.CodeAnalysis.CodeGen;\nusing Cci = Microsoft.Cci;\n\nnamespace Microsoft.CodeAnalysis.Emit.NoPia\n{\n internal abstract partial class EmbeddedTypesManager<\n TPEModuleBuilder,\n TModuleCompilationState,\n TEmbeddedTypesManager,\n TSyntaxNode,\n TAttributeData,\n TSymbol,\n TAssemblySymbol,\n TNamedTypeSymbol,\n TFieldSymbol,\n TMethodSymbol,\n TEventSymbol,\n TPropertySymbol,\n TParameterSymbol,\n TTypeParameterSymbol,\n TEmbeddedType,\n TEmbeddedField,\n TEmbeddedMethod,\n TEmbeddedEvent,\n TEmbeddedProperty,\n TEmbeddedParameter,\n TEmbeddedTypeParameter>\n {\n internal abstract class CommonEmbeddedProperty : CommonEmbeddedMember, Cci.IPropertyDefinition\n {\n private readonly ImmutableArray _parameters;\n private readonly TEmbeddedMethod _getter;\n private readonly TEmbeddedMethod _setter;\n\n protected CommonEmbeddedProperty(TPropertySymbol underlyingProperty, TEmbeddedMethod getter, TEmbeddedMethod setter) :\n base(underlyingProperty)\n {\n Debug.Assert(getter != null || setter != null);\n\n _getter = getter;\n _setter = setter;\n _parameters = GetParameters();\n }\n\n internal override TEmbeddedTypesManager TypeManager\n {\n get\n {\n return AnAccessor.TypeManager;\n }\n }\n\n protected abstract ImmutableArray GetParameters();\n protected abstract bool IsRuntimeSpecial { get; }\n protected abstract bool IsSpecialName { get; }\n protected abstract Cci.ISignature UnderlyingPropertySignature { get; }\n protected abstract TEmbeddedType ContainingType { get; }\n protected abstract Cci.TypeMemberVisibility Visibility { get; }\n protected abstract string Name { get; }\n\n public TPropertySymbol UnderlyingProperty\n {\n get\n {\n return this.UnderlyingSymbol;\n }\n }\n\n Cci.IMethodReference Cci.IPropertyDefinition.Getter\n {\n get { return _getter; }\n }\n\n Cci.IMethodReference Cci.IPropertyDefinition.Setter\n {\n get { return _setter; }\n }\n\n IEnumerable Cci.IPropertyDefinition.GetAccessors(EmitContext context)\n {\n if (_getter != null)\n {\n yield return _getter;\n }\n\n if (_setter != null)\n {\n yield return _setter;\n }\n }\n\n bool Cci.IPropertyDefinition.HasDefaultValue\n {\n get { return false; }\n }\n\n MetadataConstant Cci.IPropertyDefinition.DefaultValue\n {\n get { return null; }\n }\n\n bool Cci.IPropertyDefinition.IsRuntimeSpecial\n {\n get { return IsRuntimeSpecial; }\n }\n\n bool Cci.IPropertyDefinition.IsSpecialName\n {\n get\n {\n return IsSpecialName;\n }\n }\n\n ImmutableArray Cci.IPropertyDefinition.Parameters\n {\n get { return StaticCast.From(_parameters); }\n }\n\n Cci.CallingConvention Cci.ISignature.CallingConvention\n {\n get\n {\n return UnderlyingPropertySignature.CallingConvention;\n }\n }\n\n ushort Cci.ISignature.ParameterCount\n {\n get { return (ushort)_parameters.Length; }\n }\n\n ImmutableArray Cci.ISignature.GetParameters(EmitContext context)\n {\n return StaticCast.From(_parameters);\n }\n\n ImmutableArray Cci.ISignature.ReturnValueCustomModifiers\n {\n get\n {\n return UnderlyingPropertySignature.ReturnValueCustomModifiers;\n }\n }\n\n ImmutableArray Cci.ISignature.RefCustomModifiers\n {\n get\n {\n return UnderlyingPropertySignature.RefCustomModifiers;\n }\n }\n\n bool Cci.ISignature.ReturnValueIsByRef\n {\n get\n {\n return UnderlyingPropertySignature.ReturnValueIsByRef;\n }\n }\n\n Cci.ITypeReference Cci.ISignature.GetType(EmitContext context)\n {\n return UnderlyingPropertySignature.GetType(context);\n }\n\n protected TEmbeddedMethod AnAccessor\n {\n get\n {\n return _getter ?? _setter;\n }\n }\n\n Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition\n {\n get { return ContainingType; }\n }\n\n Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility\n {\n get\n {\n return Visibility;\n }\n }\n\n Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)\n {\n return ContainingType;\n }\n\n void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)\n {\n visitor.Visit((Cci.IPropertyDefinition)this);\n }\n\n Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)\n {\n return this;\n }\n\n string Cci.INamedEntity.Name\n {\n get\n {\n return Name;\n }\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1133,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/RuleSet/RuleSetInclude.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 Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Represents a Include tag in a RuleSet file.\n /// \n public class RuleSetInclude\n {\n private readonly string _includePath;\n /// \n /// The path of the included file.\n /// \n public string IncludePath\n {\n get { return _includePath; }\n }\n\n private readonly ReportDiagnostic _action;\n /// \n /// The effective action to apply on this included ruleset.\n /// \n public ReportDiagnostic Action\n {\n get { return _action; }\n }\n\n /// \n /// Create a RuleSetInclude given the include path and the effective action.\n /// \n public RuleSetInclude(string includePath, ReportDiagnostic action)\n {\n _includePath = includePath;\n _action = action;\n }\n\n /// \n /// Gets the RuleSet associated with this ruleset include\n /// \n /// The parent of this ruleset include\n public RuleSet? LoadRuleSet(RuleSet parent)\n {\n // Try to load the rule set\n RuleSet? ruleSet = null;\n\n string? path = _includePath;\n try\n {\n path = GetIncludePath(parent);\n if (path == null)\n {\n return null;\n }\n\n ruleSet = RuleSetProcessor.LoadFromFile(path);\n }\n catch (FileNotFoundException)\n {\n // The compiler uses the same rule set files as FxCop, but doesn't have all of\n // the same logic for resolving included files. For the moment, just ignore any\n // includes we can't resolve.\n }\n catch (Exception e)\n {\n throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, path, e.Message));\n }\n\n return ruleSet;\n }\n\n /// \n /// Returns a full path to the include file. Relative paths are expanded relative to the current rule set file.\n /// \n /// The parent of this rule set include\n private string? GetIncludePath(RuleSet parent)\n {\n var resolvedIncludePath = resolveIncludePath(_includePath, parent?.FilePath);\n if (resolvedIncludePath == null)\n {\n return null;\n }\n\n // Return the canonical full path\n return Path.GetFullPath(resolvedIncludePath);\n\n static string? resolveIncludePath(string includePath, string? parentRulesetPath)\n {\n var resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath);\n if (resolvedIncludePath == null && PathUtilities.IsUnixLikePlatform)\n {\n // Attempt to resolve legacy ruleset includes after replacing Windows style directory separator char with current plaform's directory separator char.\n includePath = includePath.Replace('\\\\', Path.DirectorySeparatorChar);\n resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath);\n }\n\n return resolvedIncludePath;\n }\n\n static string? resolveIncludePathCore(string includePath, string? parentRulesetPath)\n {\n includePath = Environment.ExpandEnvironmentVariables(includePath);\n\n // If a full path is specified then use it\n if (Path.IsPathRooted(includePath))\n {\n if (File.Exists(includePath))\n {\n return includePath;\n }\n }\n else if (!string.IsNullOrEmpty(parentRulesetPath))\n {\n // Otherwise, try to find the include file relative to the parent ruleset.\n includePath = PathUtilities.CombinePathsUnchecked(Path.GetDirectoryName(parentRulesetPath) ?? \"\", includePath);\n if (File.Exists(includePath))\n {\n return includePath;\n }\n }\n\n return null;\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 Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis\n{\n /// \n /// Represents a Include tag in a RuleSet file.\n /// \n public class RuleSetInclude\n {\n private readonly string _includePath;\n /// \n /// The path of the included file.\n /// \n public string IncludePath\n {\n get { return _includePath; }\n }\n\n private readonly ReportDiagnostic _action;\n /// \n /// The effective action to apply on this included ruleset.\n /// \n public ReportDiagnostic Action\n {\n get { return _action; }\n }\n\n /// \n /// Create a RuleSetInclude given the include path and the effective action.\n /// \n public RuleSetInclude(string includePath, ReportDiagnostic action)\n {\n _includePath = includePath;\n _action = action;\n }\n\n /// \n /// Gets the RuleSet associated with this ruleset include\n /// \n /// The parent of this ruleset include\n public RuleSet? LoadRuleSet(RuleSet parent)\n {\n // Try to load the rule set\n RuleSet? ruleSet = null;\n\n string? path = _includePath;\n try\n {\n path = GetIncludePath(parent);\n if (path == null)\n {\n return null;\n }\n\n ruleSet = RuleSetProcessor.LoadFromFile(path);\n }\n catch (FileNotFoundException)\n {\n // The compiler uses the same rule set files as FxCop, but doesn't have all of\n // the same logic for resolving included files. For the moment, just ignore any\n // includes we can't resolve.\n }\n catch (Exception e)\n {\n throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, path, e.Message));\n }\n\n return ruleSet;\n }\n\n /// \n /// Returns a full path to the include file. Relative paths are expanded relative to the current rule set file.\n /// \n /// The parent of this rule set include\n private string? GetIncludePath(RuleSet parent)\n {\n var resolvedIncludePath = resolveIncludePath(_includePath, parent?.FilePath);\n if (resolvedIncludePath == null)\n {\n return null;\n }\n\n // Return the canonical full path\n return Path.GetFullPath(resolvedIncludePath);\n\n static string? resolveIncludePath(string includePath, string? parentRulesetPath)\n {\n var resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath);\n if (resolvedIncludePath == null && PathUtilities.IsUnixLikePlatform)\n {\n // Attempt to resolve legacy ruleset includes after replacing Windows style directory separator char with current plaform's directory separator char.\n includePath = includePath.Replace('\\\\', Path.DirectorySeparatorChar);\n resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath);\n }\n\n return resolvedIncludePath;\n }\n\n static string? resolveIncludePathCore(string includePath, string? parentRulesetPath)\n {\n includePath = Environment.ExpandEnvironmentVariables(includePath);\n\n // If a full path is specified then use it\n if (Path.IsPathRooted(includePath))\n {\n if (File.Exists(includePath))\n {\n return includePath;\n }\n }\n else if (!string.IsNullOrEmpty(parentRulesetPath))\n {\n // Otherwise, try to find the include file relative to the parent ruleset.\n includePath = PathUtilities.CombinePathsUnchecked(Path.GetDirectoryName(parentRulesetPath) ?? \"\", includePath);\n if (File.Exists(includePath))\n {\n return includePath;\n }\n }\n\n return null;\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1134,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnostic.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;\n\nnamespace Microsoft.CodeAnalysis\n{\n public class WorkspaceDiagnostic\n {\n public WorkspaceDiagnosticKind Kind { get; }\n public string Message { get; }\n\n public WorkspaceDiagnostic(WorkspaceDiagnosticKind kind, string message)\n {\n this.Kind = kind;\n this.Message = message;\n }\n\n public override string ToString()\n {\n string kindText;\n\n switch (Kind)\n {\n case WorkspaceDiagnosticKind.Failure: kindText = WorkspacesResources.Failure; break;\n case WorkspaceDiagnosticKind.Warning: kindText = WorkspacesResources.Warning; break;\n default: throw ExceptionUtilities.UnexpectedValue(Kind);\n }\n\n return $\"[{kindText}] {Message}\";\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;\n\nnamespace Microsoft.CodeAnalysis\n{\n public class WorkspaceDiagnostic\n {\n public WorkspaceDiagnosticKind Kind { get; }\n public string Message { get; }\n\n public WorkspaceDiagnostic(WorkspaceDiagnosticKind kind, string message)\n {\n this.Kind = kind;\n this.Message = message;\n }\n\n public override string ToString()\n {\n string kindText;\n\n switch (Kind)\n {\n case WorkspaceDiagnosticKind.Failure: kindText = WorkspacesResources.Failure; break;\n case WorkspaceDiagnosticKind.Warning: kindText = WorkspacesResources.Warning; break;\n default: throw ExceptionUtilities.UnexpectedValue(Kind);\n }\n\n return $\"[{kindText}] {Message}\";\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1135,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/EditorFeatures/VisualBasicTest/BasicServicesTest.Debug.xunit"},"before_content":{"kind":"string","value":"\n \n \n \n "},"after_content":{"kind":"string","value":"\n \n \n \n "},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1136,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentNavigationServiceWrapper.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.Threading;\nusing Microsoft.CodeAnalysis.Navigation;\nusing Microsoft.CodeAnalysis.Options;\n\nnamespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api\n{\n internal readonly struct VSTypeScriptDocumentNavigationServiceWrapper\n {\n private readonly IDocumentNavigationService _underlyingObject;\n\n public VSTypeScriptDocumentNavigationServiceWrapper(IDocumentNavigationService underlyingObject)\n => _underlyingObject = underlyingObject;\n\n public static VSTypeScriptDocumentNavigationServiceWrapper Create(Workspace workspace)\n => new(workspace.Services.GetRequiredService());\n\n [Obsolete(\"Call overload that takes a CancellationToken\", error: false)]\n public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet? options = null)\n => this.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None);\n\n /// \n public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken)\n => _underlyingObject.TryNavigateToPosition(workspace, documentId, position, virtualSpace, 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.Threading;\nusing Microsoft.CodeAnalysis.Navigation;\nusing Microsoft.CodeAnalysis.Options;\n\nnamespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api\n{\n internal readonly struct VSTypeScriptDocumentNavigationServiceWrapper\n {\n private readonly IDocumentNavigationService _underlyingObject;\n\n public VSTypeScriptDocumentNavigationServiceWrapper(IDocumentNavigationService underlyingObject)\n => _underlyingObject = underlyingObject;\n\n public static VSTypeScriptDocumentNavigationServiceWrapper Create(Workspace workspace)\n => new(workspace.Services.GetRequiredService());\n\n [Obsolete(\"Call overload that takes a CancellationToken\", error: false)]\n public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet? options = null)\n => this.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None);\n\n /// \n public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken)\n => _underlyingObject.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1137,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Test/Perf/tests/csharp/csharp_compiler.csx"},"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#r \"../../Perf.Utilities/Roslyn.Test.Performance.Utilities.dll\"\n\nusing System.IO;\nusing System.Collections.Generic;\nusing Roslyn.Test.Performance.Utilities;\nusing static Roslyn.Test.Performance.Utilities.TestUtilities;\n\nclass CSharpCompilerTest: PerfTest\n{\n private string _rspFile;\n private ILogger _logger;\n\n public CSharpCompilerTest(string rspFile): base() {\n _rspFile = rspFile;\n _logger = new ConsoleAndFileLogger();\n }\n \n public override void Setup() \n {\n DownloadProject(\"csharp\", version: 1, logger: _logger);\n }\n \n public override void Test() \n {\n string responseFile = \"@\" + Path.Combine(TempDirectory, \"csharp\", _rspFile);\n string keyfileLocation = Path.Combine(TempDirectory, \"csharp\", \"keyfile\", \"35MSSharedLib1024.snk\");\n string args = $\"{responseFile} /keyfile:{keyfileLocation}\";\n\n string workingDirectory = Path.Combine(TempDirectory, \"csharp\");\n\n ShellOutVital(Path.Combine(MyBinaries(), \"Exes\", \"csc\", \"net46\", \"csc.exe\"), args, workingDirectory);\n _logger.Flush();\n }\n \n public override int Iterations => 3;\n public override string Name => \"csharp \" + _rspFile;\n public override string MeasuredProc => \"csc\";\n public override bool ProvidesScenarios => false;\n public override string[] GetScenarios()\n {\n throw new System.NotImplementedException();\n }\n}\n\nTestThisPlease( \n new CSharpCompilerTest(\"CSharpCompiler.rsp\"),\n new CSharpCompilerTest(\"CSharpCompilerNoAnalyzer.rsp\"),\n new CSharpCompilerTest(\"CSharpCompilerNoAnalyzerNoDeterminism.rsp\")\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#r \"../../Perf.Utilities/Roslyn.Test.Performance.Utilities.dll\"\n\nusing System.IO;\nusing System.Collections.Generic;\nusing Roslyn.Test.Performance.Utilities;\nusing static Roslyn.Test.Performance.Utilities.TestUtilities;\n\nclass CSharpCompilerTest: PerfTest\n{\n private string _rspFile;\n private ILogger _logger;\n\n public CSharpCompilerTest(string rspFile): base() {\n _rspFile = rspFile;\n _logger = new ConsoleAndFileLogger();\n }\n \n public override void Setup() \n {\n DownloadProject(\"csharp\", version: 1, logger: _logger);\n }\n \n public override void Test() \n {\n string responseFile = \"@\" + Path.Combine(TempDirectory, \"csharp\", _rspFile);\n string keyfileLocation = Path.Combine(TempDirectory, \"csharp\", \"keyfile\", \"35MSSharedLib1024.snk\");\n string args = $\"{responseFile} /keyfile:{keyfileLocation}\";\n\n string workingDirectory = Path.Combine(TempDirectory, \"csharp\");\n\n ShellOutVital(Path.Combine(MyBinaries(), \"Exes\", \"csc\", \"net46\", \"csc.exe\"), args, workingDirectory);\n _logger.Flush();\n }\n \n public override int Iterations => 3;\n public override string Name => \"csharp \" + _rspFile;\n public override string MeasuredProc => \"csc\";\n public override bool ProvidesScenarios => false;\n public override string[] GetScenarios()\n {\n throw new System.NotImplementedException();\n }\n}\n\nTestThisPlease( \n new CSharpCompilerTest(\"CSharpCompiler.rsp\"),\n new CSharpCompilerTest(\"CSharpCompilerNoAnalyzer.rsp\"),\n new CSharpCompilerTest(\"CSharpCompilerNoAnalyzerNoDeterminism.rsp\")\n);\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1138,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/EditorFeatures/Core/Extensibility/Composition/IContentTypeMetadata.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;\n\nnamespace Microsoft.CodeAnalysis.Editor\n{\n internal interface IContentTypeMetadata\n {\n IEnumerable ContentTypes { 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\n#nullable disable\n\nusing System.Collections.Generic;\n\nnamespace Microsoft.CodeAnalysis.Editor\n{\n internal interface IContentTypeMetadata\n {\n IEnumerable ContentTypes { get; }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1139,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/WithBlockHighlighterTests.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 Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting\n\nNamespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting\n Public Class WithBlockHighlighterTests\n Inherits AbstractVisualBasicKeywordHighlighterTests\n\n Friend Overrides Function GetHighlighterType() As Type\n Return GetType(WithBlockHighlighter)\n End Function\n\n \n Public Async Function TestWithBlock1() As Task\n Await TestAsync(\nClass C\nSub M()\n{|Cursor:[|With|]|} y\n.x = 10\nConsole.WriteLine(.x)\n[|End With|]\nEnd Sub\nEnd Class )\n End Function\n\n \n Public Async Function TestWithBlock2() As Task\n Await TestAsync(\nClass C\nSub M()\n[|With|] y\n.x = 10\nConsole.WriteLine(.x)\n{|Cursor:[|End With|]|}\nEnd Sub\nEnd Class )\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 Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting\n\nNamespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting\n Public Class WithBlockHighlighterTests\n Inherits AbstractVisualBasicKeywordHighlighterTests\n\n Friend Overrides Function GetHighlighterType() As Type\n Return GetType(WithBlockHighlighter)\n End Function\n\n \n Public Async Function TestWithBlock1() As Task\n Await TestAsync(\nClass C\nSub M()\n{|Cursor:[|With|]|} y\n.x = 10\nConsole.WriteLine(.x)\n[|End With|]\nEnd Sub\nEnd Class )\n End Function\n\n \n Public Async Function TestWithBlock2() As Task\n Await TestAsync(\nClass C\nSub M()\n[|With|] y\n.x = 10\nConsole.WriteLine(.x)\n{|Cursor:[|End With|]|}\nEnd Sub\nEnd Class )\n End Function\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1140,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Compilers/VisualBasic/Portable/BoundTree/BoundParameter.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 Microsoft.CodeAnalysis.VisualBasic.Symbols\n\nNamespace Microsoft.CodeAnalysis.VisualBasic\n\n Partial Friend Class BoundParameter\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)\n Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors)\n End Sub\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol)\n Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type)\n End Sub\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol, hasErrors As Boolean)\n Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors)\n End Sub\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol)\n Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type)\n End Sub\n\n Public Overrides ReadOnly Property ExpressionSymbol As Symbol\n Get\n Return Me.ParameterSymbol\n End Get\n End Property\n\n Protected Overrides Function MakeRValueImpl() As BoundExpression\n Return MakeRValue()\n End Function\n\n Public Shadows Function MakeRValue() As BoundParameter\n If _IsLValue Then\n Return Me.Update(_ParameterSymbol, False, SuppressVirtualCalls, Type)\n End If\n\n Return Me\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 Microsoft.CodeAnalysis.VisualBasic.Symbols\n\nNamespace Microsoft.CodeAnalysis.VisualBasic\n\n Partial Friend Class BoundParameter\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)\n Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors)\n End Sub\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol)\n Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type)\n End Sub\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol, hasErrors As Boolean)\n Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors)\n End Sub\n\n Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol)\n Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type)\n End Sub\n\n Public Overrides ReadOnly Property ExpressionSymbol As Symbol\n Get\n Return Me.ParameterSymbol\n End Get\n End Property\n\n Protected Overrides Function MakeRValueImpl() As BoundExpression\n Return MakeRValue()\n End Function\n\n Public Shadows Function MakeRValue() As BoundParameter\n If _IsLValue Then\n Return Me.Update(_ParameterSymbol, False, SuppressVirtualCalls, Type)\n End If\n\n Return Me\n End Function\n End Class\nEnd Namespace\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1141,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56385,"string":"56,385"},"pr_title":{"kind":"string","value":"Add completion tests for parameters in top-level statements"},"pr_description":{"kind":"string","value":"See #55969"},"author":{"kind":"string","value":"sharwell"},"date_created":{"kind":"timestamp","value":"2021-09-14T19:31:23Z","string":"2021-09-14T19:31:23Z"},"date_merged":{"kind":"timestamp","value":"2021-09-28T21:14:32Z","string":"2021-09-28T21:14:32Z"},"previous_commit":{"kind":"string","value":"ca9dba5fe617002a3abc0433a456dda80f4deec6"},"pr_commit":{"kind":"string","value":"567c588b35e3f98f3e7aec09759981505971cf9b"},"query":{"kind":"string","value":"Add completion tests for parameters in top-level statements. See #55969"},"filepath":{"kind":"string","value":"./src/Dependencies/Collections/ImmutableSegmentedDictionary`2+KeyCollection.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;\n\nnamespace Microsoft.CodeAnalysis.Collections\n{\n internal readonly partial struct ImmutableSegmentedDictionary\n {\n public readonly partial struct KeyCollection : IReadOnlyCollection, ICollection, ICollection\n {\n private readonly ImmutableSegmentedDictionary _dictionary;\n\n internal KeyCollection(ImmutableSegmentedDictionary dictionary)\n {\n _dictionary = dictionary;\n }\n\n public int Count => _dictionary.Count;\n\n bool ICollection.IsReadOnly => true;\n\n bool ICollection.IsSynchronized => true;\n\n object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;\n\n public Enumerator GetEnumerator()\n => new(_dictionary.GetEnumerator());\n\n public bool Contains(TKey item)\n => _dictionary.ContainsKey(item);\n\n IEnumerator IEnumerable.GetEnumerator()\n => GetEnumerator();\n\n IEnumerator IEnumerable.GetEnumerator()\n => GetEnumerator();\n\n void ICollection.CopyTo(TKey[] array, int arrayIndex)\n => ((ICollection)_dictionary._dictionary.Keys).CopyTo(array, arrayIndex);\n\n void ICollection.CopyTo(Array array, int index)\n => ((ICollection)_dictionary._dictionary.Keys).CopyTo(array, index);\n\n void ICollection.Add(TKey item)\n => throw new NotSupportedException();\n\n void ICollection.Clear()\n => throw new NotSupportedException();\n\n bool ICollection.Remove(TKey item)\n => throw new NotSupportedException();\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;\nusing System.Collections.Generic;\n\nnamespace Microsoft.CodeAnalysis.Collections\n{\n internal readonly partial struct ImmutableSegmentedDictionary\n {\n public readonly partial struct KeyCollection : IReadOnlyCollection, ICollection, ICollection\n {\n private readonly ImmutableSegmentedDictionary _dictionary;\n\n internal KeyCollection(ImmutableSegmentedDictionary dictionary)\n {\n _dictionary = dictionary;\n }\n\n public int Count => _dictionary.Count;\n\n bool ICollection.IsReadOnly => true;\n\n bool ICollection.IsSynchronized => true;\n\n object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;\n\n public Enumerator GetEnumerator()\n => new(_dictionary.GetEnumerator());\n\n public bool Contains(TKey item)\n => _dictionary.ContainsKey(item);\n\n IEnumerator IEnumerable.GetEnumerator()\n => GetEnumerator();\n\n IEnumerator IEnumerable.GetEnumerator()\n => GetEnumerator();\n\n void ICollection.CopyTo(TKey[] array, int arrayIndex)\n => ((ICollection)_dictionary._dictionary.Keys).CopyTo(array, arrayIndex);\n\n void ICollection.CopyTo(Array array, int index)\n => ((ICollection)_dictionary._dictionary.Keys).CopyTo(array, index);\n\n void ICollection.Add(TKey item)\n => throw new NotSupportedException();\n\n void ICollection.Clear()\n => throw new NotSupportedException();\n\n bool ICollection.Remove(TKey item)\n => throw new NotSupportedException();\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1142,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Compilers/Core/CodeAnalysisTest/DefaultAnalyzerAssemblyLoaderTests.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.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Roslyn.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Microsoft.CodeAnalysis.UnitTests\n{\n [CollectionDefinition(Name)]\n public class AssemblyLoadTestFixtureCollection : ICollectionFixture\n {\n public const string Name = nameof(AssemblyLoadTestFixtureCollection);\n private AssemblyLoadTestFixtureCollection() { }\n }\n\n [Collection(AssemblyLoadTestFixtureCollection.Name)]\n public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase\n {\n private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel);\n private readonly ITestOutputHelper _output;\n private readonly AssemblyLoadTestFixture _testFixture;\n public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture)\n {\n _output = output;\n _testFixture = testFixture;\n }\n\n [Fact, WorkItem(32226, \"https://github.com/dotnet/roslyn/issues/32226\")]\n public void LoadWithDependency()\n {\n var analyzerDependencyFile = _testFixture.AnalyzerDependency;\n var analyzerMainFile = _testFixture.AnalyzerWithDependency;\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(analyzerDependencyFile.Path);\n\n var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader);\n analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader);\n analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n\n var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages();\n Assert.Equal(1, analyzers.Length);\n Assert.Equal(\"TestAnalyzer\", analyzers[0].ToString());\n\n Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length);\n\n Assert.NotNull(analyzerDependencyReference.GetAssembly());\n }\n\n [Fact]\n public void AddDependencyLocationThrowsOnNull()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(null));\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(\"a\"));\n }\n\n [Fact]\n public void ThrowsForMissingFile()\n {\n var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + \".dll\");\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.ThrowsAny(() => loader.LoadFromPath(path));\n }\n\n [Fact]\n public void BasicLoad()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n Assert.NotNull(alpha);\n }\n\n [Fact]\n public void AssemblyLoading()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n var a = alpha.CreateInstance(\"Alpha.A\")!;\n a.GetType().GetMethod(\"Write\")!.Invoke(a, new object[] { sb, \"Test A\" });\n\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n b.GetType().GetMethod(\"Write\")!.Invoke(b, new object[] { sb, \"Test B\" });\n\n var expected = @\"Delta: Gamma: Alpha: Test A\nDelta: Gamma: Beta: Test B\n\";\n\n var actual = sb.ToString();\n\n Assert.Equal(expected, actual);\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_AssemblyLocationNotAdded()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n Assert.Throws(() => loader.LoadFromPath(_testFixture.Beta.Path));\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_DependencyLocationNotAdded()\n {\n StringBuilder sb = new StringBuilder();\n var loader = new DefaultAnalyzerAssemblyLoader();\n // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect\n // calling Beta.B.Write to fail.\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n var writeMethod = b.GetType().GetMethod(\"Write\")!;\n var exception = Assert.Throws(\n () => writeMethod.Invoke(b, new object[] { sb, \"Test B\" }));\n Assert.IsAssignableFrom(exception.InnerException);\n\n var actual = sb.ToString();\n Assert.Equal(@\"\", actual);\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(2, alcs.Length);\n\n Assert.Equal(new[] {\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n }, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n\n Assert.Equal(new[] {\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path)\n }, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MultipleLoaders()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader1 = new DefaultAnalyzerAssemblyLoader();\n loader1.AddDependencyLocation(_testFixture.Gamma.Path);\n loader1.AddDependencyLocation(_testFixture.Delta1.Path);\n\n var loader2 = new DefaultAnalyzerAssemblyLoader();\n loader2.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader2.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1);\n Assert.Equal(1, alcs1.Length);\n\n Assert.Equal(new[] {\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n }, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n\n var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2);\n Assert.Equal(1, alcs2.Length);\n\n Assert.Equal(new[] {\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path)\n }, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MissingVersion()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n var eWrite = e.GetType().GetMethod(\"Write\")!;\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n var exception = Assert.Throws(() => eWrite.Invoke(e, new object[] { sb, \"Test E\" }));\n Assert.IsAssignableFrom(exception.InnerException);\n }\n else\n {\n eWrite.Invoke(e, new object[] { sb, \"Test E\" });\n Assert.Equal(\n@\"Delta: Gamma: Test G\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n\n if (ExecutionConditionUtil.IsCoreClr)\n {\n var ex = Assert.ThrowsAny(() => analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb }));\n Assert.True(ex is MissingMethodException or TargetInvocationException, $@\"Unexpected exception type: \"\"{ex.GetType()}\"\"\");\n }\n else\n {\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(\"42\", sb.ToString());\n }\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(ExecutionConditionUtil.IsCoreClr ? \"1\" : \"42\", sb.ToString());\n }\n\n [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))]\n public void AssemblyLoading_NativeDependency()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Class1\")!;\n var result = analyzer.GetType().GetMethod(\"GetFileAttributes\")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path });\n Assert.Equal(0, Marshal.GetLastWin32Error());\n Assert.Equal(FileAttributes.Archive, (FileAttributes)result!);\n }\n\n [Fact]\n public void AssemblyLoading_Delete()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n var tempDir = Temp.CreateDirectory();\n var deltaCopy = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(deltaCopy.Path);\n Assembly delta = loader.LoadFromPath(deltaCopy.Path);\n\n try\n {\n File.Delete(deltaCopy.Path);\n }\n catch (UnauthorizedAccessException)\n {\n return;\n }\n\n // The above call may or may not throw depending on the platform configuration.\n // If it doesn't throw, we might as well check that things are still functioning reasonably.\n\n var d = delta.CreateInstance(\"Delta.D\");\n d!.GetType().GetMethod(\"Write\")!.Invoke(d, new object[] { sb, \"Test D\" });\n\n var actual = sb.ToString();\n Assert.Equal(\n@\"Delta: Test D\n\",\n actual);\n }\n\n#if NETCOREAPP\n [Fact]\n public void VerifyCompilerAssemblySimpleNames()\n {\n var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly;\n var caReferences = caAssembly.GetReferencedAssemblies();\n var allReferenceSimpleNames = ArrayBuilder.GetInstance();\n allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in caReferences)\n {\n allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException());\n }\n\n var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly;\n allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException());\n var csReferences = csAssembly.GetReferencedAssemblies();\n foreach (var reference in csReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly;\n var vbReferences = vbAssembly.GetReferencedAssemblies();\n allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in vbReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames))\n {\n allReferenceSimpleNames.Sort();\n var allNames = string.Join(\",\\r\\n \", allReferenceSimpleNames.Select(name => $@\"\"\"{name}\"\"\"));\n _output.WriteLine(\" internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\");\n _output.WriteLine(\" ImmutableHashSet.Create(\");\n _output.WriteLine(\" StringComparer.OrdinalIgnoreCase,\");\n _output.WriteLine($\" {allNames});\");\n allReferenceSimpleNames.Free();\n Assert.True(false, $\"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it.\");\n }\n else\n {\n allReferenceSimpleNames.Free();\n }\n }\n#endif\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.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.PooledObjects;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Roslyn.Test.Utilities;\nusing Roslyn.Utilities;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Microsoft.CodeAnalysis.UnitTests\n{\n [CollectionDefinition(Name)]\n public class AssemblyLoadTestFixtureCollection : ICollectionFixture\n {\n public const string Name = nameof(AssemblyLoadTestFixtureCollection);\n private AssemblyLoadTestFixtureCollection() { }\n }\n\n [Collection(AssemblyLoadTestFixtureCollection.Name)]\n public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase\n {\n private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel);\n private readonly ITestOutputHelper _output;\n private readonly AssemblyLoadTestFixture _testFixture;\n public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture)\n {\n _output = output;\n _testFixture = testFixture;\n }\n\n [Fact, WorkItem(32226, \"https://github.com/dotnet/roslyn/issues/32226\")]\n public void LoadWithDependency()\n {\n var analyzerDependencyFile = _testFixture.AnalyzerDependency;\n var analyzerMainFile = _testFixture.AnalyzerWithDependency;\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(analyzerDependencyFile.Path);\n\n var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader);\n analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader);\n analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message);\n\n var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages();\n Assert.Equal(1, analyzers.Length);\n Assert.Equal(\"TestAnalyzer\", analyzers[0].ToString());\n\n Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length);\n\n Assert.NotNull(analyzerDependencyReference.GetAssembly());\n }\n\n [Fact]\n public void AddDependencyLocationThrowsOnNull()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(null));\n Assert.Throws(\"fullPath\", () => loader.AddDependencyLocation(\"a\"));\n }\n\n [Fact]\n public void ThrowsForMissingFile()\n {\n var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + \".dll\");\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n Assert.ThrowsAny(() => loader.LoadFromPath(path));\n }\n\n [Fact]\n public void BasicLoad()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n Assert.NotNull(alpha);\n }\n\n [Fact]\n public void AssemblyLoading()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Alpha.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n\n Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path);\n\n var a = alpha.CreateInstance(\"Alpha.A\")!;\n a.GetType().GetMethod(\"Write\")!.Invoke(a, new object[] { sb, \"Test A\" });\n\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n b.GetType().GetMethod(\"Write\")!.Invoke(b, new object[] { sb, \"Test B\" });\n\n var expected = @\"Delta: Gamma: Alpha: Test A\nDelta: Gamma: Beta: Test B\n\";\n\n var actual = sb.ToString();\n\n Assert.Equal(expected, actual);\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_AssemblyLocationNotAdded()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n Assert.Throws(() => loader.LoadFromPath(_testFixture.Beta.Path));\n }\n\n [ConditionalFact(typeof(CoreClrOnly))]\n public void AssemblyLoading_DependencyLocationNotAdded()\n {\n StringBuilder sb = new StringBuilder();\n var loader = new DefaultAnalyzerAssemblyLoader();\n // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect\n // calling Beta.B.Write to fail.\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Beta.Path);\n Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path);\n\n var b = beta.CreateInstance(\"Beta.B\")!;\n var writeMethod = b.GetType().GetMethod(\"Write\")!;\n var exception = Assert.Throws(\n () => writeMethod.Invoke(b, new object[] { sb, \"Test B\" }));\n Assert.IsAssignableFrom(exception.InnerException);\n\n var actual = sb.ToString();\n Assert.Equal(@\"\", actual);\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader);\n Assert.Equal(2, alcs.Length);\n\n Assert.Equal(new[] {\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n }, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n\n Assert.Equal(new[] {\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path)\n }, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MultipleLoaders()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader1 = new DefaultAnalyzerAssemblyLoader();\n loader1.AddDependencyLocation(_testFixture.Gamma.Path);\n loader1.AddDependencyLocation(_testFixture.Delta1.Path);\n\n var loader2 = new DefaultAnalyzerAssemblyLoader();\n loader2.AddDependencyLocation(_testFixture.Epsilon.Path);\n loader2.AddDependencyLocation(_testFixture.Delta2.Path);\n\n Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n e.GetType().GetMethod(\"Write\")!.Invoke(e, new object[] { sb, \"Test E\" });\n\n#if NETCOREAPP\n var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1);\n Assert.Equal(1, alcs1.Length);\n\n Assert.Equal(new[] {\n (\"Delta\", \"1.0.0.0\", _testFixture.Delta1.Path),\n (\"Gamma\", \"0.0.0.0\", _testFixture.Gamma.Path)\n }, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n\n var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2);\n Assert.Equal(1, alcs2.Length);\n\n Assert.Equal(new[] {\n (\"Delta\", \"2.0.0.0\", _testFixture.Delta2.Path),\n (\"Epsilon\", \"0.0.0.0\", _testFixture.Epsilon.Path)\n }, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order());\n#endif\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta.2: Epsilon: Test E\n\",\n actual);\n }\n else\n {\n Assert.Equal(\n@\"Delta: Gamma: Test G\nDelta: Epsilon: Test E\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_MultipleVersions_MissingVersion()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.Gamma.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(_testFixture.Epsilon.Path);\n\n Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path);\n var g = gamma.CreateInstance(\"Gamma.G\")!;\n g.GetType().GetMethod(\"Write\")!.Invoke(g, new object[] { sb, \"Test G\" });\n\n Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path);\n var e = epsilon.CreateInstance(\"Epsilon.E\")!;\n var eWrite = e.GetType().GetMethod(\"Write\")!;\n\n var actual = sb.ToString();\n if (ExecutionConditionUtil.IsCoreClr)\n {\n var exception = Assert.Throws(() => eWrite.Invoke(e, new object[] { sb, \"Test E\" }));\n Assert.IsAssignableFrom(exception.InnerException);\n }\n else\n {\n eWrite.Invoke(e, new object[] { sb, \"Test E\" });\n Assert.Equal(\n@\"Delta: Gamma: Test G\n\",\n actual);\n }\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n\n if (ExecutionConditionUtil.IsCoreClr)\n {\n var ex = Assert.ThrowsAny(() => analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb }));\n Assert.True(ex is MissingMethodException or TargetInvocationException, $@\"Unexpected exception type: \"\"{ex.GetType()}\"\"\");\n }\n else\n {\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(\"42\", sb.ToString());\n }\n }\n\n [Fact]\n public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n Assert.Equal(ExecutionConditionUtil.IsCoreClr ? \"1\" : \"42\", sb.ToString());\n }\n\n [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))]\n public void AssemblyLoading_NativeDependency()\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Class1\")!;\n var result = analyzer.GetType().GetMethod(\"GetFileAttributes\")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path });\n Assert.Equal(0, Marshal.GetLastWin32Error());\n Assert.Equal(FileAttributes.Archive, (FileAttributes)result!);\n }\n\n [Fact]\n public void AssemblyLoading_Delete()\n {\n StringBuilder sb = new StringBuilder();\n\n var loader = new DefaultAnalyzerAssemblyLoader();\n\n var tempDir = Temp.CreateDirectory();\n var deltaCopy = tempDir.CreateFile(\"Delta.dll\").CopyContentFrom(_testFixture.Delta1.Path);\n loader.AddDependencyLocation(deltaCopy.Path);\n Assembly delta = loader.LoadFromPath(deltaCopy.Path);\n\n try\n {\n File.Delete(deltaCopy.Path);\n }\n catch (UnauthorizedAccessException)\n {\n return;\n }\n\n // The above call may or may not throw depending on the platform configuration.\n // If it doesn't throw, we might as well check that things are still functioning reasonably.\n\n var d = delta.CreateInstance(\"Delta.D\");\n d!.GetType().GetMethod(\"Write\")!.Invoke(d, new object[] { sb, \"Test D\" });\n\n var actual = sb.ToString();\n Assert.Equal(\n@\"Delta: Test D\n\",\n actual);\n }\n\n#if NETCOREAPP\n [Fact]\n public void VerifyCompilerAssemblySimpleNames()\n {\n var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly;\n var caReferences = caAssembly.GetReferencedAssemblies();\n var allReferenceSimpleNames = ArrayBuilder.GetInstance();\n allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in caReferences)\n {\n allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException());\n }\n\n var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly;\n allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException());\n var csReferences = csAssembly.GetReferencedAssemblies();\n foreach (var reference in csReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly;\n var vbReferences = vbAssembly.GetReferencedAssemblies();\n allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException());\n foreach (var reference in vbReferences)\n {\n var name = reference.Name ?? throw new InvalidOperationException();\n if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n {\n allReferenceSimpleNames.Add(name);\n }\n }\n\n if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames))\n {\n allReferenceSimpleNames.Sort();\n var allNames = string.Join(\",\\r\\n \", allReferenceSimpleNames.Select(name => $@\"\"\"{name}\"\"\"));\n _output.WriteLine(\" internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\");\n _output.WriteLine(\" ImmutableHashSet.Create(\");\n _output.WriteLine(\" StringComparer.OrdinalIgnoreCase,\");\n _output.WriteLine($\" {allNames});\");\n allReferenceSimpleNames.Free();\n Assert.True(false, $\"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it.\");\n }\n else\n {\n allReferenceSimpleNames.Free();\n }\n }\n\n [Fact]\n public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesSystemCollectionsImmutable()\n {\n // Create a separate ALC as the compiler context, load the compiler assembly and a modified version of S.C.I into it,\n // then use that to load and run `AssemblyLoadingInNonDefaultContextHelper1` below. We expect the analyzer running in\n // its own `DirectoryLoadContext` would use the bogus S.C.I loaded in the compiler load context instead of the real one\n // in the default context.\n var compilerContext = new System.Runtime.Loader.AssemblyLoadContext(\"compilerContext\");\n _ = compilerContext.LoadFromAssemblyPath(_testFixture.UserSystemCollectionsImmutable.Path);\n _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location);\n\n var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location);\n var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!,\n ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!;\n\n StringBuilder sb = new StringBuilder();\n testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper1), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb });\n Assert.Equal(\"42\", sb.ToString());\n }\n\n // This helper does the same thing as in `AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01` test above except the assertions.\n private void AssemblyLoadingInNonDefaultContextHelper1(StringBuilder sb)\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path);\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n }\n\n [Fact]\n public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesNonCompilerAssemblyUsedByDefaultContext()\n {\n // Load the V2 of Delta to default ALC, then create a separate ALC for compiler and load compiler assembly.\n // Next use compiler context to load and run `AssemblyLoadingInNonDefaultContextHelper2` below. We expect the analyzer running in\n // its own `DirectoryLoadContext` would load and use Delta V1 located in its directory instead of V2 already loaded in the default context.\n _ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(_testFixture.Delta2.Path);\n var compilerContext = new System.Runtime.Loader.AssemblyLoadContext(\"compilerContext\");\n _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location);\n\n var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location);\n var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!,\n ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!;\n\n StringBuilder sb = new StringBuilder();\n testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper2), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb });\n Assert.Equal(\n@\"Delta: Hello\n\",\n sb.ToString());\n }\n\n private void AssemblyLoadingInNonDefaultContextHelper2(StringBuilder sb)\n {\n var loader = new DefaultAnalyzerAssemblyLoader();\n loader.AddDependencyLocation(_testFixture.AnalyzerReferencesDelta1.Path);\n loader.AddDependencyLocation(_testFixture.Delta1.Path);\n\n Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesDelta1.Path);\n var analyzer = analyzerAssembly.CreateInstance(\"Analyzer\")!;\n analyzer.GetType().GetMethod(\"Method\")!.Invoke(analyzer, new object[] { sb });\n }\n#endif\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":1143,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Core.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\n#if NETCOREAPP\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.Loader;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n /// \n /// Typically a user analyzer has a reference to the compiler and some of the compiler's\n /// dependencies such as System.Collections.Immutable. For the analyzer to correctly\n /// interoperate with the compiler that created it, we need to ensure that we always use the\n /// compiler's version of a given assembly over the analyzer's version.
\n ///\n /// If we neglect to do this, then in the case where the user ships the compiler or its\n /// dependencies in the analyzer's bin directory, we could end up loading a separate\n /// instance of those assemblies in the process of loading the analyzer, which will surface\n /// as a failure to load the analyzer.
\n /// \n internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\n ImmutableHashSet.Create(\n StringComparer.OrdinalIgnoreCase,\n \"Microsoft.CodeAnalysis\",\n \"Microsoft.CodeAnalysis.CSharp\",\n \"Microsoft.CodeAnalysis.VisualBasic\",\n \"System.Collections\",\n \"System.Collections.Concurrent\",\n \"System.Collections.Immutable\",\n \"System.Console\",\n \"System.Diagnostics.Debug\",\n \"System.Diagnostics.StackTrace\",\n \"System.Diagnostics.Tracing\",\n \"System.IO.Compression\",\n \"System.IO.FileSystem\",\n \"System.Linq\",\n \"System.Linq.Expressions\",\n \"System.Memory\",\n \"System.Reflection.Metadata\",\n \"System.Reflection.Primitives\",\n \"System.Resources.ResourceManager\",\n \"System.Runtime\",\n \"System.Runtime.CompilerServices.Unsafe\",\n \"System.Runtime.Extensions\",\n \"System.Runtime.InteropServices\",\n \"System.Runtime.Loader\",\n \"System.Runtime.Numerics\",\n \"System.Runtime.Serialization.Primitives\",\n \"System.Security.Cryptography.Algorithms\",\n \"System.Security.Cryptography.Primitives\",\n \"System.Text.Encoding.CodePages\",\n \"System.Text.Encoding.Extensions\",\n \"System.Text.RegularExpressions\",\n \"System.Threading\",\n \"System.Threading.Tasks\",\n \"System.Threading.Tasks.Parallel\",\n \"System.Threading.Thread\",\n \"System.Threading.ThreadPool\",\n \"System.Xml.ReaderWriter\",\n \"System.Xml.XDocument\",\n \"System.Xml.XPath.XDocument\");\n\n private readonly object _guard = new object();\n private readonly Dictionary _loadContextByDirectory = new Dictionary(StringComparer.Ordinal);\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n DirectoryLoadContext? loadContext;\n\n var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath));\n lock (_guard)\n {\n if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext))\n {\n loadContext = new DirectoryLoadContext(fullDirectoryPath, this);\n _loadContextByDirectory[fullDirectoryPath] = loadContext;\n }\n }\n\n var name = AssemblyName.GetAssemblyName(fullPath);\n return loadContext.LoadFromAssemblyName(name);\n }\n\n internal static class TestAccessor\n {\n public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader)\n {\n return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray();\n }\n }\n\n private sealed class DirectoryLoadContext : AssemblyLoadContext\n {\n internal string Directory { get; }\n private readonly DefaultAnalyzerAssemblyLoader _loader;\n\n public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader)\n {\n Directory = directory;\n _loader = loader;\n }\n\n protected override Assembly? Load(AssemblyName assemblyName)\n {\n var simpleName = assemblyName.Name!;\n if (CompilerAssemblySimpleNames.Contains(simpleName))\n {\n // Delegate to the compiler's load context to load the compiler or anything\n // referenced by the compiler\n return null;\n }\n\n var assemblyPath = Path.Combine(Directory, simpleName + \".dll\");\n if (!_loader.IsKnownDependencyLocation(assemblyPath))\n {\n // The analyzer didn't explicitly register this dependency. Most likely the\n // assembly we're trying to load here is netstandard or a similar framework\n // assembly. We assume that if that is not the case, then the parent ALC will\n // fail to load this.\n return null;\n }\n\n var pathToLoad = _loader.GetPathToLoad(assemblyPath);\n return LoadFromAssemblyPath(pathToLoad);\n }\n\n protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)\n {\n var assemblyPath = Path.Combine(Directory, unmanagedDllName + \".dll\");\n if (!_loader.IsKnownDependencyLocation(assemblyPath))\n {\n return IntPtr.Zero;\n }\n\n var pathToLoad = _loader.GetPathToLoad(assemblyPath);\n return LoadUnmanagedDllFromPath(pathToLoad);\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\n#if NETCOREAPP\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.Loader;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader\n {\n /// \n /// Typically a user analyzer has a reference to the compiler and some of the compiler's\n /// dependencies such as System.Collections.Immutable. For the analyzer to correctly\n /// interoperate with the compiler that created it, we need to ensure that we always use the\n /// compiler's version of a given assembly over the analyzer's version.
\n ///\n /// If we neglect to do this, then in the case where the user ships the compiler or its\n /// dependencies in the analyzer's bin directory, we could end up loading a separate\n /// instance of those assemblies in the process of loading the analyzer, which will surface\n /// as a failure to load the analyzer.
\n /// \n internal static readonly ImmutableHashSet CompilerAssemblySimpleNames =\n ImmutableHashSet.Create(\n StringComparer.OrdinalIgnoreCase,\n \"Microsoft.CodeAnalysis\",\n \"Microsoft.CodeAnalysis.CSharp\",\n \"Microsoft.CodeAnalysis.VisualBasic\",\n \"System.Collections\",\n \"System.Collections.Concurrent\",\n \"System.Collections.Immutable\",\n \"System.Console\",\n \"System.Diagnostics.Debug\",\n \"System.Diagnostics.StackTrace\",\n \"System.Diagnostics.Tracing\",\n \"System.IO.Compression\",\n \"System.IO.FileSystem\",\n \"System.Linq\",\n \"System.Linq.Expressions\",\n \"System.Memory\",\n \"System.Reflection.Metadata\",\n \"System.Reflection.Primitives\",\n \"System.Resources.ResourceManager\",\n \"System.Runtime\",\n \"System.Runtime.CompilerServices.Unsafe\",\n \"System.Runtime.Extensions\",\n \"System.Runtime.InteropServices\",\n \"System.Runtime.Loader\",\n \"System.Runtime.Numerics\",\n \"System.Runtime.Serialization.Primitives\",\n \"System.Security.Cryptography.Algorithms\",\n \"System.Security.Cryptography.Primitives\",\n \"System.Text.Encoding.CodePages\",\n \"System.Text.Encoding.Extensions\",\n \"System.Text.RegularExpressions\",\n \"System.Threading\",\n \"System.Threading.Tasks\",\n \"System.Threading.Tasks.Parallel\",\n \"System.Threading.Thread\",\n \"System.Threading.ThreadPool\",\n \"System.Xml.ReaderWriter\",\n \"System.Xml.XDocument\",\n \"System.Xml.XPath.XDocument\");\n\n // This is the context where compiler (and some of its dependencies) are being loaded into, which might be different from AssemblyLoadContext.Default.\n private static readonly AssemblyLoadContext s_compilerLoadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly)!;\n\n private readonly object _guard = new object();\n private readonly Dictionary _loadContextByDirectory = new Dictionary(StringComparer.Ordinal);\n\n protected override Assembly LoadFromPathImpl(string fullPath)\n {\n DirectoryLoadContext? loadContext;\n\n var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath));\n lock (_guard)\n {\n if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext))\n {\n loadContext = new DirectoryLoadContext(fullDirectoryPath, this, s_compilerLoadContext);\n _loadContextByDirectory[fullDirectoryPath] = loadContext;\n }\n }\n\n var name = AssemblyName.GetAssemblyName(fullPath);\n return loadContext.LoadFromAssemblyName(name);\n }\n\n internal static class TestAccessor\n {\n public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader)\n {\n return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray();\n }\n }\n\n private sealed class DirectoryLoadContext : AssemblyLoadContext\n {\n internal string Directory { get; }\n private readonly DefaultAnalyzerAssemblyLoader _loader;\n private readonly AssemblyLoadContext _compilerLoadContext;\n\n public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader, AssemblyLoadContext compilerLoadContext)\n {\n Directory = directory;\n _loader = loader;\n _compilerLoadContext = compilerLoadContext;\n }\n\n protected override Assembly? Load(AssemblyName assemblyName)\n {\n var simpleName = assemblyName.Name!;\n if (CompilerAssemblySimpleNames.Contains(simpleName))\n {\n // Delegate to the compiler's load context to load the compiler or anything\n // referenced by the compiler\n return _compilerLoadContext.LoadFromAssemblyName(assemblyName);\n }\n\n var assemblyPath = Path.Combine(Directory, simpleName + \".dll\");\n if (!_loader.IsKnownDependencyLocation(assemblyPath))\n {\n // The analyzer didn't explicitly register this dependency. Most likely the\n // assembly we're trying to load here is netstandard or a similar framework\n // assembly. In this case, we want to load it in compiler's ALC to avoid any \n // potential type mismatch issue. Otherwise, if this is truly an unknown assembly,\n // we assume both compiler and default ALC will fail to load it.\n return _compilerLoadContext.LoadFromAssemblyName(assemblyName);\n }\n\n var pathToLoad = _loader.GetPathToLoad(assemblyPath);\n return LoadFromAssemblyPath(pathToLoad);\n }\n\n protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)\n {\n var assemblyPath = Path.Combine(Directory, unmanagedDllName + \".dll\");\n if (!_loader.IsKnownDependencyLocation(assemblyPath))\n {\n return IntPtr.Zero;\n }\n\n var pathToLoad = _loader.GetPathToLoad(assemblyPath);\n return LoadUnmanagedDllFromPath(pathToLoad);\n }\n }\n }\n}\n\n#endif\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":1144,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Compilers/Test/Core/AssemblyLoadTestFixture.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 Basic.Reference.Assemblies;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Roslyn.Test.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Test.Utilities\n{\n public sealed class AssemblyLoadTestFixture : IDisposable\n {\n private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel);\n\n private readonly TempRoot _temp;\n private readonly TempDirectory _directory;\n\n public TempFile Delta1 { get; }\n public TempFile Gamma { get; }\n public TempFile Beta { get; }\n public TempFile Alpha { get; }\n\n public TempFile Delta2 { get; }\n public TempFile Epsilon { get; }\n\n public TempFile UserSystemCollectionsImmutable { get; }\n\n /// \n /// An analyzer which uses members in its referenced version of System.Collections.Immutable\n /// that are not present in the compiler's version of System.Collections.Immutable.\n /// \n public TempFile AnalyzerReferencesSystemCollectionsImmutable1 { get; }\n\n /// \n /// An analyzer which uses members in its referenced version of System.Collections.Immutable\n /// which have different behavior than the same members in compiler's version of System.Collections.Immutable.\n /// \n public TempFile AnalyzerReferencesSystemCollectionsImmutable2 { get; }\n\n public TempFile FaultyAnalyzer { get; }\n\n public TempFile AnalyzerWithDependency { get; }\n public TempFile AnalyzerDependency { get; }\n\n public TempFile AnalyzerWithNativeDependency { get; }\n\n public AssemblyLoadTestFixture()\n {\n _temp = new TempRoot();\n _directory = _temp.CreateDirectory();\n\n Delta1 = GenerateDll(\"Delta\", _directory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"1.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta: \"\" + s);\n }\n }\n}\n\");\n var delta1Reference = MetadataReference.CreateFromFile(Delta1.Path);\n Gamma = GenerateDll(\"Gamma\", _directory, @\"\nusing System.Text;\nusing Delta;\n\nnamespace Gamma\n{\n public class G\n {\n public void Write(StringBuilder sb, string s)\n {\n D d = new D();\n\n d.Write(sb, \"\"Gamma: \"\" + s);\n }\n }\n}\n\", delta1Reference);\n\n var gammaReference = MetadataReference.CreateFromFile(Gamma.Path);\n Beta = GenerateDll(\"Beta\", _directory, @\"\nusing System.Text;\nusing Gamma;\n\nnamespace Beta\n{\n public class B\n {\n public void Write(StringBuilder sb, string s)\n {\n G g = new G();\n\n g.Write(sb, \"\"Beta: \"\" + s);\n }\n }\n}\n\", gammaReference);\n\n Alpha = GenerateDll(\"Alpha\", _directory, @\"\nusing System.Text;\nusing Gamma;\n\nnamespace Alpha\n{\n public class A\n {\n public void Write(StringBuilder sb, string s)\n {\n G g = new G();\n g.Write(sb, \"\"Alpha: \"\" + s);\n }\n }\n}\n\", gammaReference);\n\n var v2Directory = _directory.CreateDirectory(\"Version2\");\n Delta2 = GenerateDll(\"Delta\", v2Directory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"2.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta.2: \"\" + s);\n }\n }\n}\n\");\n var delta2Reference = MetadataReference.CreateFromFile(Delta2.Path);\n Epsilon = GenerateDll(\"Epsilon\", v2Directory, @\"\nusing System.Text;\nusing Delta;\n\nnamespace Epsilon\n{\n public class E\n {\n public void Write(StringBuilder sb, string s)\n {\n D d = new D();\n\n d.Write(sb, \"\"Epsilon: \"\" + s);\n }\n }\n}\n\", delta2Reference);\n\n var sciUserDirectory = _directory.CreateDirectory(\"SCIUser\");\n var compilerReference = MetadataReference.CreateFromFile(typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly.Location);\n\n UserSystemCollectionsImmutable = GenerateDll(\"System.Collections.Immutable\", sciUserDirectory, @\"\nnamespace System.Collections.Immutable\n{\n public static class ImmutableArray\n {\n public static ImmutableArray Create(T t) => new();\n }\n\n public struct ImmutableArray\n {\n public int Length => 42;\n\n public static int MyMethod() => 42;\n }\n}\n\", compilerReference);\n\n var userSystemCollectionsImmutableReference = MetadataReference.CreateFromFile(UserSystemCollectionsImmutable.Path);\n AnalyzerReferencesSystemCollectionsImmutable1 = GenerateDll(\"AnalyzerUsesSystemCollectionsImmutable1\", sciUserDirectory, @\"\nusing System.Text;\nusing System.Collections.Immutable;\n\npublic class Analyzer\n{\n public void Method(StringBuilder sb)\n {\n sb.Append(ImmutableArray.MyMethod());\n }\n}\n\", userSystemCollectionsImmutableReference, compilerReference);\n\n AnalyzerReferencesSystemCollectionsImmutable2 = GenerateDll(\"AnalyzerUsesSystemCollectionsImmutable2\", sciUserDirectory, @\"\nusing System.Text;\nusing System.Collections.Immutable;\n\npublic class Analyzer\n{\n public void Method(StringBuilder sb)\n {\n sb.Append(ImmutableArray.Create(\"\"a\"\").Length);\n }\n}\n\", userSystemCollectionsImmutableReference, compilerReference);\n\n var faultyAnalyzerDirectory = _directory.CreateDirectory(\"FaultyAnalyzer\");\n FaultyAnalyzer = GenerateDll(\"FaultyAnalyzer\", faultyAnalyzerDirectory, @\"\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\n[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]\npublic abstract class TestAnalyzer : DiagnosticAnalyzer\n{\n}\n\", compilerReference);\n\n var realSciReference = MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location);\n var analyzerWithDependencyDirectory = _directory.CreateDirectory(\"AnalyzerWithDependency\");\n AnalyzerDependency = GenerateDll(\"AnalyzerDependency\", analyzerWithDependencyDirectory, @\"\nusing System;\nusing System.Collections.Immutable;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\npublic abstract class AbstractTestAnalyzer : DiagnosticAnalyzer\n{\n protected static string SomeString = nameof(SomeString);\n public override ImmutableArray SupportedDiagnostics { get { throw new NotImplementedException(); } }\n public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); }\n}\n\", realSciReference, compilerReference);\n\n AnalyzerWithDependency = GenerateDll(\"Analyzer\", analyzerWithDependencyDirectory, @\"\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\n[DiagnosticAnalyzer(LanguageNames.CSharp)]\npublic sealed class TestAnalyzer : AbstractTestAnalyzer\n{\n private static string SomeString2 = AbstractTestAnalyzer.SomeString;\n}\", realSciReference, compilerReference, MetadataReference.CreateFromFile(AnalyzerDependency.Path));\n\n AnalyzerWithNativeDependency = GenerateDll(\"AnalyzerWithNativeDependency\", _directory, @\"\nusing System;\nusing System.Runtime.InteropServices;\n\npublic class Class1\n{\n [DllImport(\"\"kernel32.dll\"\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern int GetFileAttributesW(string lpFileName);\n\n public int GetFileAttributes(string path)\n {\n return GetFileAttributesW(path);\n }\n}\n\n\");\n }\n\n private static TempFile GenerateDll(string assemblyName, TempDirectory directory, string csSource, params MetadataReference[] additionalReferences)\n {\n var analyzerDependencyCompilation = CSharpCompilation.Create(\n assemblyName: assemblyName,\n syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(csSource) },\n references: new MetadataReference[]\n {\n NetStandard20.mscorlib,\n NetStandard20.netstandard,\n NetStandard20.SystemRuntime\n }.Concat(additionalReferences),\n options: s_dllWithMaxWarningLevel);\n\n var tempFile = directory.CreateFile($\"{assemblyName}.dll\");\n tempFile.WriteAllBytes(analyzerDependencyCompilation.EmitToArray());\n return tempFile;\n }\n\n public void Dispose()\n {\n _temp.Dispose();\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.Linq;\nusing Basic.Reference.Assemblies;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\nusing Roslyn.Test.Utilities;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Test.Utilities\n{\n public sealed class AssemblyLoadTestFixture : IDisposable\n {\n private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel);\n\n private readonly TempRoot _temp;\n private readonly TempDirectory _directory;\n\n public TempFile Delta1 { get; }\n public TempFile Gamma { get; }\n public TempFile Beta { get; }\n public TempFile Alpha { get; }\n\n public TempFile Delta2 { get; }\n public TempFile Epsilon { get; }\n\n public TempFile UserSystemCollectionsImmutable { get; }\n\n /// \n /// An analyzer which uses members in its referenced version of System.Collections.Immutable\n /// that are not present in the compiler's version of System.Collections.Immutable.\n /// \n public TempFile AnalyzerReferencesSystemCollectionsImmutable1 { get; }\n\n /// \n /// An analyzer which uses members in its referenced version of System.Collections.Immutable\n /// which have different behavior than the same members in compiler's version of System.Collections.Immutable.\n /// \n public TempFile AnalyzerReferencesSystemCollectionsImmutable2 { get; }\n\n public TempFile AnalyzerReferencesDelta1 { get; }\n\n public TempFile FaultyAnalyzer { get; }\n\n public TempFile AnalyzerWithDependency { get; }\n public TempFile AnalyzerDependency { get; }\n\n public TempFile AnalyzerWithNativeDependency { get; }\n\n public AssemblyLoadTestFixture()\n {\n _temp = new TempRoot();\n _directory = _temp.CreateDirectory();\n\n Delta1 = GenerateDll(\"Delta\", _directory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"1.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta: \"\" + s);\n }\n }\n}\n\");\n var delta1Reference = MetadataReference.CreateFromFile(Delta1.Path);\n Gamma = GenerateDll(\"Gamma\", _directory, @\"\nusing System.Text;\nusing Delta;\n\nnamespace Gamma\n{\n public class G\n {\n public void Write(StringBuilder sb, string s)\n {\n D d = new D();\n\n d.Write(sb, \"\"Gamma: \"\" + s);\n }\n }\n}\n\", delta1Reference);\n\n var gammaReference = MetadataReference.CreateFromFile(Gamma.Path);\n Beta = GenerateDll(\"Beta\", _directory, @\"\nusing System.Text;\nusing Gamma;\n\nnamespace Beta\n{\n public class B\n {\n public void Write(StringBuilder sb, string s)\n {\n G g = new G();\n\n g.Write(sb, \"\"Beta: \"\" + s);\n }\n }\n}\n\", gammaReference);\n\n Alpha = GenerateDll(\"Alpha\", _directory, @\"\nusing System.Text;\nusing Gamma;\n\nnamespace Alpha\n{\n public class A\n {\n public void Write(StringBuilder sb, string s)\n {\n G g = new G();\n g.Write(sb, \"\"Alpha: \"\" + s);\n }\n }\n}\n\", gammaReference);\n\n var v2Directory = _directory.CreateDirectory(\"Version2\");\n Delta2 = GenerateDll(\"Delta\", v2Directory, @\"\nusing System.Text;\n\n[assembly: System.Reflection.AssemblyTitle(\"\"Delta\"\")]\n[assembly: System.Reflection.AssemblyVersion(\"\"2.0.0.0\"\")]\n\nnamespace Delta\n{\n public class D\n {\n public void Write(StringBuilder sb, string s)\n {\n sb.AppendLine(\"\"Delta.2: \"\" + s);\n }\n }\n}\n\");\n var delta2Reference = MetadataReference.CreateFromFile(Delta2.Path);\n Epsilon = GenerateDll(\"Epsilon\", v2Directory, @\"\nusing System.Text;\nusing Delta;\n\nnamespace Epsilon\n{\n public class E\n {\n public void Write(StringBuilder sb, string s)\n {\n D d = new D();\n\n d.Write(sb, \"\"Epsilon: \"\" + s);\n }\n }\n}\n\", delta2Reference);\n\n var sciUserDirectory = _directory.CreateDirectory(\"SCIUser\");\n var compilerReference = MetadataReference.CreateFromFile(typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly.Location);\n\n UserSystemCollectionsImmutable = GenerateDll(\"System.Collections.Immutable\", sciUserDirectory, @\"\nnamespace System.Collections.Immutable\n{\n public static class ImmutableArray\n {\n public static ImmutableArray Create(T t) => new();\n }\n\n public struct ImmutableArray\n {\n public int Length => 42;\n\n public static int MyMethod() => 42;\n }\n}\n\", compilerReference);\n\n var userSystemCollectionsImmutableReference = MetadataReference.CreateFromFile(UserSystemCollectionsImmutable.Path);\n AnalyzerReferencesSystemCollectionsImmutable1 = GenerateDll(\"AnalyzerUsesSystemCollectionsImmutable1\", sciUserDirectory, @\"\nusing System.Text;\nusing System.Collections.Immutable;\n\npublic class Analyzer\n{\n public void Method(StringBuilder sb)\n {\n sb.Append(ImmutableArray.MyMethod());\n }\n}\n\", userSystemCollectionsImmutableReference, compilerReference);\n\n AnalyzerReferencesSystemCollectionsImmutable2 = GenerateDll(\"AnalyzerUsesSystemCollectionsImmutable2\", sciUserDirectory, @\"\nusing System.Text;\nusing System.Collections.Immutable;\n\npublic class Analyzer\n{\n public void Method(StringBuilder sb)\n {\n sb.Append(ImmutableArray.Create(\"\"a\"\").Length);\n }\n}\n\", userSystemCollectionsImmutableReference, compilerReference);\n\n var analyzerReferencesDelta1Directory = _directory.CreateDirectory(\"AnalyzerReferencesDelta1\");\n var delta1InAnalyzerReferencesDelta1 = analyzerReferencesDelta1Directory.CopyFile(Delta1.Path);\n\n AnalyzerReferencesDelta1 = GenerateDll(\"AnalyzerReferencesDelta1\", _directory, @\"\nusing System.Text;\nusing Delta;\n\npublic class Analyzer\n{\n public void Method(StringBuilder sb)\n {\n var d = new D();\n d.Write(sb, \"\"Hello\"\");\n }\n}\n\", MetadataReference.CreateFromFile(delta1InAnalyzerReferencesDelta1.Path), compilerReference);\n\n var faultyAnalyzerDirectory = _directory.CreateDirectory(\"FaultyAnalyzer\");\n FaultyAnalyzer = GenerateDll(\"FaultyAnalyzer\", faultyAnalyzerDirectory, @\"\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\n[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]\npublic abstract class TestAnalyzer : DiagnosticAnalyzer\n{\n}\n\", compilerReference);\n\n var realSciReference = MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location);\n var analyzerWithDependencyDirectory = _directory.CreateDirectory(\"AnalyzerWithDependency\");\n AnalyzerDependency = GenerateDll(\"AnalyzerDependency\", analyzerWithDependencyDirectory, @\"\nusing System;\nusing System.Collections.Immutable;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\npublic abstract class AbstractTestAnalyzer : DiagnosticAnalyzer\n{\n protected static string SomeString = nameof(SomeString);\n public override ImmutableArray SupportedDiagnostics { get { throw new NotImplementedException(); } }\n public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); }\n}\n\", realSciReference, compilerReference);\n\n AnalyzerWithDependency = GenerateDll(\"Analyzer\", analyzerWithDependencyDirectory, @\"\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\n\n[DiagnosticAnalyzer(LanguageNames.CSharp)]\npublic sealed class TestAnalyzer : AbstractTestAnalyzer\n{\n private static string SomeString2 = AbstractTestAnalyzer.SomeString;\n}\", realSciReference, compilerReference, MetadataReference.CreateFromFile(AnalyzerDependency.Path));\n\n AnalyzerWithNativeDependency = GenerateDll(\"AnalyzerWithNativeDependency\", _directory, @\"\nusing System;\nusing System.Runtime.InteropServices;\n\npublic class Class1\n{\n [DllImport(\"\"kernel32.dll\"\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern int GetFileAttributesW(string lpFileName);\n\n public int GetFileAttributes(string path)\n {\n return GetFileAttributesW(path);\n }\n}\n\n\");\n }\n\n private static TempFile GenerateDll(string assemblyName, TempDirectory directory, string csSource, params MetadataReference[] additionalReferences)\n {\n var analyzerDependencyCompilation = CSharpCompilation.Create(\n assemblyName: assemblyName,\n syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(csSource) },\n references: new MetadataReference[]\n {\n NetStandard20.mscorlib,\n NetStandard20.netstandard,\n NetStandard20.SystemRuntime\n }.Concat(additionalReferences),\n options: s_dllWithMaxWarningLevel);\n\n var tempFile = directory.CreateFile($\"{assemblyName}.dll\");\n tempFile.WriteAllBytes(analyzerDependencyCompilation.EmitToArray());\n return tempFile;\n }\n\n public void Dispose()\n {\n _temp.Dispose();\n }\n }\n}\n"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":1145,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/VisualStudio/Setup/source.extension.vsixmanifest"},"before_content":{"kind":"string","value":"\n\n \n \n Roslyn Language Services \n C# and VB.NET language services for Visual Studio. \n Microsoft.CodeAnalysis.VisualStudio.Setup \n EULA.rtf \n true \n \n \n \n amd64 \n \n \n amd64 \n \n \n amd64 \n \n \n amd64 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \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 Roslyn Language Services \n C# and VB.NET language services for Visual Studio. \n Microsoft.CodeAnalysis.VisualStudio.Setup \n EULA.rtf \n true \n \n \n \n amd64 \n \n \n amd64 \n \n \n amd64 \n \n \n amd64 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \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":1146,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.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.Linq;\n\nnamespace Microsoft.CodeAnalysis.Shared.Utilities\n{\n internal static partial class ExtensionOrderer\n {\n internal static IList> Order(\n IEnumerable> extensions)\n where TMetadata : OrderableMetadata\n {\n var graph = GetGraph(extensions);\n return graph.TopologicalSort();\n }\n\n private static Graph GetGraph(\n IEnumerable> extensions)\n where TMetadata : OrderableMetadata\n {\n var list = extensions.ToList();\n var graph = new Graph();\n\n foreach (var extension in list)\n {\n graph.Nodes.Add(extension, new Node(extension));\n }\n\n foreach (var extension in list)\n {\n var extensionNode = graph.Nodes[extension];\n foreach (var before in extension.Metadata.BeforeTyped)\n {\n foreach (var beforeExtension in graph.FindExtensions(before))\n {\n var otherExtensionNode = graph.Nodes[beforeExtension];\n otherExtensionNode.ExtensionsBeforeMeSet.Add(extensionNode);\n }\n }\n\n foreach (var after in extension.Metadata.AfterTyped)\n {\n foreach (var afterExtension in graph.FindExtensions(after))\n {\n var otherExtensionNode = graph.Nodes[afterExtension];\n extensionNode.ExtensionsBeforeMeSet.Add(otherExtensionNode);\n }\n }\n }\n\n return graph;\n }\n\n internal static class TestAccessor\n {\n /// \n /// Helper for checking whether cycles exist in the extension ordering.\n /// Throws if a cycle is detected.\n /// \n /// A cycle was detected in the extension ordering. \n internal static void CheckForCycles(\n IEnumerable> extensions)\n where TMetadata : OrderableMetadata\n {\n var graph = GetGraph(extensions);\n graph.CheckForCycles();\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.Linq;\n\nnamespace Microsoft.CodeAnalysis.Shared.Utilities\n{\n internal static partial class ExtensionOrderer\n {\n internal static IList> Order(\n IEnumerable> extensions)\n where TMetadata : OrderableMetadata\n {\n var graph = GetGraph(extensions);\n return graph.TopologicalSort();\n }\n\n private static Graph GetGraph(\n IEnumerable> extensions)\n where TMetadata : OrderableMetadata\n {\n var list = extensions.ToList();\n var graph = new Graph();\n\n foreach (var extension in list)\n {\n graph.Nodes.Add(extension, new Node(extension));\n }\n\n foreach (var extension in list)\n {\n var extensionNode = graph.Nodes[extension];\n foreach (var before in extension.Metadata.BeforeTyped)\n {\n foreach (var beforeExtension in graph.FindExtensions(before))\n {\n var otherExtensionNode = graph.Nodes[beforeExtension];\n otherExtensionNode.ExtensionsBeforeMeSet.Add(extensionNode);\n }\n }\n\n foreach (var after in extension.Metadata.AfterTyped)\n {\n foreach (var afterExtension in graph.FindExtensions(after))\n {\n var otherExtensionNode = graph.Nodes[afterExtension];\n extensionNode.ExtensionsBeforeMeSet.Add(otherExtensionNode);\n }\n }\n }\n\n return graph;\n }\n\n internal static class TestAccessor\n {\n /// \n /// Helper for checking whether cycles exist in the extension ordering.\n /// Throws if a cycle is detected.\n /// \n /// A cycle was detected in the extension ordering. \n internal static void CheckForCycles(\n IEnumerable> extensions)\n where TMetadata : OrderableMetadata\n {\n var graph = GetGraph(extensions);\n graph.CheckForCycles();\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1147,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Features/Core/Portable/ValidateFormatString/ValidateFormatStringOptionProvider.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 Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Options;\nusing Microsoft.CodeAnalysis.Options.Providers;\n\nnamespace Microsoft.CodeAnalysis.ValidateFormatString\n{\n [ExportOptionProvider, Shared]\n internal class ValidateFormatStringOptionProvider : IOptionProvider\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public ValidateFormatStringOptionProvider()\n {\n }\n\n public ImmutableArray Options { get; } = ImmutableArray.Create(\n ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls);\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 Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Options;\nusing Microsoft.CodeAnalysis.Options.Providers;\n\nnamespace Microsoft.CodeAnalysis.ValidateFormatString\n{\n [ExportOptionProvider, Shared]\n internal class ValidateFormatStringOptionProvider : IOptionProvider\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public ValidateFormatStringOptionProvider()\n {\n }\n\n public ImmutableArray Options { get; } = ImmutableArray.Create(\n ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1148,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsHierarchyEvents.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;\nusing Microsoft.VisualStudio.Shell.Interop;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy\n{\n internal partial class AbstractLegacyProject : IVsHierarchyEvents\n {\n private uint _hierarchyEventsCookie;\n\n private void ConnectHierarchyEvents()\n {\n Debug.Assert(!this.AreHierarchyEventsConnected, \"IVsHierarchyEvents are already connected!\");\n\n if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie)))\n {\n Debug.Fail(\"Failed to connect IVsHierarchyEvents\");\n _hierarchyEventsCookie = 0;\n }\n }\n\n private void DisconnectHierarchyEvents()\n {\n if (this.AreHierarchyEventsConnected)\n {\n Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie);\n _hierarchyEventsCookie = 0;\n }\n }\n\n private bool AreHierarchyEventsConnected\n {\n get { return _hierarchyEventsCookie != 0; }\n }\n\n int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnItemDeleted(uint itemid)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnItemsAppended(uint itemidParent)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags)\n {\n if ((propid == (int)__VSHPROPID.VSHPROPID_Caption ||\n propid == (int)__VSHPROPID.VSHPROPID_Name) &&\n itemid == (uint)VSConstants.VSITEMID.Root)\n {\n var filePath = Hierarchy.TryGetProjectFilePath();\n\n if (filePath != null && File.Exists(filePath))\n {\n VisualStudioProject.FilePath = filePath;\n }\n\n if (Hierarchy.TryGetName(out var name))\n {\n VisualStudioProject.DisplayName = name;\n }\n }\n\n return VSConstants.S_OK;\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;\nusing Microsoft.VisualStudio.Shell.Interop;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy\n{\n internal partial class AbstractLegacyProject : IVsHierarchyEvents\n {\n private uint _hierarchyEventsCookie;\n\n private void ConnectHierarchyEvents()\n {\n Debug.Assert(!this.AreHierarchyEventsConnected, \"IVsHierarchyEvents are already connected!\");\n\n if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie)))\n {\n Debug.Fail(\"Failed to connect IVsHierarchyEvents\");\n _hierarchyEventsCookie = 0;\n }\n }\n\n private void DisconnectHierarchyEvents()\n {\n if (this.AreHierarchyEventsConnected)\n {\n Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie);\n _hierarchyEventsCookie = 0;\n }\n }\n\n private bool AreHierarchyEventsConnected\n {\n get { return _hierarchyEventsCookie != 0; }\n }\n\n int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnItemDeleted(uint itemid)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnItemsAppended(uint itemidParent)\n => VSConstants.E_NOTIMPL;\n\n int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags)\n {\n if ((propid == (int)__VSHPROPID.VSHPROPID_Caption ||\n propid == (int)__VSHPROPID.VSHPROPID_Name) &&\n itemid == (uint)VSConstants.VSITEMID.Root)\n {\n var filePath = Hierarchy.TryGetProjectFilePath();\n\n if (filePath != null && File.Exists(filePath))\n {\n VisualStudioProject.FilePath = filePath;\n }\n\n if (Hierarchy.TryGetName(out var name))\n {\n VisualStudioProject.DisplayName = name;\n }\n }\n\n return VSConstants.S_OK;\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1149,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Compilers/Test/Resources/Core/SymbolsTests/Methods/CSMethods.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 /t:library CSMethods.cs\n\npublic class C1\n{\n public class SameName\n { \n }\n\n public void sameName()\n { \n }\n\n public void SameName2()\n {\n }\n\n public void SameName2(int x)\n {\n }\n\n public void sameName2(double x)\n {\n }\n\n}\n\n\n\npublic abstract class Modifiers1\n{\n public abstract void M1();\n\n public virtual void M2()\n {}\n\n public void M3()\n {}\n\n public virtual void M4()\n {}\n}\n\npublic abstract class Modifiers2\n : Modifiers1\n{\n public sealed override void M1()\n {}\n\n public abstract override void M2();\n\n public virtual new void M3()\n { }\n}\n\npublic abstract class Modifiers3\n : Modifiers1\n{\n public override void M1()\n {}\n\n public new void M3()\n { }\n\n public abstract new void M4();\n\n}\n\npublic class DefaultParameterValues\n{\n public static void M(\n string text,\n string path = \"\",\n DefaultParameterValues d = null,\n System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { }\n}\n\npublic class MultiDimArrays\n{\n public static void Goo(int[,] x) { }\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 /t:library CSMethods.cs\n\npublic class C1\n{\n public class SameName\n { \n }\n\n public void sameName()\n { \n }\n\n public void SameName2()\n {\n }\n\n public void SameName2(int x)\n {\n }\n\n public void sameName2(double x)\n {\n }\n\n}\n\n\n\npublic abstract class Modifiers1\n{\n public abstract void M1();\n\n public virtual void M2()\n {}\n\n public void M3()\n {}\n\n public virtual void M4()\n {}\n}\n\npublic abstract class Modifiers2\n : Modifiers1\n{\n public sealed override void M1()\n {}\n\n public abstract override void M2();\n\n public virtual new void M3()\n { }\n}\n\npublic abstract class Modifiers3\n : Modifiers1\n{\n public override void M1()\n {}\n\n public new void M3()\n { }\n\n public abstract new void M4();\n\n}\n\npublic class DefaultParameterValues\n{\n public static void M(\n string text,\n string path = \"\",\n DefaultParameterValues d = null,\n System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { }\n}\n\npublic class MultiDimArrays\n{\n public static void Goo(int[,] x) { }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1150,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/ChangeSignatureDialog_OutOfProc.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.VisualStudio.IntegrationTest.Utilities.InProcess;\nusing Microsoft.VisualStudio.IntegrationTest.Utilities.Input;\n\nnamespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess\n{\n public class ChangeSignatureDialog_OutOfProc : OutOfProcComponent\n {\n private readonly ChangeSignatureDialog_InProc _inProc;\n\n public ChangeSignatureDialog_OutOfProc(VisualStudioInstance visualStudioInstance)\n : base(visualStudioInstance)\n {\n _inProc = CreateInProcComponent(visualStudioInstance);\n }\n\n public void VerifyOpen()\n => _inProc.VerifyOpen();\n\n public void VerifyClosed()\n => _inProc.VerifyClosed();\n\n public bool CloseWindow()\n => _inProc.CloseWindow();\n\n public void Invoke()\n => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.V, ShiftState.Ctrl));\n\n public void ClickOK()\n => _inProc.ClickOK();\n\n public void ClickCancel()\n => _inProc.ClickCancel();\n\n public void ClickDownButton()\n => _inProc.ClickDownButton();\n\n public void ClickUpButton()\n => _inProc.ClickUpButton();\n\n public void ClickAddButton()\n => _inProc.ClickAddButton();\n\n public void ClickRemoveButton()\n => _inProc.ClickRemoveButton();\n\n public void ClickRestoreButton()\n => _inProc.ClickRestoreButton();\n\n public void SelectParameter(string parameterName)\n => _inProc.SelectParameter(parameterName);\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.VisualStudio.IntegrationTest.Utilities.InProcess;\nusing Microsoft.VisualStudio.IntegrationTest.Utilities.Input;\n\nnamespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess\n{\n public class ChangeSignatureDialog_OutOfProc : OutOfProcComponent\n {\n private readonly ChangeSignatureDialog_InProc _inProc;\n\n public ChangeSignatureDialog_OutOfProc(VisualStudioInstance visualStudioInstance)\n : base(visualStudioInstance)\n {\n _inProc = CreateInProcComponent(visualStudioInstance);\n }\n\n public void VerifyOpen()\n => _inProc.VerifyOpen();\n\n public void VerifyClosed()\n => _inProc.VerifyClosed();\n\n public bool CloseWindow()\n => _inProc.CloseWindow();\n\n public void Invoke()\n => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.V, ShiftState.Ctrl));\n\n public void ClickOK()\n => _inProc.ClickOK();\n\n public void ClickCancel()\n => _inProc.ClickCancel();\n\n public void ClickDownButton()\n => _inProc.ClickDownButton();\n\n public void ClickUpButton()\n => _inProc.ClickUpButton();\n\n public void ClickAddButton()\n => _inProc.ClickAddButton();\n\n public void ClickRemoveButton()\n => _inProc.ClickRemoveButton();\n\n public void ClickRestoreButton()\n => _inProc.ClickRestoreButton();\n\n public void SelectParameter(string parameterName)\n => _inProc.SelectParameter(parameterName);\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1151,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Analyzers/Core/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.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.Diagnostics.CodeAnalysis;\nusing System.Linq;\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;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.UseThrowExpression\n{\n [ExportCodeFixProvider(LanguageNames.CSharp,\n Name = PredefinedCodeFixProviderNames.UseThrowExpression), Shared]\n internal partial class UseThrowExpressionCodeFixProvider : 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 UseThrowExpressionCodeFixProvider()\n {\n }\n\n public override ImmutableArray FixableDiagnosticIds\n => ImmutableArray.Create(IDEDiagnosticIds.UseThrowExpressionDiagnosticId);\n\n internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;\n\n protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)\n => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);\n\n public override Task RegisterCodeFixesAsync(CodeFixContext context)\n {\n var diagnostic = context.Diagnostics.First();\n context.RegisterCodeFix(\n new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)),\n diagnostic);\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 generator = editor.Generator;\n var root = editor.OriginalRoot;\n\n foreach (var diagnostic in diagnostics)\n {\n var ifStatement = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan);\n var throwStatementExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);\n var assignmentValue = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);\n\n // First, remote the if-statement entirely.\n editor.RemoveNode(ifStatement);\n\n // Now, update the assignment value to go from 'a' to 'a ?? throw ...'.\n editor.ReplaceNode(assignmentValue,\n generator.CoalesceExpression(assignmentValue,\n generator.ThrowExpression(throwStatementExpression)));\n }\n\n return Task.CompletedTask;\n }\n\n private class MyCodeAction : CustomCodeActions.DocumentChangeAction\n {\n public MyCodeAction(\n Func> createChangedDocument)\n : base(AnalyzersResources.Use_throw_expression, createChangedDocument, nameof(AnalyzersResources.Use_throw_expression))\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.Immutable;\nusing System.Composition;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\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;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.UseThrowExpression\n{\n [ExportCodeFixProvider(LanguageNames.CSharp,\n Name = PredefinedCodeFixProviderNames.UseThrowExpression), Shared]\n internal partial class UseThrowExpressionCodeFixProvider : 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 UseThrowExpressionCodeFixProvider()\n {\n }\n\n public override ImmutableArray FixableDiagnosticIds\n => ImmutableArray.Create(IDEDiagnosticIds.UseThrowExpressionDiagnosticId);\n\n internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;\n\n protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)\n => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);\n\n public override Task RegisterCodeFixesAsync(CodeFixContext context)\n {\n var diagnostic = context.Diagnostics.First();\n context.RegisterCodeFix(\n new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)),\n diagnostic);\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 generator = editor.Generator;\n var root = editor.OriginalRoot;\n\n foreach (var diagnostic in diagnostics)\n {\n var ifStatement = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan);\n var throwStatementExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);\n var assignmentValue = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);\n\n // First, remote the if-statement entirely.\n editor.RemoveNode(ifStatement);\n\n // Now, update the assignment value to go from 'a' to 'a ?? throw ...'.\n editor.ReplaceNode(assignmentValue,\n generator.CoalesceExpression(assignmentValue,\n generator.ThrowExpression(throwStatementExpression)));\n }\n\n return Task.CompletedTask;\n }\n\n private class MyCodeAction : CustomCodeActions.DocumentChangeAction\n {\n public MyCodeAction(\n Func> createChangedDocument)\n : base(AnalyzersResources.Use_throw_expression, createChangedDocument, nameof(AnalyzersResources.Use_throw_expression))\n {\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1152,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService.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;\nusing Microsoft.CodeAnalysis.CodeActions;\nusing Microsoft.CodeAnalysis.CodeActions.WorkspaceServices;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.VisualStudio;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;\nusing Microsoft.VisualStudio.OLE.Interop;\nusing Microsoft.VisualStudio.Shell.Interop;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation\n{\n [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared]\n internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService()\n {\n }\n\n public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity)\n {\n if (projectId == null)\n {\n throw new ArgumentNullException(nameof(projectId));\n }\n\n if (assemblyIdentity == null)\n {\n throw new ArgumentNullException(nameof(assemblyIdentity));\n }\n\n return new AddMetadataReferenceOperation(projectId, assemblyIdentity);\n }\n\n private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation\n {\n private readonly AssemblyIdentity _assemblyIdentity;\n private readonly ProjectId _projectId;\n\n public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity)\n {\n _projectId = projectId;\n _assemblyIdentity = assemblyIdentity;\n }\n\n public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default)\n {\n var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace;\n if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, \"*\" + _assemblyIdentity.GetDisplayName()))\n {\n // We failed to add the reference, which means the project system wasn't able to bind.\n // We'll pop up the Add Reference dialog to let the user figure this out themselves.\n // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix\n\n if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy)\n {\n var command = new OLECMD[1];\n command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE;\n\n if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero)))\n {\n if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0)\n {\n uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero);\n }\n }\n }\n }\n }\n\n public override string Title\n => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName());\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;\nusing Microsoft.CodeAnalysis.CodeActions;\nusing Microsoft.CodeAnalysis.CodeActions.WorkspaceServices;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.VisualStudio;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;\nusing Microsoft.VisualStudio.OLE.Interop;\nusing Microsoft.VisualStudio.Shell.Interop;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation\n{\n [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared]\n internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService\n {\n [ImportingConstructor]\n [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]\n public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService()\n {\n }\n\n public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity)\n {\n if (projectId == null)\n {\n throw new ArgumentNullException(nameof(projectId));\n }\n\n if (assemblyIdentity == null)\n {\n throw new ArgumentNullException(nameof(assemblyIdentity));\n }\n\n return new AddMetadataReferenceOperation(projectId, assemblyIdentity);\n }\n\n private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation\n {\n private readonly AssemblyIdentity _assemblyIdentity;\n private readonly ProjectId _projectId;\n\n public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity)\n {\n _projectId = projectId;\n _assemblyIdentity = assemblyIdentity;\n }\n\n public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default)\n {\n var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace;\n if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, \"*\" + _assemblyIdentity.GetDisplayName()))\n {\n // We failed to add the reference, which means the project system wasn't able to bind.\n // We'll pop up the Add Reference dialog to let the user figure this out themselves.\n // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix\n\n if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy)\n {\n var command = new OLECMD[1];\n command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE;\n\n if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero)))\n {\n if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0)\n {\n uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero);\n }\n }\n }\n }\n }\n\n public override string Title\n => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName());\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1153,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeEvent.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.Runtime.InteropServices;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Interop;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements\n{\n [ComVisible(true)]\n [ComDefaultInterface(typeof(EnvDTE80.CodeEvent))]\n public sealed class ExternalCodeEvent : AbstractExternalCodeMember, EnvDTE80.CodeEvent\n {\n internal static EnvDTE80.CodeEvent Create(CodeModelState state, ProjectId projectId, IEventSymbol symbol)\n {\n var element = new ExternalCodeEvent(state, projectId, symbol);\n return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);\n }\n\n private ExternalCodeEvent(CodeModelState state, ProjectId projectId, IEventSymbol symbol)\n : base(state, projectId, symbol)\n {\n }\n\n private IEventSymbol EventSymbol\n {\n get { return (IEventSymbol)LookupSymbol(); }\n }\n\n protected override EnvDTE.CodeElements GetParameters()\n => throw new NotImplementedException();\n\n public override EnvDTE.vsCMElement Kind\n {\n get { return EnvDTE.vsCMElement.vsCMElementEvent; }\n }\n\n public EnvDTE.CodeFunction Adder\n {\n get\n {\n var symbol = EventSymbol;\n if (symbol.AddMethod == null)\n {\n throw Exceptions.ThrowEFail();\n }\n\n return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.AddMethod, this);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n // TODO: Verify VB implementation\n public bool IsPropertyStyleEvent\n {\n get { return true; }\n }\n\n // TODO: Verify VB implementation\n public EnvDTE80.vsCMOverrideKind OverrideKind\n {\n get\n {\n throw Exceptions.ThrowENotImpl();\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n public EnvDTE.CodeFunction Remover\n {\n get\n {\n var symbol = EventSymbol;\n if (symbol.RemoveMethod == null)\n {\n throw Exceptions.ThrowEFail();\n }\n\n return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RemoveMethod, this);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n public EnvDTE.CodeFunction Thrower\n {\n get\n {\n // TODO: Verify this with VB implementation\n var symbol = EventSymbol;\n if (symbol.RaiseMethod == null)\n {\n throw Exceptions.ThrowEFail();\n }\n\n return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RaiseMethod, this);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n public EnvDTE.CodeTypeRef Type\n {\n get\n {\n return CodeTypeRef.Create(this.State, this, this.ProjectId, EventSymbol.Type);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\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.Runtime.InteropServices;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Interop;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements\n{\n [ComVisible(true)]\n [ComDefaultInterface(typeof(EnvDTE80.CodeEvent))]\n public sealed class ExternalCodeEvent : AbstractExternalCodeMember, EnvDTE80.CodeEvent\n {\n internal static EnvDTE80.CodeEvent Create(CodeModelState state, ProjectId projectId, IEventSymbol symbol)\n {\n var element = new ExternalCodeEvent(state, projectId, symbol);\n return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);\n }\n\n private ExternalCodeEvent(CodeModelState state, ProjectId projectId, IEventSymbol symbol)\n : base(state, projectId, symbol)\n {\n }\n\n private IEventSymbol EventSymbol\n {\n get { return (IEventSymbol)LookupSymbol(); }\n }\n\n protected override EnvDTE.CodeElements GetParameters()\n => throw new NotImplementedException();\n\n public override EnvDTE.vsCMElement Kind\n {\n get { return EnvDTE.vsCMElement.vsCMElementEvent; }\n }\n\n public EnvDTE.CodeFunction Adder\n {\n get\n {\n var symbol = EventSymbol;\n if (symbol.AddMethod == null)\n {\n throw Exceptions.ThrowEFail();\n }\n\n return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.AddMethod, this);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n // TODO: Verify VB implementation\n public bool IsPropertyStyleEvent\n {\n get { return true; }\n }\n\n // TODO: Verify VB implementation\n public EnvDTE80.vsCMOverrideKind OverrideKind\n {\n get\n {\n throw Exceptions.ThrowENotImpl();\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n public EnvDTE.CodeFunction Remover\n {\n get\n {\n var symbol = EventSymbol;\n if (symbol.RemoveMethod == null)\n {\n throw Exceptions.ThrowEFail();\n }\n\n return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RemoveMethod, this);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n public EnvDTE.CodeFunction Thrower\n {\n get\n {\n // TODO: Verify this with VB implementation\n var symbol = EventSymbol;\n if (symbol.RaiseMethod == null)\n {\n throw Exceptions.ThrowEFail();\n }\n\n return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RaiseMethod, this);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n\n public EnvDTE.CodeTypeRef Type\n {\n get\n {\n return CodeTypeRef.Create(this.State, this, this.ProjectId, EventSymbol.Type);\n }\n\n set\n {\n throw Exceptions.ThrowEFail();\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1154,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ParenthesesPreference.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.CodeStyle\n{\n internal enum ParenthesesPreference\n {\n AlwaysForClarity,\n NeverIfUnnecessary,\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.CodeStyle\n{\n internal enum ParenthesesPreference\n {\n AlwaysForClarity,\n NeverIfUnnecessary,\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1155,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Compilers/Core/Portable/EncodedStringText.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.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Text\n{\n internal static class EncodedStringText\n {\n private const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB\n\n /// \n /// Encoding to use when there is no byte order mark (BOM) on the stream. This encoder may throw a \n /// if the stream contains invalid UTF-8 bytes.\n /// \n private static readonly Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n\n private static readonly Lazy s_fallbackEncoding = new(CreateFallbackEncoding);\n\n /// \n /// Encoding to use when UTF-8 fails. We try to find the following, in order, if available:\n /// 1. The default ANSI codepage\n /// 2. CodePage 1252.\n /// 3. Latin1.\n /// \n internal static Encoding CreateFallbackEncoding()\n {\n try\n {\n if (CodePagesEncodingProvider.Instance != null)\n {\n // If we're running on CoreCLR we have to register the CodePagesEncodingProvider\n // first\n Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);\n }\n\n // Try to get the default ANSI code page in the operating system's\n // regional and language settings, and fall back to 1252 otherwise\n return Encoding.GetEncoding(0)\n ?? Encoding.GetEncoding(1252);\n }\n catch (NotSupportedException)\n {\n return Encoding.GetEncoding(name: \"Latin1\");\n }\n }\n\n /// \n /// Initializes an instance of from the provided stream. This version differs\n /// from in two ways:\n /// 1. It attempts to minimize allocations by trying to read the stream into a byte array.\n /// 2. If is null, it will first try UTF8 and, if that fails, it will\n /// try CodePage 1252. If CodePage 1252 is not available on the system, then it will try Latin1.\n /// \n /// The stream containing encoded text.\n /// \n /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark).\n /// If not specified auto-detect heuristics are used to determine the encoding. If these heuristics fail the decoding is assumed to be Encoding.Default.\n /// Note that if the stream starts with Byte Order Mark the value of is ignored.\n /// \n /// Indicates if the file can be embedded in the PDB.\n /// Hash algorithm used to calculate document checksum.\n /// \n /// The stream content can't be decoded using the specified , or\n /// is null and the stream appears to be a binary file.\n /// \n /// An IO error occurred while reading from the stream. \n internal static SourceText Create(Stream stream,\n Encoding? defaultEncoding = null,\n SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,\n bool canBeEmbedded = false)\n {\n return Create(stream,\n s_fallbackEncoding,\n defaultEncoding: defaultEncoding,\n checksumAlgorithm: checksumAlgorithm,\n canBeEmbedded: canBeEmbedded);\n }\n\n internal static SourceText Create(Stream stream,\n Lazy getEncoding,\n Encoding? defaultEncoding = null,\n SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,\n bool canBeEmbedded = false)\n {\n RoslynDebug.Assert(stream != null);\n RoslynDebug.Assert(stream.CanRead);\n\n bool detectEncoding = defaultEncoding == null;\n if (detectEncoding)\n {\n try\n {\n return Decode(stream, s_utf8Encoding, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: canBeEmbedded);\n }\n catch (DecoderFallbackException)\n {\n // Fall back to Encoding.ASCII\n }\n }\n\n try\n {\n return Decode(stream, defaultEncoding ?? getEncoding.Value, checksumAlgorithm, throwIfBinaryDetected: detectEncoding, canBeEmbedded: canBeEmbedded);\n }\n catch (DecoderFallbackException e)\n {\n throw new InvalidDataException(e.Message);\n }\n }\n\n /// \n /// Try to create a from the given stream using the given encoding.\n /// \n /// The input stream containing the encoded text. The stream will not be closed.\n /// The expected encoding of the stream. The actual encoding used may be different if byte order marks are detected.\n /// The checksum algorithm to use.\n /// Throw if binary (non-text) data is detected.\n /// Indicates if the text can be embedded in the PDB.\n /// The decoded from the stream. \n /// The decoder was unable to decode the stream with the given encoding. \n /// Error reading from stream. \n private static SourceText Decode(\n Stream data,\n Encoding encoding,\n SourceHashAlgorithm checksumAlgorithm,\n bool throwIfBinaryDetected = false,\n bool canBeEmbedded = false)\n {\n RoslynDebug.Assert(data != null);\n RoslynDebug.Assert(encoding != null);\n\n if (data.CanSeek)\n {\n data.Seek(0, SeekOrigin.Begin);\n\n // For small streams, see if we can read the byte buffer directly.\n if (encoding.GetMaxCharCountOrThrowIfHuge(data) < LargeObjectHeapLimitInChars)\n {\n if (TryGetBytesFromStream(data, out ArraySegment bytes) && bytes.Offset == 0 && bytes.Array is object)\n {\n return SourceText.From(bytes.Array,\n (int)data.Length,\n encoding,\n checksumAlgorithm,\n throwIfBinaryDetected,\n canBeEmbedded);\n }\n }\n }\n\n return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);\n }\n\n /// \n /// Some streams are easily represented as bytes.\n /// \n /// The stream\n /// The bytes, if available.\n /// \n /// True if the stream's bytes could easily be read, false otherwise.\n /// \n internal static bool TryGetBytesFromStream(Stream data, out ArraySegment bytes)\n {\n // PERF: If the input is a MemoryStream, we may be able to get at the buffer directly\n var memoryStream = data as MemoryStream;\n if (memoryStream != null)\n {\n return memoryStream.TryGetBuffer(out bytes);\n }\n\n // PERF: If the input is a FileStream, we may be able to minimize allocations\n var fileStream = data as FileStream;\n if (fileStream != null)\n {\n return TryGetBytesFromFileStream(fileStream, out bytes);\n }\n\n bytes = new ArraySegment(Array.Empty());\n return false;\n }\n\n /// \n /// Read the contents of a FileStream into a byte array.\n /// \n /// The FileStream with encoded text.\n /// A byte array filled with the contents of the file.\n /// True if a byte array could be created. \n private static bool TryGetBytesFromFileStream(FileStream stream,\n out ArraySegment bytes)\n {\n RoslynDebug.Assert(stream != null);\n RoslynDebug.Assert(stream.Position == 0);\n\n int length = (int)stream.Length;\n if (length == 0)\n {\n bytes = new ArraySegment(Array.Empty());\n return true;\n }\n\n // PERF: While this is an obvious byte array allocation, it is still cheaper than\n // using StreamReader.ReadToEnd. The alternative allocates:\n // 1. A 1KB byte array in the StreamReader for buffered reads\n // 2. A 4KB byte array in the FileStream for buffered reads\n // 3. A StringBuilder and its associated char arrays (enough to represent the final decoded string)\n\n // TODO: Can this allocation be pooled?\n var buffer = new byte[length];\n\n // Note: FileStream.Read may still allocate its internal buffer if length is less\n // than the buffer size. The default buffer size is 4KB, so this will incur a 4KB\n // allocation for any files less than 4KB. That's why, for example, the command\n // line compiler actually specifies a very small buffer size.\n var success = stream.TryReadAll(buffer, 0, length) == length;\n\n bytes = success\n ? new ArraySegment(buffer)\n : new ArraySegment(Array.Empty());\n\n return success;\n }\n\n internal static class TestAccessor\n {\n internal static SourceText Create(Stream stream, Lazy getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)\n => EncodedStringText.Create(stream, getEncoding, defaultEncoding, checksumAlgorithm, canBeEmbedded);\n\n internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)\n => EncodedStringText.Decode(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);\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.Text;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis.Text\n{\n internal static class EncodedStringText\n {\n private const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB\n\n /// \n /// Encoding to use when there is no byte order mark (BOM) on the stream. This encoder may throw a \n /// if the stream contains invalid UTF-8 bytes.\n /// \n private static readonly Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n\n private static readonly Lazy s_fallbackEncoding = new(CreateFallbackEncoding);\n\n /// \n /// Encoding to use when UTF-8 fails. We try to find the following, in order, if available:\n /// 1. The default ANSI codepage\n /// 2. CodePage 1252.\n /// 3. Latin1.\n /// \n internal static Encoding CreateFallbackEncoding()\n {\n try\n {\n if (CodePagesEncodingProvider.Instance != null)\n {\n // If we're running on CoreCLR we have to register the CodePagesEncodingProvider\n // first\n Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);\n }\n\n // Try to get the default ANSI code page in the operating system's\n // regional and language settings, and fall back to 1252 otherwise\n return Encoding.GetEncoding(0)\n ?? Encoding.GetEncoding(1252);\n }\n catch (NotSupportedException)\n {\n return Encoding.GetEncoding(name: \"Latin1\");\n }\n }\n\n /// \n /// Initializes an instance of from the provided stream. This version differs\n /// from in two ways:\n /// 1. It attempts to minimize allocations by trying to read the stream into a byte array.\n /// 2. If is null, it will first try UTF8 and, if that fails, it will\n /// try CodePage 1252. If CodePage 1252 is not available on the system, then it will try Latin1.\n /// \n /// The stream containing encoded text.\n /// \n /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark).\n /// If not specified auto-detect heuristics are used to determine the encoding. If these heuristics fail the decoding is assumed to be Encoding.Default.\n /// Note that if the stream starts with Byte Order Mark the value of is ignored.\n /// \n /// Indicates if the file can be embedded in the PDB.\n /// Hash algorithm used to calculate document checksum.\n /// \n /// The stream content can't be decoded using the specified , or\n /// is null and the stream appears to be a binary file.\n /// \n /// An IO error occurred while reading from the stream. \n internal static SourceText Create(Stream stream,\n Encoding? defaultEncoding = null,\n SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,\n bool canBeEmbedded = false)\n {\n return Create(stream,\n s_fallbackEncoding,\n defaultEncoding: defaultEncoding,\n checksumAlgorithm: checksumAlgorithm,\n canBeEmbedded: canBeEmbedded);\n }\n\n internal static SourceText Create(Stream stream,\n Lazy getEncoding,\n Encoding? defaultEncoding = null,\n SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,\n bool canBeEmbedded = false)\n {\n RoslynDebug.Assert(stream != null);\n RoslynDebug.Assert(stream.CanRead);\n\n bool detectEncoding = defaultEncoding == null;\n if (detectEncoding)\n {\n try\n {\n return Decode(stream, s_utf8Encoding, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: canBeEmbedded);\n }\n catch (DecoderFallbackException)\n {\n // Fall back to Encoding.ASCII\n }\n }\n\n try\n {\n return Decode(stream, defaultEncoding ?? getEncoding.Value, checksumAlgorithm, throwIfBinaryDetected: detectEncoding, canBeEmbedded: canBeEmbedded);\n }\n catch (DecoderFallbackException e)\n {\n throw new InvalidDataException(e.Message);\n }\n }\n\n /// \n /// Try to create a from the given stream using the given encoding.\n /// \n /// The input stream containing the encoded text. The stream will not be closed.\n /// The expected encoding of the stream. The actual encoding used may be different if byte order marks are detected.\n /// The checksum algorithm to use.\n /// Throw if binary (non-text) data is detected.\n /// Indicates if the text can be embedded in the PDB.\n /// The decoded from the stream. \n /// The decoder was unable to decode the stream with the given encoding. \n /// Error reading from stream. \n private static SourceText Decode(\n Stream data,\n Encoding encoding,\n SourceHashAlgorithm checksumAlgorithm,\n bool throwIfBinaryDetected = false,\n bool canBeEmbedded = false)\n {\n RoslynDebug.Assert(data != null);\n RoslynDebug.Assert(encoding != null);\n\n if (data.CanSeek)\n {\n data.Seek(0, SeekOrigin.Begin);\n\n // For small streams, see if we can read the byte buffer directly.\n if (encoding.GetMaxCharCountOrThrowIfHuge(data) < LargeObjectHeapLimitInChars)\n {\n if (TryGetBytesFromStream(data, out ArraySegment bytes) && bytes.Offset == 0 && bytes.Array is object)\n {\n return SourceText.From(bytes.Array,\n (int)data.Length,\n encoding,\n checksumAlgorithm,\n throwIfBinaryDetected,\n canBeEmbedded);\n }\n }\n }\n\n return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);\n }\n\n /// \n /// Some streams are easily represented as bytes.\n /// \n /// The stream\n /// The bytes, if available.\n /// \n /// True if the stream's bytes could easily be read, false otherwise.\n /// \n internal static bool TryGetBytesFromStream(Stream data, out ArraySegment bytes)\n {\n // PERF: If the input is a MemoryStream, we may be able to get at the buffer directly\n var memoryStream = data as MemoryStream;\n if (memoryStream != null)\n {\n return memoryStream.TryGetBuffer(out bytes);\n }\n\n // PERF: If the input is a FileStream, we may be able to minimize allocations\n var fileStream = data as FileStream;\n if (fileStream != null)\n {\n return TryGetBytesFromFileStream(fileStream, out bytes);\n }\n\n bytes = new ArraySegment(Array.Empty());\n return false;\n }\n\n /// \n /// Read the contents of a FileStream into a byte array.\n /// \n /// The FileStream with encoded text.\n /// A byte array filled with the contents of the file.\n /// True if a byte array could be created. \n private static bool TryGetBytesFromFileStream(FileStream stream,\n out ArraySegment bytes)\n {\n RoslynDebug.Assert(stream != null);\n RoslynDebug.Assert(stream.Position == 0);\n\n int length = (int)stream.Length;\n if (length == 0)\n {\n bytes = new ArraySegment(Array.Empty());\n return true;\n }\n\n // PERF: While this is an obvious byte array allocation, it is still cheaper than\n // using StreamReader.ReadToEnd. The alternative allocates:\n // 1. A 1KB byte array in the StreamReader for buffered reads\n // 2. A 4KB byte array in the FileStream for buffered reads\n // 3. A StringBuilder and its associated char arrays (enough to represent the final decoded string)\n\n // TODO: Can this allocation be pooled?\n var buffer = new byte[length];\n\n // Note: FileStream.Read may still allocate its internal buffer if length is less\n // than the buffer size. The default buffer size is 4KB, so this will incur a 4KB\n // allocation for any files less than 4KB. That's why, for example, the command\n // line compiler actually specifies a very small buffer size.\n var success = stream.TryReadAll(buffer, 0, length) == length;\n\n bytes = success\n ? new ArraySegment(buffer)\n : new ArraySegment(Array.Empty());\n\n return success;\n }\n\n internal static class TestAccessor\n {\n internal static SourceText Create(Stream stream, Lazy getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)\n => EncodedStringText.Create(stream, getEncoding, defaultEncoding, checksumAlgorithm, canBeEmbedded);\n\n internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)\n => EncodedStringText.Decode(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1156,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Compilers/Test/Resources/Core/Encoding/sjis.cs"},"before_content":{"kind":"string","value":"using System.IO;\nusing System.Text;\n\nclass vleX\n{\n public static void Main()\n {\n File.WriteAllText(\"output.txt\", \" Y\", Encoding.GetEncoding(932));\n }\n}\n"},"after_content":{"kind":"string","value":"using System.IO;\nusing System.Text;\n\nclass vleX\n{\n public static void Main()\n {\n File.WriteAllText(\"output.txt\", \" Y\", Encoding.GetEncoding(932));\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1157,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IProjectCodeModelProvider.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.Threading;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS\n{\n internal sealed partial class CPSProject\n {\n public EnvDTE.CodeModel GetCodeModel(EnvDTE.Project parent)\n => _projectCodeModel.GetOrCreateRootCodeModel(parent);\n\n public EnvDTE.FileCodeModel GetFileCodeModel(EnvDTE.ProjectItem item)\n {\n if (!item.TryGetFullPath(out var filePath))\n {\n return null;\n }\n\n return _projectCodeModel.GetOrCreateFileCodeModel(filePath, item);\n }\n\n private class CPSCodeModelInstanceFactory : ICodeModelInstanceFactory\n {\n private readonly CPSProject _project;\n\n public CPSCodeModelInstanceFactory(CPSProject project)\n => _project = project;\n\n EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath)\n {\n var projectItem = GetProjectItem(filePath);\n if (projectItem == null)\n {\n return null;\n }\n\n return _project._projectCodeModel.GetOrCreateFileCodeModel(filePath, projectItem);\n }\n\n private EnvDTE.ProjectItem GetProjectItem(string filePath)\n {\n var dteProject = _project._visualStudioWorkspace.TryGetDTEProject(_project._visualStudioProject.Id);\n if (dteProject == null)\n {\n return null;\n }\n\n return dteProject.FindItemByPath(filePath, StringComparer.OrdinalIgnoreCase);\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.Threading;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS\n{\n internal sealed partial class CPSProject\n {\n public EnvDTE.CodeModel GetCodeModel(EnvDTE.Project parent)\n => _projectCodeModel.GetOrCreateRootCodeModel(parent);\n\n public EnvDTE.FileCodeModel GetFileCodeModel(EnvDTE.ProjectItem item)\n {\n if (!item.TryGetFullPath(out var filePath))\n {\n return null;\n }\n\n return _projectCodeModel.GetOrCreateFileCodeModel(filePath, item);\n }\n\n private class CPSCodeModelInstanceFactory : ICodeModelInstanceFactory\n {\n private readonly CPSProject _project;\n\n public CPSCodeModelInstanceFactory(CPSProject project)\n => _project = project;\n\n EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath)\n {\n var projectItem = GetProjectItem(filePath);\n if (projectItem == null)\n {\n return null;\n }\n\n return _project._projectCodeModel.GetOrCreateFileCodeModel(filePath, projectItem);\n }\n\n private EnvDTE.ProjectItem GetProjectItem(string filePath)\n {\n var dteProject = _project._visualStudioWorkspace.TryGetDTEProject(_project._visualStudioProject.Id);\n if (dteProject == null)\n {\n return null;\n }\n\n return dteProject.FindItemByPath(filePath, StringComparer.OrdinalIgnoreCase);\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1158,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.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.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Xml.Linq;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Completion;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp;\nusing Microsoft.CodeAnalysis.Editor.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Internal.Log;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.Notification;\nusing Microsoft.CodeAnalysis.Options;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Shared.Utilities;\nusing Microsoft.CodeAnalysis.SignatureHelp;\nusing Microsoft.CodeAnalysis.Text;\nusing Microsoft.CodeAnalysis.Text.Shared.Extensions;\nusing Microsoft.VisualStudio.Editor;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;\nusing Microsoft.VisualStudio.Text;\nusing Microsoft.VisualStudio.Text.Editor;\nusing Microsoft.VisualStudio.Text.Editor.Commanding;\nusing Microsoft.VisualStudio.Text.Editor.Commanding.Commands;\nusing Microsoft.VisualStudio.TextManager.Interop;\nusing MSXML;\nusing Roslyn.Utilities;\nusing CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers;\nusing VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets\n{\n internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient\n {\n /// \n /// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the\n /// invocation has no parameters.\n /// \n private const string PlaceholderSnippetField = \"placeholder\";\n\n /// \n /// A generated random string which is used to identify argument completion snippets from other snippets.\n /// \n private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString(\"N\");\n\n private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider;\n private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory;\n protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;\n protected readonly Guid LanguageServiceGuid;\n protected readonly ITextView TextView;\n protected readonly ITextBuffer SubjectBuffer;\n\n private readonly ImmutableArray> _allArgumentProviders;\n private ImmutableArray _argumentProviders;\n\n private bool _indentCaretOnCommit;\n private int _indentDepth;\n private bool _earlyEndExpansionHappened;\n\n /// \n /// Set to when the snippet client registers an event listener for\n /// .\n /// \n /// \n /// This field should only be used from the main thread.\n /// \n private bool _registeredForSignatureHelpEvents;\n\n // Writes to this state only occur on the main thread.\n private readonly State _state = new();\n\n public AbstractSnippetExpansionClient(\n IThreadingContext threadingContext,\n Guid languageServiceGuid,\n ITextView textView,\n ITextBuffer subjectBuffer,\n SignatureHelpControllerProvider signatureHelpControllerProvider,\n IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory,\n IVsEditorAdaptersFactoryService editorAdaptersFactoryService,\n ImmutableArray> argumentProviders)\n : base(threadingContext)\n {\n this.LanguageServiceGuid = languageServiceGuid;\n this.TextView = textView;\n this.SubjectBuffer = subjectBuffer;\n _signatureHelpControllerProvider = signatureHelpControllerProvider;\n _editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory;\n this.EditorAdaptersFactoryService = editorAdaptersFactoryService;\n _allArgumentProviders = argumentProviders;\n }\n\n /// \n public IVsExpansionSession? ExpansionSession => _state._expansionSession;\n\n /// \n public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet;\n\n public ImmutableArray GetArgumentProviders(Workspace workspace)\n {\n AssertIsForeground();\n\n // TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897\n if (_argumentProviders.IsDefault)\n {\n _argumentProviders = workspace.Services\n .SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType)\n .ToImmutableArray();\n }\n\n return _argumentProviders;\n }\n\n public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc);\n protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan();\n internal abstract Document AddImports(Document document, OptionSet options, int position, XElement snippetNode, bool allowInHiddenRegions, CancellationToken cancellationToken);\n protected abstract string FallbackDefaultLiteral { get; }\n\n public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer)\n {\n AssertIsForeground();\n\n if (ExpansionSession == null)\n {\n return VSConstants.E_FAIL;\n }\n\n // If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since\n // doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet'\n // because '_state._methodNameForInsertFullMethodCall' is not initialized at this point.\n if (ExpansionSession.TryGetHeaderNode(\"Description\", out var descriptionNode)\n && descriptionNode?.text == s_fullMethodCallDescriptionSentinel)\n {\n return VSConstants.S_OK;\n }\n\n // Formatting a snippet isn't cancellable.\n var cancellationToken = CancellationToken.None;\n // At this point, the $selection$ token has been replaced with the selected text and\n // declarations have been replaced with their default text. We need to format the \n // inserted snippet text while carefully handling $end$ position (where the caret goes\n // after Return is pressed). The IVsExpansionSession keeps a tracking point for this\n // position but we do the tracking ourselves to properly deal with virtual space. To \n // ensure the end location is correct, we take three extra steps:\n // 1. Insert an empty comment (\"/**/\" or \"'\") at the current $end$ position (prior \n // to formatting), and keep a tracking span for the comment.\n // 2. After formatting the new snippet text, find and delete the empty multiline \n // comment (via the tracking span) and notify the IVsExpansionSession of the new \n // $end$ location. If the line then contains only whitespace (due to the formatter\n // putting the empty comment on its own line), then delete the white space and \n // remember the indentation depth for that line.\n // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()\n // is called, check to see if the end location was on a line containing only white\n // space in the previous step. If so, and if that line is still empty, then position\n // the caret in virtual space.\n // This technique ensures that a snippet like \"if($condition$) { $end$ }\" will end up \n // as:\n // if ($condition$)\n // {\n // $end$\n // }\n if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan))\n {\n return VSConstants.S_OK;\n }\n\n // Insert empty comment and track end position\n var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);\n\n var fullSnippetSpan = new VsTextSpan[1];\n ExpansionSession.GetSnippetSpan(fullSnippetSpan);\n\n var isFullSnippetFormat =\n fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine &&\n fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex &&\n fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine &&\n fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex;\n var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;\n\n var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));\n\n SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None);\n\n if (isFullSnippetFormat)\n {\n CleanUpEndLocation(endPositionTrackingSpan);\n\n // Unfortunately, this is the only place we can safely add references and imports\n // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the\n // snippet xml will be available, and changing the buffer during OnAfterInsertion can\n // cause the underlying tracking spans to get out of sync.\n var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position;\n AddReferencesAndImports(\n ExpansionSession, currentStartPosition, cancellationToken);\n\n SetNewEndPosition(endPositionTrackingSpan);\n }\n\n return VSConstants.S_OK;\n }\n\n private void SetNewEndPosition(ITrackingSpan? endTrackingSpan)\n {\n RoslynDebug.AssertNotNull(ExpansionSession);\n if (SetEndPositionIfNoneSpecified(ExpansionSession))\n {\n return;\n }\n\n if (endTrackingSpan != null)\n {\n if (!TryGetSpanOnHigherBuffer(\n endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),\n TextView.TextBuffer,\n out var endSpanInSurfaceBuffer))\n {\n return;\n }\n\n TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar);\n ExpansionSession.SetEndSpan(new VsTextSpan\n {\n iStartLine = endLine,\n iStartIndex = endChar,\n iEndLine = endLine,\n iEndIndex = endChar\n });\n }\n }\n\n private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan)\n {\n if (endTrackingSpan != null)\n {\n // Find the empty comment and remove it...\n var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);\n SubjectBuffer.Delete(endSnapshotSpan.Span);\n\n // Remove the whitespace before the comment if necessary. If whitespace is removed,\n // then remember the indentation depth so we can appropriately position the caret\n // in virtual space when the session is ended.\n var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);\n var lineText = line.GetText();\n\n if (lineText.Trim() == string.Empty)\n {\n _indentCaretOnCommit = true;\n\n var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document != null)\n {\n var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize));\n }\n else\n {\n // If we don't have a document, then just guess the typical default TabSize value.\n _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4);\n }\n\n SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));\n _ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));\n }\n }\n }\n\n /// \n /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it\n /// defaults to the beginning of the snippet code.\n /// \n private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession)\n {\n if (!TryGetSnippetNode(pSession, out var snippetNode))\n {\n return false;\n }\n\n var ns = snippetNode.Name.NamespaceName;\n var codeNode = snippetNode.Element(XName.Get(\"Code\", ns));\n if (codeNode == null)\n {\n return false;\n }\n\n var delimiterAttribute = codeNode.Attribute(\"Delimiter\");\n var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : \"$\";\n if (codeNode.Value.IndexOf(string.Format(\"{0}end{0}\", delimiter), StringComparison.OrdinalIgnoreCase) != -1)\n {\n return false;\n }\n\n var snippetSpan = new VsTextSpan[1];\n if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK)\n {\n return false;\n }\n\n var newEndSpan = new VsTextSpan\n {\n iStartLine = snippetSpan[0].iEndLine,\n iStartIndex = snippetSpan[0].iEndIndex,\n iEndLine = snippetSpan[0].iEndLine,\n iEndIndex = snippetSpan[0].iEndIndex\n };\n\n pSession.SetEndSpan(newEndSpan);\n return true;\n }\n\n protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode)\n {\n IXMLDOMNode? xmlNode = null;\n snippetNode = null;\n\n try\n {\n // Cast to our own version of IVsExpansionSession so that we can get pNode as an\n // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is\n // released before leaving this method. Otherwise, a second invocation of the same\n // snippet may cause an AccessViolationException.\n var session = (IVsExpansionSessionInternal)pSession;\n if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK)\n {\n return false;\n }\n\n xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode);\n snippetNode = XElement.Parse(xmlNode.xml);\n return true;\n }\n finally\n {\n if (xmlNode != null && Marshal.IsComObject(xmlNode))\n {\n Marshal.ReleaseComObject(xmlNode);\n }\n }\n }\n\n public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName(\"Microsoft.VisualStudio.TextManager.Interop.TextSpan\")] VsTextSpan[] ts)\n {\n // If the formatted location of the $end$ position (the inserted comment) was on an\n // empty line and indented, then we have already removed the white space on that line\n // and the navigation location will be at column 0 on a blank line. We must now\n // position the caret in virtual space.\n pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength);\n pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText);\n pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition);\n\n PositionCaretForEditingInternal(endLineText, endLinePosition);\n\n return VSConstants.S_OK;\n }\n\n /// \n /// Internal for testing purposes. All real caret positioning logic takes place here. \n /// only extracts the and from the provided .\n /// Tests can call this method directly to avoid producing an IVsTextLines.\n /// \n /// \n /// \n internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition)\n {\n if (_indentCaretOnCommit && endLineText == string.Empty)\n {\n TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth));\n }\n }\n\n public virtual bool TryHandleTab()\n {\n if (ExpansionSession != null)\n {\n // When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the\n // first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an\n // argument provider snippet, the snippet session is automatically committed (this behavior matches the\n // design for Insert Full Method Call intended for multiple IDEs).\n var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0);\n\n if (!tabbedInsideSnippetField)\n {\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n }\n\n return tabbedInsideSnippetField;\n }\n\n return false;\n }\n\n public virtual bool TryHandleBackTab()\n {\n if (ExpansionSession != null)\n {\n var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField();\n\n if (!tabbedInsideSnippetField)\n {\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n }\n\n return tabbedInsideSnippetField;\n }\n\n return false;\n }\n\n public virtual bool TryHandleEscape()\n {\n if (ExpansionSession != null)\n {\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n return true;\n }\n\n return false;\n }\n\n public virtual bool TryHandleReturn()\n {\n return CommitSnippet(leaveCaret: false);\n }\n\n /// \n /// Commit the active snippet, if any.\n /// \n /// to leave the caret position unchanged by the call;\n /// otherwise, to move the caret to the $end$ position of the snippet when the\n /// snippet is committed.\n /// if the caret may have moved from the call; otherwise,\n /// if the caret did not move, or if there was no active snippet session to\n /// commit. \n public bool CommitSnippet(bool leaveCaret)\n {\n if (ExpansionSession != null)\n {\n if (!leaveCaret)\n {\n // Only move the caret if the enter was hit within the snippet fields.\n var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0);\n leaveCaret = !hitWithinField;\n }\n\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0);\n\n return !leaveCaret;\n }\n\n return false;\n }\n\n public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken)\n {\n var textViewModel = TextView.TextViewModel;\n if (textViewModel == null)\n {\n Debug.Assert(TextView.IsClosed);\n return false;\n }\n\n // The expansion itself needs to be created in the data buffer, so map everything up\n var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer);\n if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan))\n {\n return false;\n }\n\n var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);\n if (buffer is not IVsExpansion expansion)\n {\n return false;\n }\n\n buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex);\n buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex);\n\n var textSpan = new VsTextSpan\n {\n iStartLine = startLine,\n iStartIndex = startIndex,\n iEndLine = endLine,\n iEndIndex = endIndex\n };\n\n if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken))\n {\n Debug.Assert(_state.IsFullMethodCallSnippet);\n return true;\n }\n\n if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK)\n {\n // This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol\n // information\n Debug.Assert(!_state.IsFullMethodCallSnippet);\n return true;\n }\n\n return false;\n }\n\n private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken)\n {\n if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false))\n {\n // Argument completion snippets are not enabled\n return false;\n }\n\n var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document is null)\n {\n // Couldn't identify the current document\n return false;\n }\n\n var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken));\n\n var methodSymbols = symbols.OfType().ToImmutableArray();\n if (methodSymbols.Any())\n {\n // This is the method name as it appears in source text\n var methodName = dataBufferSpan.GetText();\n var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray.Empty, ImmutableDictionary.Empty);\n\n var doc = (DOMDocument)new DOMDocumentClass();\n if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))\n {\n if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)\n {\n Debug.Assert(_state._expansionSession != null);\n _state._methodNameForInsertFullMethodCall = methodSymbols.First().Name;\n Debug.Assert(_state._method == null);\n\n if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller)\n {\n EnsureRegisteredForModelUpdatedEvents(this, controller);\n }\n\n // Trigger signature help after starting the snippet session\n //\n // TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does.\n // https://github.com/dotnet/roslyn/issues/50036\n var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer);\n editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null);\n\n return true;\n }\n }\n }\n\n return false;\n\n // Local function\n static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller)\n {\n // Access to _registeredForSignatureHelpEvents is synchronized on the main thread\n client.ThreadingContext.ThrowIfNotOnUIThread();\n\n if (!client._registeredForSignatureHelpEvents)\n {\n client._registeredForSignatureHelpEvents = true;\n controller.ModelUpdated += client.OnModelUpdated;\n client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; };\n }\n }\n }\n\n /// \n /// Creates a snippet for providing arguments to a call.\n /// \n /// The name of the method as it should appear in code.\n /// \n /// to include the method name and invocation parentheses in the resulting snippet;\n /// otherwise, if the method name and parentheses are assumed to already exist and the\n /// template will only specify the argument placeholders. Since the $end$ marker is always considered to\n /// lie after the closing ) of the invocation, it is only included when this parameter is\n /// . \n ///\n /// For example, consider a call to . If\n /// is , the resulting snippet text might look like\n /// this: \n ///\n /// \n /// ToString($provider$)$end$\n ///
\n ///\n /// If is , the resulting snippet text might look\n /// like this: \n ///\n /// \n /// $provider$\n ///
\n ///\n /// This parameter supports cycling between overloads of a method for argument completion. Since any text\n /// edit that alters the ( or ) characters will force the Signature Help session to close, we are\n /// careful to only update text that lies between these characters. \n /// \n /// The parameters to the method. If the specific target of the invocation is not\n /// known, an empty array may be passed to create a template with a placeholder where arguments will eventually\n /// go.\n private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray parameters, ImmutableDictionary parameterValues)\n {\n XNamespace snippetNamespace = \"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\";\n\n var template = new StringBuilder();\n\n if (includeMethod)\n {\n template.Append(methodName).Append('(');\n }\n\n var declarations = new List();\n foreach (var parameter in parameters)\n {\n if (declarations.Any())\n {\n template.Append(\", \");\n }\n\n // Create a snippet field for the argument. The name of the field matches the parameter name, and the\n // default value for the field is provided by a call to the internal ArgumentValue snippet function. The\n // parameter to the snippet function is a serialized SymbolKey which can be mapped back to the\n // IParameterSymbol.\n template.Append('$').Append(parameter.Name).Append('$');\n declarations.Add(new XElement(\n snippetNamespace + \"Literal\",\n new XElement(snippetNamespace + \"ID\", new XText(parameter.Name)),\n new XElement(snippetNamespace + \"Default\", new XText(parameterValues.GetValueOrDefault(parameter.Name, \"\")))));\n }\n\n if (!declarations.Any())\n {\n // If the invocation does not have any parameters, include an empty placeholder in the snippet template\n // to ensure the caret starts inside the parentheses and can track changes to other overloads (which may\n // have parameters).\n template.Append($\"${PlaceholderSnippetField}$\");\n declarations.Add(new XElement(\n snippetNamespace + \"Literal\",\n new XElement(snippetNamespace + \"ID\", new XText(PlaceholderSnippetField)),\n new XElement(snippetNamespace + \"Default\", new XText(\"\"))));\n }\n\n if (includeMethod)\n {\n template.Append(')');\n }\n\n template.Append(\"$end$\");\n\n // A snippet is manually constructed. Replacement fields are added for each argument, and the field name\n // matches the parameter name.\n // https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019\n return new XDocument(\n new XDeclaration(\"1.0\", \"utf-8\", null),\n new XElement(\n snippetNamespace + \"CodeSnippets\",\n new XElement(\n snippetNamespace + \"CodeSnippet\",\n new XAttribute(snippetNamespace + \"Format\", \"1.0.0\"),\n new XElement(\n snippetNamespace + \"Header\",\n new XElement(snippetNamespace + \"Title\", new XText(methodName)),\n new XElement(snippetNamespace + \"Description\", new XText(s_fullMethodCallDescriptionSentinel))),\n new XElement(\n snippetNamespace + \"Snippet\",\n new XElement(snippetNamespace + \"Declarations\", declarations.ToArray()),\n new XElement(\n snippetNamespace + \"Code\",\n new XAttribute(snippetNamespace + \"Language\", \"csharp\"),\n new XCData(template.ToString()))))));\n }\n\n private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e)\n {\n AssertIsForeground();\n\n if (e.NewModel is null)\n {\n // Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space.\n // Leave the snippet session (if any) in its current state to allow it to process either a subsequent\n // Signature Help update or the Escape/Enter keys that close the snippet session.\n return;\n }\n\n if (!_state.IsFullMethodCallSnippet)\n {\n // Signature Help is showing an updated signature, but either there is no active snippet, or the active\n // snippet is not performing argument value completion, so we just ignore it.\n return;\n }\n\n if (!e.NewModel.UserSelected && _state._method is not null)\n {\n // This was an implicit signature change which was not triggered by user pressing up/down, and we are\n // already showing an initialized argument completion snippet session, so avoid switching sessions.\n return;\n }\n\n var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document is null)\n {\n // It's unclear if/how this state would occur, but if it does we would throw an exception trying to\n // use it. Just return immediately.\n return;\n }\n\n // TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value\n // completion session is active, which is behind an experimental feature flag.\n // https://github.com/dotnet/roslyn/issues/50634\n var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None));\n var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default;\n var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol();\n if (newSymbol is not IMethodSymbol method)\n return;\n\n MoveToSpecificMethod(method, CancellationToken.None);\n }\n\n private static async Task> GetReferencedSymbolsToLeftOfCaretAsync(\n Document document,\n SnapshotPoint caretPosition,\n CancellationToken cancellationToken)\n {\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService(), cancellationToken).ConfigureAwait(false);\n if (token.RawKind == 0)\n {\n // There is no touching word, so return empty immediately\n return ImmutableArray.Empty;\n }\n\n var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken);\n return semanticInfo.ReferencedSymbols;\n }\n\n /// \n /// Update the current argument value completion session to use a specific method.\n /// \n /// The currently-selected method in Signature Help.\n /// A cancellation token the operation may observe.\n public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken)\n {\n AssertIsForeground();\n\n if (ExpansionSession is null)\n {\n return;\n }\n\n if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method))\n {\n return;\n }\n\n if (_state._methodNameForInsertFullMethodCall != method.Name)\n {\n // Signature Help is showing a signature that wasn't part of the set this argument value completion\n // session was created from. It's unclear how this state should be handled, so we stop processing\n // Signature Help updates for the current session.\n // TODO: https://github.com/dotnet/roslyn/issues/50636\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n return;\n }\n\n // If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet\n // as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters)\n // causes the inserted session to immediately dismiss; this works around that issue.\n if (_state._method is null && method.Parameters.Length == 0)\n {\n _state._method = method;\n return;\n }\n\n var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document is null)\n {\n // Couldn't identify the current document\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n return;\n }\n\n var textViewModel = TextView.TextViewModel;\n if (textViewModel == null)\n {\n Debug.Assert(TextView.IsClosed);\n return;\n }\n\n var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);\n if (buffer is not IVsExpansion expansion)\n {\n return;\n }\n\n // We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses.\n // This span starts at the beginning of the first snippet field, and ends at the end of the last snippet\n // field. Methods with no arguments still have an empty \"placeholder\" snippet field representing the initial\n // caret position when the snippet is created.\n var textSpan = new VsTextSpan[1];\n if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK)\n {\n return;\n }\n\n var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField;\n if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK)\n {\n return;\n }\n\n VsTextSpan adjustedTextSpan;\n adjustedTextSpan.iStartLine = textSpan[0].iStartLine;\n adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex;\n\n var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField;\n if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK)\n {\n return;\n }\n\n adjustedTextSpan.iEndLine = textSpan[0].iEndLine;\n adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex;\n\n // Track current argument values so input created/updated by a user is not lost when cycling through\n // Signature Help overloads:\n //\n // 1. For each parameter of the method currently presented as a snippet, the value of the argument as\n // it appears in code.\n // 2. Place the argument values in a map from parameter name to current value.\n // 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters.\n var newArguments = _state._arguments;\n\n if (_state._method is null || !_state._method.Parameters.Any())\n {\n // If we didn't have any previous parameters, then there is only the placeholder in the snippet.\n // We don't want to lose what the user has typed there, if they typed something\n if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK &&\n placeholderValue.Length > 0)\n {\n if (method.Parameters.Any())\n {\n newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue);\n }\n else\n {\n // TODO: if the user is typing before signature help updated the model, and we have no parameters here,\n // should we still create a new snippet that has the existing placeholder text?\n }\n }\n }\n else if (_state._method is not null)\n {\n foreach (var previousParameter in _state._method.Parameters)\n {\n if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK)\n {\n newArguments = newArguments.SetItem(previousParameter.Name, previousValue);\n }\n }\n }\n\n // Now compute the new arguments for the new call\n var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken);\n var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex);\n\n foreach (var parameter in method.Parameters)\n {\n newArguments.TryGetValue(parameter.Name, out var value);\n\n foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace))\n {\n var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken);\n ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context));\n\n if (context.DefaultValue is not null)\n {\n value = context.DefaultValue;\n break;\n }\n }\n\n // If we still have no value, fill in the default\n if (value is null)\n {\n value = FallbackDefaultLiteral;\n }\n\n newArguments = newArguments.SetItem(parameter.Name, value);\n }\n\n var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments);\n var doc = (DOMDocument)new DOMDocumentClass();\n if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))\n {\n if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)\n {\n Debug.Assert(_state._expansionSession != null);\n _state._methodNameForInsertFullMethodCall = method.Name;\n _state._method = method;\n _state._arguments = newArguments;\n\n // On this path, the closing parenthesis is not part of the updated snippet, so there is no way for\n // the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead,\n // we use the internal APIs to manually specify the effective position of the $end$ marker as the\n // location in code immediately following the ')'. To do this, we use the knowledge that the snippet\n // includes all text up to (but not including) the ')', and move that span one position to the\n // right.\n if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK)\n {\n textSpan[0].iStartIndex++;\n textSpan[0].iEndIndex++;\n ExpansionSession.SetEndSpan(textSpan[0]);\n }\n }\n }\n }\n\n public int EndExpansion()\n {\n if (ExpansionSession == null)\n {\n _earlyEndExpansionHappened = true;\n }\n\n _state.Clear();\n\n _indentCaretOnCommit = false;\n\n return VSConstants.S_OK;\n }\n\n public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind)\n {\n pfIsValidKind = 1;\n return VSConstants.S_OK;\n }\n\n public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType)\n {\n pfIsValidType = 1;\n return VSConstants.S_OK;\n }\n\n public int OnAfterInsertion(IVsExpansionSession pSession)\n {\n Logger.Log(FunctionId.Snippet_OnAfterInsertion);\n\n return VSConstants.S_OK;\n }\n\n public int OnBeforeInsertion(IVsExpansionSession pSession)\n {\n Logger.Log(FunctionId.Snippet_OnBeforeInsertion);\n\n _state._expansionSession = pSession;\n\n // Symbol information (when necessary) is set by the caller\n\n return VSConstants.S_OK;\n }\n\n public int OnItemChosen(string pszTitle, string pszPath)\n {\n var textViewModel = TextView.TextViewModel;\n if (textViewModel == null)\n {\n Debug.Assert(TextView.IsClosed);\n return VSConstants.E_FAIL;\n }\n\n int hr;\n try\n {\n VsTextSpan textSpan;\n GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex);\n\n textSpan.iEndLine = textSpan.iStartLine;\n textSpan.iEndIndex = textSpan.iStartIndex;\n\n var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);\n Contract.ThrowIfNull(expansion);\n\n _earlyEndExpansionHappened = false;\n\n hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession);\n\n if (_earlyEndExpansionHappened)\n {\n // EndExpansion was called before InsertNamedExpansion returned, so set\n // expansionSession to null to indicate that there is no active expansion\n // session. This can occur when the snippet inserted doesn't have any expansion\n // fields.\n _state._expansionSession = null;\n _earlyEndExpansionHappened = false;\n }\n }\n catch (COMException ex)\n {\n hr = ex.ErrorCode;\n }\n\n return hr;\n }\n\n private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn)\n {\n var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView);\n Contract.ThrowIfNull(vsTextView);\n vsTextView.GetCaretPos(out caretLine, out caretColumn);\n vsTextView.GetBuffer(out var textLines);\n // Handle virtual space (e.g, see Dev10 778675)\n textLines.GetLengthOfLine(caretLine, out var lineLength);\n if (caretColumn > lineLength)\n {\n caretColumn = lineLength;\n }\n }\n\n private void AddReferencesAndImports(\n IVsExpansionSession pSession,\n int position,\n CancellationToken cancellationToken)\n {\n if (!TryGetSnippetNode(pSession, out var snippetNode))\n {\n return;\n }\n\n var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (documentWithImports == null)\n {\n return;\n }\n\n var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);\n var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions();\n\n documentWithImports = AddImports(documentWithImports, documentOptions, position, snippetNode, allowInHiddenRegions, cancellationToken);\n AddReferences(documentWithImports.Project, snippetNode);\n }\n\n private void AddReferences(Project originalProject, XElement snippetNode)\n {\n var referencesNode = snippetNode.Element(XName.Get(\"References\", snippetNode.Name.NamespaceName));\n if (referencesNode == null)\n {\n return;\n }\n\n var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display));\n var workspace = originalProject.Solution.Workspace;\n var projectId = originalProject.Id;\n\n var assemblyXmlName = XName.Get(\"Assembly\", snippetNode.Name.NamespaceName);\n var failedReferenceAdditions = new List();\n\n foreach (var reference in referencesNode.Elements(XName.Get(\"Reference\", snippetNode.Name.NamespaceName)))\n {\n // Note: URL references are not supported\n var assemblyElement = reference.Element(assemblyXmlName);\n\n var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null;\n\n if (RoslynString.IsNullOrEmpty(assemblyName))\n {\n continue;\n }\n\n if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace ||\n !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName))\n {\n failedReferenceAdditions.Add(assemblyName);\n }\n }\n\n if (failedReferenceAdditions.Any())\n {\n var notificationService = workspace.Services.GetRequiredService();\n notificationService.SendNotification(\n string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine)\n + Environment.NewLine + Environment.NewLine\n + string.Join(Environment.NewLine, failedReferenceAdditions),\n severity: NotificationSeverity.Warning);\n }\n }\n\n protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable memberImportsNamespaces)\n {\n if (document.Project.Solution.Workspace is not VisualStudioWorkspaceImpl vsWorkspace)\n {\n return false;\n }\n\n var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id);\n if (containedDocument == null)\n {\n return false;\n }\n\n if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost)\n {\n foreach (var importClause in memberImportsNamespaces)\n {\n if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK)\n {\n return false;\n }\n }\n }\n\n return true;\n }\n\n protected static bool TryGetSnippetFunctionInfo(\n IXMLDOMNode xmlFunctionNode,\n [NotNullWhen(true)] out string? snippetFunctionName,\n [NotNullWhen(true)] out string? param)\n {\n if (xmlFunctionNode.text.IndexOf('(') == -1 ||\n xmlFunctionNode.text.IndexOf(')') == -1 ||\n xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('('))\n {\n snippetFunctionName = null;\n param = null;\n return false;\n }\n\n snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('('));\n\n var paramStart = xmlFunctionNode.text.IndexOf('(') + 1;\n var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1;\n param = xmlFunctionNode.text.Substring(paramStart, paramLength);\n return true;\n }\n\n internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan)\n {\n var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan);\n var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);\n\n // Bail if a snippet span does not map down to exactly one subject buffer span.\n if (subjectBufferSpanCollection.Count == 1)\n {\n subjectBufferSpan = subjectBufferSpanCollection.Single();\n return true;\n }\n\n subjectBufferSpan = default;\n return false;\n }\n\n internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)\n {\n var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);\n\n // Bail if a snippet span does not map up to exactly one span.\n if (spanCollection.Count == 1)\n {\n span = spanCollection.Single();\n return true;\n }\n\n span = default;\n return false;\n }\n\n private sealed class State\n {\n /// \n /// The current expansion session.\n /// \n public IVsExpansionSession? _expansionSession;\n\n /// \n /// The symbol name of the method that we have invoked insert full method call on; or \n /// if there is no active snippet session or the active session is a regular snippets session.\n /// \n public string? _methodNameForInsertFullMethodCall;\n\n /// \n /// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help\n /// has not yet provided a symbol to show.\n /// \n public IMethodSymbol? _method;\n\n /// \n /// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for\n /// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a\n /// parameter with this name. This map is cleared at the final end of an argument provider snippet session.\n /// \n public ImmutableDictionary _arguments = ImmutableDictionary.Create();\n\n /// \n /// if the current snippet session is a Full Method Call snippet session; otherwise,\n /// if there is no current snippet session or if the current snippet session is a normal snippet.\n /// \n public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null;\n\n public void Clear()\n {\n _expansionSession = null;\n _methodNameForInsertFullMethodCall = null;\n _method = null;\n _arguments = _arguments.Clear();\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.Collections.Immutable;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Xml.Linq;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Completion;\nusing Microsoft.CodeAnalysis.Editing;\nusing Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp;\nusing Microsoft.CodeAnalysis.Editor.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.CodeAnalysis.Formatting;\nusing Microsoft.CodeAnalysis.Host.Mef;\nusing Microsoft.CodeAnalysis.Internal.Log;\nusing Microsoft.CodeAnalysis.LanguageServices;\nusing Microsoft.CodeAnalysis.Notification;\nusing Microsoft.CodeAnalysis.Options;\nusing Microsoft.CodeAnalysis.Shared.Extensions;\nusing Microsoft.CodeAnalysis.Shared.Utilities;\nusing Microsoft.CodeAnalysis.SignatureHelp;\nusing Microsoft.CodeAnalysis.Text;\nusing Microsoft.CodeAnalysis.Text.Shared.Extensions;\nusing Microsoft.VisualStudio.Editor;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;\nusing Microsoft.VisualStudio.Text;\nusing Microsoft.VisualStudio.Text.Editor;\nusing Microsoft.VisualStudio.Text.Editor.Commanding;\nusing Microsoft.VisualStudio.Text.Editor.Commanding.Commands;\nusing Microsoft.VisualStudio.TextManager.Interop;\nusing MSXML;\nusing Roslyn.Utilities;\nusing CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers;\nusing VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets\n{\n internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient\n {\n /// \n /// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the\n /// invocation has no parameters.\n /// \n private const string PlaceholderSnippetField = \"placeholder\";\n\n /// \n /// A generated random string which is used to identify argument completion snippets from other snippets.\n /// \n private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString(\"N\");\n\n private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider;\n private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory;\n protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;\n protected readonly Guid LanguageServiceGuid;\n protected readonly ITextView TextView;\n protected readonly ITextBuffer SubjectBuffer;\n\n private readonly ImmutableArray> _allArgumentProviders;\n private ImmutableArray _argumentProviders;\n\n private bool _indentCaretOnCommit;\n private int _indentDepth;\n private bool _earlyEndExpansionHappened;\n\n /// \n /// Set to when the snippet client registers an event listener for\n /// .\n /// \n /// \n /// This field should only be used from the main thread.\n /// \n private bool _registeredForSignatureHelpEvents;\n\n // Writes to this state only occur on the main thread.\n private readonly State _state = new();\n\n public AbstractSnippetExpansionClient(\n IThreadingContext threadingContext,\n Guid languageServiceGuid,\n ITextView textView,\n ITextBuffer subjectBuffer,\n SignatureHelpControllerProvider signatureHelpControllerProvider,\n IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory,\n IVsEditorAdaptersFactoryService editorAdaptersFactoryService,\n ImmutableArray> argumentProviders)\n : base(threadingContext)\n {\n this.LanguageServiceGuid = languageServiceGuid;\n this.TextView = textView;\n this.SubjectBuffer = subjectBuffer;\n _signatureHelpControllerProvider = signatureHelpControllerProvider;\n _editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory;\n this.EditorAdaptersFactoryService = editorAdaptersFactoryService;\n _allArgumentProviders = argumentProviders;\n }\n\n /// \n public IVsExpansionSession? ExpansionSession => _state._expansionSession;\n\n /// \n public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet;\n\n public ImmutableArray GetArgumentProviders(Workspace workspace)\n {\n AssertIsForeground();\n\n // TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897\n if (_argumentProviders.IsDefault)\n {\n _argumentProviders = workspace.Services\n .SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType)\n .ToImmutableArray();\n }\n\n return _argumentProviders;\n }\n\n public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc);\n protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan();\n internal abstract Document AddImports(Document document, OptionSet options, int position, XElement snippetNode, bool allowInHiddenRegions, CancellationToken cancellationToken);\n protected abstract string FallbackDefaultLiteral { get; }\n\n public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer)\n {\n AssertIsForeground();\n\n if (ExpansionSession == null)\n {\n return VSConstants.E_FAIL;\n }\n\n // If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since\n // doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet'\n // because '_state._methodNameForInsertFullMethodCall' is not initialized at this point.\n if (ExpansionSession.TryGetHeaderNode(\"Description\", out var descriptionNode)\n && descriptionNode?.text == s_fullMethodCallDescriptionSentinel)\n {\n return VSConstants.S_OK;\n }\n\n // Formatting a snippet isn't cancellable.\n var cancellationToken = CancellationToken.None;\n // At this point, the $selection$ token has been replaced with the selected text and\n // declarations have been replaced with their default text. We need to format the \n // inserted snippet text while carefully handling $end$ position (where the caret goes\n // after Return is pressed). The IVsExpansionSession keeps a tracking point for this\n // position but we do the tracking ourselves to properly deal with virtual space. To \n // ensure the end location is correct, we take three extra steps:\n // 1. Insert an empty comment (\"/**/\" or \"'\") at the current $end$ position (prior \n // to formatting), and keep a tracking span for the comment.\n // 2. After formatting the new snippet text, find and delete the empty multiline \n // comment (via the tracking span) and notify the IVsExpansionSession of the new \n // $end$ location. If the line then contains only whitespace (due to the formatter\n // putting the empty comment on its own line), then delete the white space and \n // remember the indentation depth for that line.\n // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()\n // is called, check to see if the end location was on a line containing only white\n // space in the previous step. If so, and if that line is still empty, then position\n // the caret in virtual space.\n // This technique ensures that a snippet like \"if($condition$) { $end$ }\" will end up \n // as:\n // if ($condition$)\n // {\n // $end$\n // }\n if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan))\n {\n return VSConstants.S_OK;\n }\n\n // Insert empty comment and track end position\n var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);\n\n var fullSnippetSpan = new VsTextSpan[1];\n ExpansionSession.GetSnippetSpan(fullSnippetSpan);\n\n var isFullSnippetFormat =\n fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine &&\n fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex &&\n fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine &&\n fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex;\n var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;\n\n var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));\n\n SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None);\n\n if (isFullSnippetFormat)\n {\n CleanUpEndLocation(endPositionTrackingSpan);\n\n // Unfortunately, this is the only place we can safely add references and imports\n // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the\n // snippet xml will be available, and changing the buffer during OnAfterInsertion can\n // cause the underlying tracking spans to get out of sync.\n var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position;\n AddReferencesAndImports(\n ExpansionSession, currentStartPosition, cancellationToken);\n\n SetNewEndPosition(endPositionTrackingSpan);\n }\n\n return VSConstants.S_OK;\n }\n\n private void SetNewEndPosition(ITrackingSpan? endTrackingSpan)\n {\n RoslynDebug.AssertNotNull(ExpansionSession);\n if (SetEndPositionIfNoneSpecified(ExpansionSession))\n {\n return;\n }\n\n if (endTrackingSpan != null)\n {\n if (!TryGetSpanOnHigherBuffer(\n endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),\n TextView.TextBuffer,\n out var endSpanInSurfaceBuffer))\n {\n return;\n }\n\n TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar);\n ExpansionSession.SetEndSpan(new VsTextSpan\n {\n iStartLine = endLine,\n iStartIndex = endChar,\n iEndLine = endLine,\n iEndIndex = endChar\n });\n }\n }\n\n private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan)\n {\n if (endTrackingSpan != null)\n {\n // Find the empty comment and remove it...\n var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);\n SubjectBuffer.Delete(endSnapshotSpan.Span);\n\n // Remove the whitespace before the comment if necessary. If whitespace is removed,\n // then remember the indentation depth so we can appropriately position the caret\n // in virtual space when the session is ended.\n var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);\n var lineText = line.GetText();\n\n if (lineText.Trim() == string.Empty)\n {\n _indentCaretOnCommit = true;\n\n var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document != null)\n {\n var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize));\n }\n else\n {\n // If we don't have a document, then just guess the typical default TabSize value.\n _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4);\n }\n\n SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));\n _ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));\n }\n }\n }\n\n /// \n /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it\n /// defaults to the beginning of the snippet code.\n /// \n private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession)\n {\n if (!TryGetSnippetNode(pSession, out var snippetNode))\n {\n return false;\n }\n\n var ns = snippetNode.Name.NamespaceName;\n var codeNode = snippetNode.Element(XName.Get(\"Code\", ns));\n if (codeNode == null)\n {\n return false;\n }\n\n var delimiterAttribute = codeNode.Attribute(\"Delimiter\");\n var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : \"$\";\n if (codeNode.Value.IndexOf(string.Format(\"{0}end{0}\", delimiter), StringComparison.OrdinalIgnoreCase) != -1)\n {\n return false;\n }\n\n var snippetSpan = new VsTextSpan[1];\n if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK)\n {\n return false;\n }\n\n var newEndSpan = new VsTextSpan\n {\n iStartLine = snippetSpan[0].iEndLine,\n iStartIndex = snippetSpan[0].iEndIndex,\n iEndLine = snippetSpan[0].iEndLine,\n iEndIndex = snippetSpan[0].iEndIndex\n };\n\n pSession.SetEndSpan(newEndSpan);\n return true;\n }\n\n protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode)\n {\n IXMLDOMNode? xmlNode = null;\n snippetNode = null;\n\n try\n {\n // Cast to our own version of IVsExpansionSession so that we can get pNode as an\n // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is\n // released before leaving this method. Otherwise, a second invocation of the same\n // snippet may cause an AccessViolationException.\n var session = (IVsExpansionSessionInternal)pSession;\n if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK)\n {\n return false;\n }\n\n xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode);\n snippetNode = XElement.Parse(xmlNode.xml);\n return true;\n }\n finally\n {\n if (xmlNode != null && Marshal.IsComObject(xmlNode))\n {\n Marshal.ReleaseComObject(xmlNode);\n }\n }\n }\n\n public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName(\"Microsoft.VisualStudio.TextManager.Interop.TextSpan\")] VsTextSpan[] ts)\n {\n // If the formatted location of the $end$ position (the inserted comment) was on an\n // empty line and indented, then we have already removed the white space on that line\n // and the navigation location will be at column 0 on a blank line. We must now\n // position the caret in virtual space.\n pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength);\n pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText);\n pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition);\n\n PositionCaretForEditingInternal(endLineText, endLinePosition);\n\n return VSConstants.S_OK;\n }\n\n /// \n /// Internal for testing purposes. All real caret positioning logic takes place here. \n /// only extracts the and from the provided .\n /// Tests can call this method directly to avoid producing an IVsTextLines.\n /// \n /// \n /// \n internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition)\n {\n if (_indentCaretOnCommit && endLineText == string.Empty)\n {\n TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth));\n }\n }\n\n public virtual bool TryHandleTab()\n {\n if (ExpansionSession != null)\n {\n // When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the\n // first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an\n // argument provider snippet, the snippet session is automatically committed (this behavior matches the\n // design for Insert Full Method Call intended for multiple IDEs).\n var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0);\n\n if (!tabbedInsideSnippetField)\n {\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n }\n\n return tabbedInsideSnippetField;\n }\n\n return false;\n }\n\n public virtual bool TryHandleBackTab()\n {\n if (ExpansionSession != null)\n {\n var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField();\n\n if (!tabbedInsideSnippetField)\n {\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n }\n\n return tabbedInsideSnippetField;\n }\n\n return false;\n }\n\n public virtual bool TryHandleEscape()\n {\n if (ExpansionSession != null)\n {\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n return true;\n }\n\n return false;\n }\n\n public virtual bool TryHandleReturn()\n {\n return CommitSnippet(leaveCaret: false);\n }\n\n /// \n /// Commit the active snippet, if any.\n /// \n /// to leave the caret position unchanged by the call;\n /// otherwise, to move the caret to the $end$ position of the snippet when the\n /// snippet is committed.\n /// if the caret may have moved from the call; otherwise,\n /// if the caret did not move, or if there was no active snippet session to\n /// commit. \n public bool CommitSnippet(bool leaveCaret)\n {\n if (ExpansionSession != null)\n {\n if (!leaveCaret)\n {\n // Only move the caret if the enter was hit within the snippet fields.\n var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0);\n leaveCaret = !hitWithinField;\n }\n\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0);\n\n return !leaveCaret;\n }\n\n return false;\n }\n\n public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken)\n {\n var textViewModel = TextView.TextViewModel;\n if (textViewModel == null)\n {\n Debug.Assert(TextView.IsClosed);\n return false;\n }\n\n // The expansion itself needs to be created in the data buffer, so map everything up\n var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer);\n if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan))\n {\n return false;\n }\n\n var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);\n if (buffer is not IVsExpansion expansion)\n {\n return false;\n }\n\n buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex);\n buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex);\n\n var textSpan = new VsTextSpan\n {\n iStartLine = startLine,\n iStartIndex = startIndex,\n iEndLine = endLine,\n iEndIndex = endIndex\n };\n\n if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken))\n {\n Debug.Assert(_state.IsFullMethodCallSnippet);\n return true;\n }\n\n if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK)\n {\n // This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol\n // information\n Debug.Assert(!_state.IsFullMethodCallSnippet);\n return true;\n }\n\n return false;\n }\n\n private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken)\n {\n if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false))\n {\n // Argument completion snippets are not enabled\n return false;\n }\n\n var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document is null)\n {\n // Couldn't identify the current document\n return false;\n }\n\n var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken));\n\n var methodSymbols = symbols.OfType().ToImmutableArray();\n if (methodSymbols.Any())\n {\n // This is the method name as it appears in source text\n var methodName = dataBufferSpan.GetText();\n var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray.Empty, ImmutableDictionary.Empty);\n\n var doc = (DOMDocument)new DOMDocumentClass();\n if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))\n {\n if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)\n {\n Debug.Assert(_state._expansionSession != null);\n _state._methodNameForInsertFullMethodCall = methodSymbols.First().Name;\n Debug.Assert(_state._method == null);\n\n if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller)\n {\n EnsureRegisteredForModelUpdatedEvents(this, controller);\n }\n\n // Trigger signature help after starting the snippet session\n //\n // TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does.\n // https://github.com/dotnet/roslyn/issues/50036\n var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer);\n editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null);\n\n return true;\n }\n }\n }\n\n return false;\n\n // Local function\n static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller)\n {\n // Access to _registeredForSignatureHelpEvents is synchronized on the main thread\n client.ThreadingContext.ThrowIfNotOnUIThread();\n\n if (!client._registeredForSignatureHelpEvents)\n {\n client._registeredForSignatureHelpEvents = true;\n controller.ModelUpdated += client.OnModelUpdated;\n client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; };\n }\n }\n }\n\n /// \n /// Creates a snippet for providing arguments to a call.\n /// \n /// The name of the method as it should appear in code.\n /// \n /// to include the method name and invocation parentheses in the resulting snippet;\n /// otherwise, if the method name and parentheses are assumed to already exist and the\n /// template will only specify the argument placeholders. Since the $end$ marker is always considered to\n /// lie after the closing ) of the invocation, it is only included when this parameter is\n /// . \n ///\n /// For example, consider a call to . If\n /// is , the resulting snippet text might look like\n /// this: \n ///\n /// \n /// ToString($provider$)$end$\n ///
\n ///\n /// If is , the resulting snippet text might look\n /// like this: \n ///\n /// \n /// $provider$\n ///
\n ///\n /// This parameter supports cycling between overloads of a method for argument completion. Since any text\n /// edit that alters the ( or ) characters will force the Signature Help session to close, we are\n /// careful to only update text that lies between these characters. \n /// \n /// The parameters to the method. If the specific target of the invocation is not\n /// known, an empty array may be passed to create a template with a placeholder where arguments will eventually\n /// go.\n private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray parameters, ImmutableDictionary parameterValues)\n {\n XNamespace snippetNamespace = \"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\";\n\n var template = new StringBuilder();\n\n if (includeMethod)\n {\n template.Append(methodName).Append('(');\n }\n\n var declarations = new List();\n foreach (var parameter in parameters)\n {\n if (declarations.Any())\n {\n template.Append(\", \");\n }\n\n // Create a snippet field for the argument. The name of the field matches the parameter name, and the\n // default value for the field is provided by a call to the internal ArgumentValue snippet function. The\n // parameter to the snippet function is a serialized SymbolKey which can be mapped back to the\n // IParameterSymbol.\n template.Append('$').Append(parameter.Name).Append('$');\n declarations.Add(new XElement(\n snippetNamespace + \"Literal\",\n new XElement(snippetNamespace + \"ID\", new XText(parameter.Name)),\n new XElement(snippetNamespace + \"Default\", new XText(parameterValues.GetValueOrDefault(parameter.Name, \"\")))));\n }\n\n if (!declarations.Any())\n {\n // If the invocation does not have any parameters, include an empty placeholder in the snippet template\n // to ensure the caret starts inside the parentheses and can track changes to other overloads (which may\n // have parameters).\n template.Append($\"${PlaceholderSnippetField}$\");\n declarations.Add(new XElement(\n snippetNamespace + \"Literal\",\n new XElement(snippetNamespace + \"ID\", new XText(PlaceholderSnippetField)),\n new XElement(snippetNamespace + \"Default\", new XText(\"\"))));\n }\n\n if (includeMethod)\n {\n template.Append(')');\n }\n\n template.Append(\"$end$\");\n\n // A snippet is manually constructed. Replacement fields are added for each argument, and the field name\n // matches the parameter name.\n // https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019\n return new XDocument(\n new XDeclaration(\"1.0\", \"utf-8\", null),\n new XElement(\n snippetNamespace + \"CodeSnippets\",\n new XElement(\n snippetNamespace + \"CodeSnippet\",\n new XAttribute(snippetNamespace + \"Format\", \"1.0.0\"),\n new XElement(\n snippetNamespace + \"Header\",\n new XElement(snippetNamespace + \"Title\", new XText(methodName)),\n new XElement(snippetNamespace + \"Description\", new XText(s_fullMethodCallDescriptionSentinel))),\n new XElement(\n snippetNamespace + \"Snippet\",\n new XElement(snippetNamespace + \"Declarations\", declarations.ToArray()),\n new XElement(\n snippetNamespace + \"Code\",\n new XAttribute(snippetNamespace + \"Language\", \"csharp\"),\n new XCData(template.ToString()))))));\n }\n\n private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e)\n {\n AssertIsForeground();\n\n if (e.NewModel is null)\n {\n // Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space.\n // Leave the snippet session (if any) in its current state to allow it to process either a subsequent\n // Signature Help update or the Escape/Enter keys that close the snippet session.\n return;\n }\n\n if (!_state.IsFullMethodCallSnippet)\n {\n // Signature Help is showing an updated signature, but either there is no active snippet, or the active\n // snippet is not performing argument value completion, so we just ignore it.\n return;\n }\n\n if (!e.NewModel.UserSelected && _state._method is not null)\n {\n // This was an implicit signature change which was not triggered by user pressing up/down, and we are\n // already showing an initialized argument completion snippet session, so avoid switching sessions.\n return;\n }\n\n var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document is null)\n {\n // It's unclear if/how this state would occur, but if it does we would throw an exception trying to\n // use it. Just return immediately.\n return;\n }\n\n // TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value\n // completion session is active, which is behind an experimental feature flag.\n // https://github.com/dotnet/roslyn/issues/50634\n var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None));\n var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default;\n var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol();\n if (newSymbol is not IMethodSymbol method)\n return;\n\n MoveToSpecificMethod(method, CancellationToken.None);\n }\n\n private static async Task> GetReferencedSymbolsToLeftOfCaretAsync(\n Document document,\n SnapshotPoint caretPosition,\n CancellationToken cancellationToken)\n {\n var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);\n\n var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService(), cancellationToken).ConfigureAwait(false);\n if (token.RawKind == 0)\n {\n // There is no touching word, so return empty immediately\n return ImmutableArray.Empty;\n }\n\n var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken);\n return semanticInfo.ReferencedSymbols;\n }\n\n /// \n /// Update the current argument value completion session to use a specific method.\n /// \n /// The currently-selected method in Signature Help.\n /// A cancellation token the operation may observe.\n public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken)\n {\n AssertIsForeground();\n\n if (ExpansionSession is null)\n {\n return;\n }\n\n if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method))\n {\n return;\n }\n\n if (_state._methodNameForInsertFullMethodCall != method.Name)\n {\n // Signature Help is showing a signature that wasn't part of the set this argument value completion\n // session was created from. It's unclear how this state should be handled, so we stop processing\n // Signature Help updates for the current session.\n // TODO: https://github.com/dotnet/roslyn/issues/50636\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n return;\n }\n\n // If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet\n // as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters)\n // causes the inserted session to immediately dismiss; this works around that issue.\n if (_state._method is null && method.Parameters.Length == 0)\n {\n _state._method = method;\n return;\n }\n\n var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (document is null)\n {\n // Couldn't identify the current document\n ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);\n return;\n }\n\n var textViewModel = TextView.TextViewModel;\n if (textViewModel == null)\n {\n Debug.Assert(TextView.IsClosed);\n return;\n }\n\n var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);\n if (buffer is not IVsExpansion expansion)\n {\n return;\n }\n\n // We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses.\n // This span starts at the beginning of the first snippet field, and ends at the end of the last snippet\n // field. Methods with no arguments still have an empty \"placeholder\" snippet field representing the initial\n // caret position when the snippet is created.\n var textSpan = new VsTextSpan[1];\n if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK)\n {\n return;\n }\n\n var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField;\n if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK)\n {\n return;\n }\n\n VsTextSpan adjustedTextSpan;\n adjustedTextSpan.iStartLine = textSpan[0].iStartLine;\n adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex;\n\n var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField;\n if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK)\n {\n return;\n }\n\n adjustedTextSpan.iEndLine = textSpan[0].iEndLine;\n adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex;\n\n // Track current argument values so input created/updated by a user is not lost when cycling through\n // Signature Help overloads:\n //\n // 1. For each parameter of the method currently presented as a snippet, the value of the argument as\n // it appears in code.\n // 2. Place the argument values in a map from parameter name to current value.\n // 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters.\n var newArguments = _state._arguments;\n\n if (_state._method is null || !_state._method.Parameters.Any())\n {\n // If we didn't have any previous parameters, then there is only the placeholder in the snippet.\n // We don't want to lose what the user has typed there, if they typed something\n if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK &&\n placeholderValue.Length > 0)\n {\n if (method.Parameters.Any())\n {\n newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue);\n }\n else\n {\n // TODO: if the user is typing before signature help updated the model, and we have no parameters here,\n // should we still create a new snippet that has the existing placeholder text?\n }\n }\n }\n else if (_state._method is not null)\n {\n foreach (var previousParameter in _state._method.Parameters)\n {\n if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK)\n {\n newArguments = newArguments.SetItem(previousParameter.Name, previousValue);\n }\n }\n }\n\n // Now compute the new arguments for the new call\n var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken);\n var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex);\n\n foreach (var parameter in method.Parameters)\n {\n newArguments.TryGetValue(parameter.Name, out var value);\n\n foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace))\n {\n var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken);\n ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context));\n\n if (context.DefaultValue is not null)\n {\n value = context.DefaultValue;\n break;\n }\n }\n\n // If we still have no value, fill in the default\n if (value is null)\n {\n value = FallbackDefaultLiteral;\n }\n\n newArguments = newArguments.SetItem(parameter.Name, value);\n }\n\n var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments);\n var doc = (DOMDocument)new DOMDocumentClass();\n if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))\n {\n if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)\n {\n Debug.Assert(_state._expansionSession != null);\n _state._methodNameForInsertFullMethodCall = method.Name;\n _state._method = method;\n _state._arguments = newArguments;\n\n // On this path, the closing parenthesis is not part of the updated snippet, so there is no way for\n // the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead,\n // we use the internal APIs to manually specify the effective position of the $end$ marker as the\n // location in code immediately following the ')'. To do this, we use the knowledge that the snippet\n // includes all text up to (but not including) the ')', and move that span one position to the\n // right.\n if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK)\n {\n textSpan[0].iStartIndex++;\n textSpan[0].iEndIndex++;\n ExpansionSession.SetEndSpan(textSpan[0]);\n }\n }\n }\n }\n\n public int EndExpansion()\n {\n if (ExpansionSession == null)\n {\n _earlyEndExpansionHappened = true;\n }\n\n _state.Clear();\n\n _indentCaretOnCommit = false;\n\n return VSConstants.S_OK;\n }\n\n public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind)\n {\n pfIsValidKind = 1;\n return VSConstants.S_OK;\n }\n\n public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType)\n {\n pfIsValidType = 1;\n return VSConstants.S_OK;\n }\n\n public int OnAfterInsertion(IVsExpansionSession pSession)\n {\n Logger.Log(FunctionId.Snippet_OnAfterInsertion);\n\n return VSConstants.S_OK;\n }\n\n public int OnBeforeInsertion(IVsExpansionSession pSession)\n {\n Logger.Log(FunctionId.Snippet_OnBeforeInsertion);\n\n _state._expansionSession = pSession;\n\n // Symbol information (when necessary) is set by the caller\n\n return VSConstants.S_OK;\n }\n\n public int OnItemChosen(string pszTitle, string pszPath)\n {\n var textViewModel = TextView.TextViewModel;\n if (textViewModel == null)\n {\n Debug.Assert(TextView.IsClosed);\n return VSConstants.E_FAIL;\n }\n\n int hr;\n try\n {\n VsTextSpan textSpan;\n GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex);\n\n textSpan.iEndLine = textSpan.iStartLine;\n textSpan.iEndIndex = textSpan.iStartIndex;\n\n var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);\n Contract.ThrowIfNull(expansion);\n\n _earlyEndExpansionHappened = false;\n\n hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession);\n\n if (_earlyEndExpansionHappened)\n {\n // EndExpansion was called before InsertNamedExpansion returned, so set\n // expansionSession to null to indicate that there is no active expansion\n // session. This can occur when the snippet inserted doesn't have any expansion\n // fields.\n _state._expansionSession = null;\n _earlyEndExpansionHappened = false;\n }\n }\n catch (COMException ex)\n {\n hr = ex.ErrorCode;\n }\n\n return hr;\n }\n\n private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn)\n {\n var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView);\n Contract.ThrowIfNull(vsTextView);\n vsTextView.GetCaretPos(out caretLine, out caretColumn);\n vsTextView.GetBuffer(out var textLines);\n // Handle virtual space (e.g, see Dev10 778675)\n textLines.GetLengthOfLine(caretLine, out var lineLength);\n if (caretColumn > lineLength)\n {\n caretColumn = lineLength;\n }\n }\n\n private void AddReferencesAndImports(\n IVsExpansionSession pSession,\n int position,\n CancellationToken cancellationToken)\n {\n if (!TryGetSnippetNode(pSession, out var snippetNode))\n {\n return;\n }\n\n var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();\n if (documentWithImports == null)\n {\n return;\n }\n\n var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);\n var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions();\n\n documentWithImports = AddImports(documentWithImports, documentOptions, position, snippetNode, allowInHiddenRegions, cancellationToken);\n AddReferences(documentWithImports.Project, snippetNode);\n }\n\n private void AddReferences(Project originalProject, XElement snippetNode)\n {\n var referencesNode = snippetNode.Element(XName.Get(\"References\", snippetNode.Name.NamespaceName));\n if (referencesNode == null)\n {\n return;\n }\n\n var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display));\n var workspace = originalProject.Solution.Workspace;\n var projectId = originalProject.Id;\n\n var assemblyXmlName = XName.Get(\"Assembly\", snippetNode.Name.NamespaceName);\n var failedReferenceAdditions = new List();\n\n foreach (var reference in referencesNode.Elements(XName.Get(\"Reference\", snippetNode.Name.NamespaceName)))\n {\n // Note: URL references are not supported\n var assemblyElement = reference.Element(assemblyXmlName);\n\n var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null;\n\n if (RoslynString.IsNullOrEmpty(assemblyName))\n {\n continue;\n }\n\n if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace ||\n !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName))\n {\n failedReferenceAdditions.Add(assemblyName);\n }\n }\n\n if (failedReferenceAdditions.Any())\n {\n var notificationService = workspace.Services.GetRequiredService();\n notificationService.SendNotification(\n string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine)\n + Environment.NewLine + Environment.NewLine\n + string.Join(Environment.NewLine, failedReferenceAdditions),\n severity: NotificationSeverity.Warning);\n }\n }\n\n protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable memberImportsNamespaces)\n {\n if (document.Project.Solution.Workspace is not VisualStudioWorkspaceImpl vsWorkspace)\n {\n return false;\n }\n\n var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id);\n if (containedDocument == null)\n {\n return false;\n }\n\n if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost)\n {\n foreach (var importClause in memberImportsNamespaces)\n {\n if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK)\n {\n return false;\n }\n }\n }\n\n return true;\n }\n\n protected static bool TryGetSnippetFunctionInfo(\n IXMLDOMNode xmlFunctionNode,\n [NotNullWhen(true)] out string? snippetFunctionName,\n [NotNullWhen(true)] out string? param)\n {\n if (xmlFunctionNode.text.IndexOf('(') == -1 ||\n xmlFunctionNode.text.IndexOf(')') == -1 ||\n xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('('))\n {\n snippetFunctionName = null;\n param = null;\n return false;\n }\n\n snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('('));\n\n var paramStart = xmlFunctionNode.text.IndexOf('(') + 1;\n var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1;\n param = xmlFunctionNode.text.Substring(paramStart, paramLength);\n return true;\n }\n\n internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan)\n {\n var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan);\n var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);\n\n // Bail if a snippet span does not map down to exactly one subject buffer span.\n if (subjectBufferSpanCollection.Count == 1)\n {\n subjectBufferSpan = subjectBufferSpanCollection.Single();\n return true;\n }\n\n subjectBufferSpan = default;\n return false;\n }\n\n internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)\n {\n var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);\n\n // Bail if a snippet span does not map up to exactly one span.\n if (spanCollection.Count == 1)\n {\n span = spanCollection.Single();\n return true;\n }\n\n span = default;\n return false;\n }\n\n private sealed class State\n {\n /// \n /// The current expansion session.\n /// \n public IVsExpansionSession? _expansionSession;\n\n /// \n /// The symbol name of the method that we have invoked insert full method call on; or \n /// if there is no active snippet session or the active session is a regular snippets session.\n /// \n public string? _methodNameForInsertFullMethodCall;\n\n /// \n /// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help\n /// has not yet provided a symbol to show.\n /// \n public IMethodSymbol? _method;\n\n /// \n /// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for\n /// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a\n /// parameter with this name. This map is cleared at the final end of an argument provider snippet session.\n /// \n public ImmutableDictionary _arguments = ImmutableDictionary.Create();\n\n /// \n /// if the current snippet session is a Full Method Call snippet session; otherwise,\n /// if there is no current snippet session or if the current snippet session is a normal snippet.\n /// \n public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null;\n\n public void Clear()\n {\n _expansionSession = null;\n _methodNameForInsertFullMethodCall = null;\n _method = null;\n _arguments = _arguments.Clear();\n }\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1159,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.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.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.UseExpressionBody;\nusing Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;\nusing Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody\n{\n public class UseExpressionBodyForLocalFunctionsRefactoringTests : AbstractCSharpCodeActionTest\n {\n protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)\n => new UseExpressionBodyCodeRefactoringProvider();\n\n private OptionsCollection UseExpressionBody =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement);\n\n private OptionsCollection UseExpressionBodyDisabledDiagnostic =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None));\n\n private OptionsCollection UseBlockBody =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement);\n\n private OptionsCollection UseBlockBodyDisabledDiagnostic =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None));\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()\n {\n await TestMissingAsync(\n@\"class C\n{\n void Goo()\n {\n void Bar() \n {\n [||]Test();\n }\n }\n}\", parameters: new TestParameters(options: UseExpressionBody));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() \n {\n [||]Test();\n }\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar() => Test();\n }\n}\", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() \n {\n [||]Test();\n }\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar() => Test();\n }\n}\", parameters: new TestParameters(options: UseBlockBody));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()\n {\n await TestMissingAsync(\n@\"class C\n{\n void Goo()\n {\n void Bar() => [||]Test();\n }\n}\", parameters: new TestParameters(options: UseBlockBody));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() => [||]Test();\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar()\n {\n Test();\n }\n }\n}\", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() => [||]Test();\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar()\n {\n Test();\n }\n }\n}\", parameters: new TestParameters(options: UseExpressionBody));\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.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.CodeStyle;\nusing Microsoft.CodeAnalysis.CSharp.UseExpressionBody;\nusing Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;\nusing Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;\nusing Microsoft.CodeAnalysis.Test.Utilities;\nusing Xunit;\n\nnamespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody\n{\n public class UseExpressionBodyForLocalFunctionsRefactoringTests : AbstractCSharpCodeActionTest\n {\n protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)\n => new UseExpressionBodyCodeRefactoringProvider();\n\n private OptionsCollection UseExpressionBody =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement);\n\n private OptionsCollection UseExpressionBodyDisabledDiagnostic =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None));\n\n private OptionsCollection UseBlockBody =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement);\n\n private OptionsCollection UseBlockBodyDisabledDiagnostic =>\n Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None));\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()\n {\n await TestMissingAsync(\n@\"class C\n{\n void Goo()\n {\n void Bar() \n {\n [||]Test();\n }\n }\n}\", parameters: new TestParameters(options: UseExpressionBody));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() \n {\n [||]Test();\n }\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar() => Test();\n }\n}\", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() \n {\n [||]Test();\n }\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar() => Test();\n }\n}\", parameters: new TestParameters(options: UseBlockBody));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()\n {\n await TestMissingAsync(\n@\"class C\n{\n void Goo()\n {\n void Bar() => [||]Test();\n }\n}\", parameters: new TestParameters(options: UseBlockBody));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() => [||]Test();\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar()\n {\n Test();\n }\n }\n}\", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic));\n }\n\n [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]\n public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()\n {\n await TestInRegularAndScript1Async(\n@\"class C\n{\n void Goo()\n {\n void Bar() => [||]Test();\n }\n}\",\n@\"class C\n{\n void Goo()\n {\n void Bar()\n {\n Test();\n }\n }\n}\", parameters: new TestParameters(options: UseExpressionBody));\n }\n }\n}\n"},"label":{"kind":"number","value":-1,"string":"-1"}}},{"rowIdx":1160,"cells":{"repo_name":{"kind":"string","value":"dotnet/roslyn"},"pr_number":{"kind":"number","value":56357,"string":"56,357"},"pr_title":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader"},"pr_description":{"kind":"string","value":"Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"author":{"kind":"string","value":"genlu"},"date_created":{"kind":"timestamp","value":"2021-09-13T20:58:22Z","string":"2021-09-13T20:58:22Z"},"date_merged":{"kind":"timestamp","value":"2021-09-21T19:08:56Z","string":"2021-09-21T19:08:56Z"},"previous_commit":{"kind":"string","value":"388f27cab65b3dddb07cc04be839ad603cf0c713"},"pr_commit":{"kind":"string","value":"aa7161be66427e809276fb5f2f91cfe8335eadff"},"query":{"kind":"string","value":"Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default.\r\n\r\nIn Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself.\r\nSee [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation.\r\n\r\nFix #56254"},"filepath":{"kind":"string","value":"./src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.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.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Diagnostics;\nusing Microsoft.CodeAnalysis.Host;\nusing Microsoft.CodeAnalysis.Serialization;\nusing Roslyn.Utilities;\n\nnamespace Microsoft.CodeAnalysis\n{\n internal partial class ProjectState\n {\n private readonly ProjectInfo _projectInfo;\n private readonly HostLanguageServices _languageServices;\n private readonly SolutionServices _solutionServices;\n\n /// \n /// The documents in this project. They are sorted by to provide a stable sort for\n /// .\n /// \n public readonly TextDocumentStates DocumentStates;\n\n /// \n /// The additional documents in this project. They are sorted by to provide a stable sort for\n /// .\n /// \n public readonly TextDocumentStates AdditionalDocumentStates;\n\n /// \n /// The analyzer config documents in this project. They are sorted by to provide a stable sort for\n /// .\n /// \n public readonly TextDocumentStates AnalyzerConfigDocumentStates;\n\n private readonly AsyncLazy _lazyLatestDocumentVersion;\n private readonly AsyncLazy _lazyLatestDocumentTopLevelChangeVersion;\n\n // Checksums for this solution state\n private readonly ValueSource _lazyChecksums;\n\n /// \n /// The to be used for analyzer options for specific trees.\n /// \n private readonly ValueSource _lazyAnalyzerConfigSet;\n\n private AnalyzerOptions? _lazyAnalyzerOptions;\n\n /// \n /// Backing field for ; this is a default ImmutableArray if it hasn't been computed yet.\n /// \n private ImmutableArray _lazySourceGenerators;\n\n private ProjectState(\n ProjectInfo projectInfo,\n HostLanguageServices languageServices,\n SolutionServices solutionServices,\n TextDocumentStates documentStates,\n TextDocumentStates additionalDocumentStates,\n TextDocumentStates analyzerConfigDocumentStates,\n AsyncLazy lazyLatestDocumentVersion,\n AsyncLazy lazyLatestDocumentTopLevelChangeVersion,\n ValueSource lazyAnalyzerConfigSet)\n {\n _solutionServices = solutionServices;\n _languageServices = languageServices;\n DocumentStates = documentStates;\n AdditionalDocumentStates = additionalDocumentStates;\n AnalyzerConfigDocumentStates = analyzerConfigDocumentStates;\n _lazyLatestDocumentVersion = lazyLatestDocumentVersion;\n _lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion;\n _lazyAnalyzerConfigSet = lazyAnalyzerConfigSet;\n\n // ownership of information on document has moved to project state. clear out documentInfo the state is\n // holding on. otherwise, these information will be held onto unnecessarily by projectInfo even after\n // the info has changed by DocumentState.\n _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfo);\n\n _lazyChecksums = new AsyncLazy(ComputeChecksumsAsync, cacheResult: true);\n }\n\n public ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices)\n {\n Contract.ThrowIfNull(projectInfo);\n Contract.ThrowIfNull(languageServices);\n Contract.ThrowIfNull(solutionServices);\n\n _languageServices = languageServices;\n _solutionServices = solutionServices;\n\n var projectInfoFixed = FixProjectInfo(projectInfo);\n\n // We need to compute our AnalyerConfigDocumentStates first, since we use those to produce our DocumentStates\n AnalyzerConfigDocumentStates = new TextDocumentStates(projectInfoFixed.AnalyzerConfigDocuments, info => new AnalyzerConfigDocumentState(info, solutionServices));\n\n _lazyAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(AnalyzerConfigDocumentStates);\n\n // Add analyzer config information to the compilation options\n if (projectInfoFixed.CompilationOptions != null)\n {\n projectInfoFixed = projectInfoFixed.WithCompilationOptions(\n projectInfoFixed.CompilationOptions.WithSyntaxTreeOptionsProvider(\n new WorkspaceSyntaxTreeOptionsProvider(_lazyAnalyzerConfigSet)));\n }\n\n var parseOptions = projectInfoFixed.ParseOptions;\n\n DocumentStates = new TextDocumentStates(projectInfoFixed.Documents, info => CreateDocument(info, parseOptions));\n AdditionalDocumentStates = new TextDocumentStates(projectInfoFixed.AdditionalDocuments, info => new AdditionalDocumentState(info, solutionServices));\n\n _lazyLatestDocumentVersion = new AsyncLazy(c => ComputeLatestDocumentVersionAsync(DocumentStates, AdditionalDocumentStates, c), cacheResult: true);\n _lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy(c => ComputeLatestDocumentTopLevelChangeVersionAsync(DocumentStates, AdditionalDocumentStates, c), cacheResult: true);\n\n // ownership of information on document has moved to project state. clear out documentInfo the state is\n // holding on. otherwise, these information will be held onto unnecessarily by projectInfo even after\n // the info has changed by DocumentState.\n // we hold onto the info so that we don't need to duplicate all information info already has in the state\n _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfoFixed);\n\n _lazyChecksums = new AsyncLazy(ComputeChecksumsAsync, cacheResult: true);\n }\n\n private static ProjectInfo ClearAllDocumentsFromProjectInfo(ProjectInfo projectInfo)\n {\n return projectInfo\n .WithDocuments(ImmutableArray.Empty)\n .WithAdditionalDocuments(ImmutableArray.Empty)\n .WithAnalyzerConfigDocuments(ImmutableArray.Empty);\n }\n\n private ProjectInfo FixProjectInfo(ProjectInfo projectInfo)\n {\n if (projectInfo.CompilationOptions == null)\n {\n var compilationFactory = _languageServices.GetService();\n if (compilationFactory != null)\n {\n projectInfo = projectInfo.WithCompilationOptions(compilationFactory.GetDefaultCompilationOptions());\n }\n }\n\n if (projectInfo.ParseOptions == null)\n {\n var syntaxTreeFactory = _languageServices.GetService();\n if (syntaxTreeFactory != null)\n {\n projectInfo = projectInfo.WithParseOptions(syntaxTreeFactory.GetDefaultParseOptions());\n }\n }\n\n return projectInfo;\n }\n\n private static async Task ComputeLatestDocumentVersionAsync(TextDocumentStates documentStates, TextDocumentStates additionalDocumentStates, CancellationToken cancellationToken)\n {\n // this may produce a version that is out of sync with the actual Document versions.\n var latestVersion = VersionStamp.Default;\n foreach (var (_, state) in documentStates.States)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n if (!state.IsGenerated)\n {\n var version = await state.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);\n latestVersion = version.GetNewerVersion(latestVersion);\n }\n }\n\n foreach (var (_, state) in additionalDocumentStates.States)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var version = await state.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);\n latestVersion = version.GetNewerVersion(latestVersion);\n }\n\n return latestVersion;\n }\n\n private AsyncLazy CreateLazyLatestDocumentTopLevelChangeVersion(\n TextDocumentState newDocument,\n TextDocumentStates newDocumentStates,\n TextDocumentStates newAdditionalDocumentStates)\n {\n if (_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var oldVersion))\n {\n return new AsyncLazy(c => ComputeTopLevelChangeTextVersionAsync(oldVersion, newDocument, c), cacheResult: true);\n }\n else\n {\n return new AsyncLazy(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true);\n }\n }\n\n private static async Task ComputeTopLevelChangeTextVersionAsync(VersionStamp oldVersion, TextDocumentState newDocument, CancellationToken cancellationToken)\n {\n var newVersion = await newDocument.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false);\n return newVersion.GetNewerVersion(oldVersion);\n }\n\n private static async Task ComputeLatestDocumentTopLevelChangeVersionAsync(TextDocumentStates documentStates, TextDocumentStates additionalDocumentStates, CancellationToken cancellationToken)\n {\n // this may produce a version that is out of sync with the actual Document versions.\n var latestVersion = VersionStamp.Default;\n foreach (var (_, state) in documentStates.States)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var version = await state.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false);\n latestVersion = version.GetNewerVersion(latestVersion);\n }\n\n foreach (var (_, state) in additionalDocumentStates.States)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n var version = await state.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false);\n latestVersion = version.GetNewerVersion(latestVersion);\n }\n\n return latestVersion;\n }\n\n internal DocumentState CreateDocument(DocumentInfo documentInfo, ParseOptions? parseOptions)\n {\n var doc = new DocumentState(documentInfo, parseOptions, _languageServices, _solutionServices);\n\n if (doc.SourceCodeKind != documentInfo.SourceCodeKind)\n {\n doc = doc.UpdateSourceCodeKind(documentInfo.SourceCodeKind);\n }\n\n return doc;\n }\n\n public AnalyzerOptions AnalyzerOptions\n => _lazyAnalyzerOptions ??= new AnalyzerOptions(\n additionalFiles: AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText),\n optionsProvider: new WorkspaceAnalyzerConfigOptionsProvider(this));\n\n public async Task> GetAnalyzerOptionsForPathAsync(\n string path,\n CancellationToken cancellationToken)\n {\n var configSet = await _lazyAnalyzerConfigSet.GetValueAsync(cancellationToken).ConfigureAwait(false);\n return configSet.GetOptionsForSourcePath(path).AnalyzerOptions;\n }\n\n public AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions()\n {\n // We need to find the analyzer config options at the root of the project.\n // Currently, there is no compiler API to query analyzer config options for a directory in a language agnostic fashion.\n // So, we use a dummy language-specific file name appended to the project directory to query analyzer config options.\n\n var projectDirectory = PathUtilities.GetDirectoryName(_projectInfo.FilePath);\n if (!PathUtilities.IsAbsolute(projectDirectory))\n {\n return null;\n }\n\n var fileName = Guid.NewGuid().ToString();\n string sourceFilePath;\n switch (_projectInfo.Language)\n {\n case LanguageNames.CSharp:\n // Suppression should be removed or addressed https://github.com/dotnet/roslyn/issues/41636\n sourceFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(projectDirectory, $\"{fileName}.cs\")!;\n break;\n\n case LanguageNames.VisualBasic:\n // Suppression should be removed or addressed https://github.com/dotnet/roslyn/issues/41636\n sourceFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(projectDirectory, $\"{fileName}.vb\")!;\n break;\n\n default:\n return null;\n }\n\n return _lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(sourceFilePath);\n }\n\n internal sealed class WorkspaceAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider\n {\n private readonly ProjectState _projectState;\n\n public WorkspaceAnalyzerConfigOptionsProvider(ProjectState projectState)\n => _projectState = projectState;\n\n public override AnalyzerConfigOptions GlobalOptions\n => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(string.Empty));\n\n public override AnalyzerConfigOptions GetOptions(SyntaxTree tree)\n => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(tree.FilePath));\n\n public override AnalyzerConfigOptions GetOptions(AdditionalText textFile)\n {\n // TODO: correctly find the file path, since it looks like we give this the document's .Name under the covers if we don't have one\n return new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(textFile.Path));\n }\n\n public AnalyzerConfigOptions GetOptionsForSourcePath(string path)\n => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(path));\n\n private sealed class WorkspaceAnalyzerConfigOptions : AnalyzerConfigOptions\n {\n private readonly ImmutableDictionary _backing;\n\n public WorkspaceAnalyzerConfigOptions(AnalyzerConfigOptionsResult analyzerConfigOptions)\n => _backing = analyzerConfigOptions.AnalyzerOptions;\n\n public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) => _backing.TryGetValue(key, out value);\n }\n }\n\n private sealed class WorkspaceSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider\n {\n private readonly ValueSource _lazyAnalyzerConfigSet;\n\n public WorkspaceSyntaxTreeOptionsProvider(ValueSource