repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); EditSession = new EditSession(this, nonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(nonRemappableRegions: null, inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>? nonRemappableRegions, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, nonRemappableRegions ?? EditSession.NonRemappableRegions, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var newNonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in pendingUpdate.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (newNonRemappableRegions.IsEmpty) newNonRemappableRegions = null; // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in pendingUpdate.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(pendingUpdate.Solution); // Restart edit session with no active statements (switching to run mode). RestartEditSession(newNonRemappableRegions, inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), EditSession.BaseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, EditSession.Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); EditSession = new EditSession(this, nonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateChanged(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(nonRemappableRegions: null, inBreakState, out documentsToReanalyze); internal void RestartEditSession(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>? nonRemappableRegions, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, nonRemappableRegions ?? EditSession.NonRemappableRegions, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var newNonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in pendingUpdate.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (newNonRemappableRegions.IsEmpty) newNonRemappableRegions = null; // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in pendingUpdate.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(pendingUpdate.Solution); // Restart edit session with no active statements (switching to run mode). RestartEditSession(newNonRemappableRegions, inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), EditSession.BaseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, EditSession.Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new EditAndContinueWorkspaceService(); } internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; internal EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateEntered(out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether the updates made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply /// them on "continue". /// </summary> /// <returns> /// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors /// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether /// the update is valid or not. /// </returns> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new EditAndContinueWorkspaceService(); } internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; internal EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateChanged(DebuggingSessionId sessionId, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateChanged(inBreakState, out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether the updates made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply /// them on "continue". /// </summary> /// <returns> /// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors /// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether /// the update is valid or not. /// </returns> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/EditAndContinue/IEditAndContinueWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IEditAndContinueWorkspaceService : IWorkspaceService { ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken); ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken); ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken); void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze); void DiscardSolutionUpdate(DebuggingSessionId sessionId); void OnSourceFileUpdated(Document document); ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken); void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze); void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze); ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IEditAndContinueWorkspaceService : IWorkspaceService { ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken); ValueTask<bool> HasChangesAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken); ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken); void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze); void DiscardSolutionUpdate(DebuggingSessionId sessionId); void OnSourceFileUpdated(Document document); ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken); void BreakStateChanged(DebuggingSessionId sessionId, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze); void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze); ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken); } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/EditAndContinue/Remote/IRemoteEditAndContinueService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IRemoteEditAndContinueService { internal interface ICallback { ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken); } ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken); ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> BreakStateEnteredAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IRemoteEditAndContinueService { internal interface ICallback { ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken); } ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken); ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> BreakStateChangedAsync(DebuggingSessionId sessionId, bool isBreakState, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken); } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateEnteredAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateEntered(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateEnteredAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/Remote/ServiceHub/Services/EditAndContinue/RemoteEditAndContinueService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteEditAndContinueService : BrokeredServiceBase, IRemoteEditAndContinueService { internal sealed class Factory : FactoryBase<IRemoteEditAndContinueService, IRemoteEditAndContinueService.ICallback> { protected override IRemoteEditAndContinueService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) => new RemoteEditAndContinueService(arguments, callback); } private sealed class ManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService { private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public ManagedEditAndContinueDebuggerService(RemoteCallback<IRemoteEditAndContinueService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } Task<ImmutableArray<ManagedActiveStatementDebugInfo>> IManagedEditAndContinueDebuggerService.GetActiveStatementsAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetActiveStatementsAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task<ManagedEditAndContinueAvailability> IManagedEditAndContinueDebuggerService.GetAvailabilityAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetAvailabilityAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); Task<ImmutableArray<string>> IManagedEditAndContinueDebuggerService.GetCapabilitiesAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetCapabilitiesAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task IManagedEditAndContinueDebuggerService.PrepareModuleForUpdateAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.PrepareModuleForUpdateAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); } private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; public RemoteEditAndContinueService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) : base(arguments) { _callback = callback; } private IEditAndContinueWorkspaceService GetService() => GetWorkspace().Services.GetRequiredService<IEditAndContinueWorkspaceService>(); private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServiceCallbackId callbackId) => new((documentId, filePath, cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetSpansAsync(callbackId, documentId, filePath, cancellationToken), cancellationToken)); /// <summary> /// Remote API. /// </summary> public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId); var sessionId = await GetService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false); return sessionId; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> BreakStateEnteredAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().BreakStateEntered(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().EndDebuggingSession(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var diagnostics = await GetService().GetDocumentDiagnosticsAsync(document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return diagnostics.SelectAsArray(diagnostic => DiagnosticData.Create(diagnostic, document)); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().HasChangesAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), sourceFilePath, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var service = GetService(); var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); try { var results = await service.EmitSolutionUpdateAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return results.Dehydrate(solution); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError); var diagnostic = Diagnostic.Create(descriptor, Location.None, new[] { e.Message }); var diagnostics = ImmutableArray.Create(DiagnosticData.Create(diagnostic, solution.Options)); return new EmitSolutionUpdateResults.Data(updates, diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty); } }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().CommitSolutionUpdate(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().DiscardSolutionUpdate(sessionId); return default; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetBaseActiveStatementSpansAsync(sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); return await GetService().GetAdjustedActiveStatementSpansAsync(sessionId, document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().IsActiveStatementInExceptionRegionAsync(sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetCurrentActiveStatementPositionAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); // TODO: Non-C#/VB documents are not currently serialized to remote workspace. // https://github.com/dotnet/roslyn/issues/47341 var document = solution.GetDocument(documentId); if (document != null) { GetService().OnSourceFileUpdated(document); } }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteEditAndContinueService : BrokeredServiceBase, IRemoteEditAndContinueService { internal sealed class Factory : FactoryBase<IRemoteEditAndContinueService, IRemoteEditAndContinueService.ICallback> { protected override IRemoteEditAndContinueService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) => new RemoteEditAndContinueService(arguments, callback); } private sealed class ManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService { private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public ManagedEditAndContinueDebuggerService(RemoteCallback<IRemoteEditAndContinueService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } Task<ImmutableArray<ManagedActiveStatementDebugInfo>> IManagedEditAndContinueDebuggerService.GetActiveStatementsAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetActiveStatementsAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task<ManagedEditAndContinueAvailability> IManagedEditAndContinueDebuggerService.GetAvailabilityAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetAvailabilityAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); Task<ImmutableArray<string>> IManagedEditAndContinueDebuggerService.GetCapabilitiesAsync(CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetCapabilitiesAsync(_callbackId, cancellationToken), cancellationToken).AsTask(); Task IManagedEditAndContinueDebuggerService.PrepareModuleForUpdateAsync(Guid moduleVersionId, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.PrepareModuleForUpdateAsync(_callbackId, moduleVersionId, cancellationToken), cancellationToken).AsTask(); } private readonly RemoteCallback<IRemoteEditAndContinueService.ICallback> _callback; public RemoteEditAndContinueService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteEditAndContinueService.ICallback> callback) : base(arguments) { _callback = callback; } private IEditAndContinueWorkspaceService GetService() => GetWorkspace().Services.GetRequiredService<IEditAndContinueWorkspaceService>(); private ActiveStatementSpanProvider CreateActiveStatementSpanProvider(RemoteServiceCallbackId callbackId) => new((documentId, filePath, cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.GetSpansAsync(callbackId, documentId, filePath, cancellationToken), cancellationToken)); /// <summary> /// Remote API. /// </summary> public ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var debuggerService = new ManagedEditAndContinueDebuggerService(_callback, callbackId); var sessionId = await GetService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false); return sessionId; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> BreakStateChangedAsync(DebuggingSessionId sessionId, bool inBreakState, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().BreakStateChanged(sessionId, inBreakState, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().EndDebuggingSession(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var diagnostics = await GetService().GetDocumentDiagnosticsAsync(document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return diagnostics.SelectAsArray(diagnostic => DiagnosticData.Create(diagnostic, document)); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().HasChangesAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), sourceFilePath, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var service = GetService(); var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); try { var results = await service.EmitSolutionUpdateAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); return results.Dehydrate(solution); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError); var diagnostic = Diagnostic.Create(descriptor, Location.None, new[] { e.Message }); var diagnostics = ImmutableArray.Create(DiagnosticData.Create(diagnostic, solution.Options)); return new EmitSolutionUpdateResults.Data(updates, diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty); } }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().CommitSolutionUpdate(sessionId, out var documentsToReanalyze); return new ValueTask<ImmutableArray<DocumentId>>(documentsToReanalyze); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => { GetService().DiscardSolutionUpdate(sessionId); return default; }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetBaseActiveStatementSpansAsync(sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetRequiredTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); return await GetService().GetAdjustedActiveStatementSpansAsync(sessionId, document, CreateActiveStatementSpanProvider(callbackId), cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().IsActiveStatementInExceptionRegionAsync(sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); return await GetService().GetCurrentActiveStatementPositionAsync(sessionId, solution, CreateActiveStatementSpanProvider(callbackId), instructionId, cancellationToken).ConfigureAwait(false); }, cancellationToken); } /// <summary> /// Remote API. /// </summary> public ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); // TODO: Non-C#/VB documents are not currently serialized to remote workspace. // https://github.com/dotnet/roslyn/issues/47341 var document = solution.GetDocument(documentId); if (document != null) { GetService().OnSourceFileUpdated(document); } }, cancellationToken); } } }
1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/EditorConfigSettings/Common/IEnumSettingViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModel { string[] GetValueDescriptions(); int GetValueIndex(); void ChangeProperty(string v); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModel { string[] GetValueDescriptions(); int GetValueIndex(); void ChangeProperty(string v); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DescendingKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DescendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DescendingKeywordRecommender() : base(SyntaxKind.DescendingKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.TargetToken.IsOrderByDirectionContext(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DescendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DescendingKeywordRecommender() : base(SyntaxKind.DescendingKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.TargetToken.IsOrderByDirectionContext(); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/Implementation/Snippets/SnippetFunctions/AbstractSnippetFunctionSimpleTypeName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions { internal abstract class AbstractSnippetFunctionSimpleTypeName : AbstractSnippetFunction { private readonly string _fieldName; private readonly string _fullyQualifiedName; public AbstractSnippetFunctionSimpleTypeName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName) : base(snippetExpansionClient, subjectBuffer) { _fieldName = fieldName; _fullyQualifiedName = fullyQualifiedName; } protected abstract bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName); protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue) { value = _fullyQualifiedName; hasDefaultValue = 1; if (!TryGetDocument(out var document)) { return VSConstants.E_FAIL; } if (!TryGetDocumentWithFullyQualifiedTypeName(document, out var updatedTextSpan, out var documentWithFullyQualifiedTypeName)) { return VSConstants.E_FAIL; } if (!TryGetSimplifiedTypeName(documentWithFullyQualifiedTypeName, updatedTextSpan, cancellationToken, out var simplifiedName)) { return VSConstants.E_FAIL; } value = simplifiedName; hasDefaultValue = 1; return VSConstants.S_OK; } private bool TryGetDocumentWithFullyQualifiedTypeName(Document document, out TextSpan updatedTextSpan, out Document documentWithFullyQualifiedTypeName) { documentWithFullyQualifiedTypeName = null; updatedTextSpan = default; var surfaceBufferFieldSpan = new VsTextSpan[1]; if (snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName, surfaceBufferFieldSpan) != VSConstants.S_OK) { return false; } if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan)) { return false; } var originalTextSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length); updatedTextSpan = new TextSpan(subjectBufferFieldSpan.Start, _fullyQualifiedName.Length); var textChange = new TextChange(originalTextSpan, _fullyQualifiedName); var newText = document.GetTextSynchronously(CancellationToken.None).WithChanges(textChange); documentWithFullyQualifiedTypeName = document.WithText(newText); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions { internal abstract class AbstractSnippetFunctionSimpleTypeName : AbstractSnippetFunction { private readonly string _fieldName; private readonly string _fullyQualifiedName; public AbstractSnippetFunctionSimpleTypeName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName) : base(snippetExpansionClient, subjectBuffer) { _fieldName = fieldName; _fullyQualifiedName = fullyQualifiedName; } protected abstract bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName); protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue) { value = _fullyQualifiedName; hasDefaultValue = 1; if (!TryGetDocument(out var document)) { return VSConstants.E_FAIL; } if (!TryGetDocumentWithFullyQualifiedTypeName(document, out var updatedTextSpan, out var documentWithFullyQualifiedTypeName)) { return VSConstants.E_FAIL; } if (!TryGetSimplifiedTypeName(documentWithFullyQualifiedTypeName, updatedTextSpan, cancellationToken, out var simplifiedName)) { return VSConstants.E_FAIL; } value = simplifiedName; hasDefaultValue = 1; return VSConstants.S_OK; } private bool TryGetDocumentWithFullyQualifiedTypeName(Document document, out TextSpan updatedTextSpan, out Document documentWithFullyQualifiedTypeName) { documentWithFullyQualifiedTypeName = null; updatedTextSpan = default; var surfaceBufferFieldSpan = new VsTextSpan[1]; if (snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName, surfaceBufferFieldSpan) != VSConstants.S_OK) { return false; } if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan)) { return false; } var originalTextSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length); updatedTextSpan = new TextSpan(subjectBufferFieldSpan.Start, _fullyQualifiedName.Length); var textChange = new TextChange(originalTextSpan, _fullyQualifiedName); var newText = document.GetTextSynchronously(CancellationToken.None).WithChanges(textChange); documentWithFullyQualifiedTypeName = document.WithText(newText); return true; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Scripting/CoreTest/ScriptOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Scripting.Test { public class ScriptOptionsTests : TestBase { [Fact] public void AddReferences() { var options = ScriptOptions.Default. AddReferences(typeof(int).GetTypeInfo().Assembly). AddReferences(typeof(int).GetTypeInfo().Assembly). AddReferences(MetadataReference.CreateFromAssemblyInternal(typeof(int).GetTypeInfo().Assembly)). AddReferences("System.Linq"). AddReferences("System.Linq"); Assert.Equal(GacFileResolver.IsAvailable ? 5 : 30, options.MetadataReferences.Length); } [Fact] public void AddReferences_Errors() { var moduleRef = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference(); var options = ScriptOptions.Default.WithReferences(ImmutableArray<MetadataReference>.Empty); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((MetadataReference[])null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences(new MetadataReference[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((IEnumerable<MetadataReference>)null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences((IEnumerable<MetadataReference>)new MetadataReference[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((Assembly[])null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences(new Assembly[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((IEnumerable<Assembly>)null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences((IEnumerable<Assembly>)new Assembly[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((string[])null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences(new string[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences((IEnumerable<string>)new string[] { null })); } [Fact] public void WithReferences() { var empty = ScriptOptions.Default.WithReferences(ImmutableArray<MetadataReference>.Empty); var options = empty.WithReferences("System.Linq", "system.linq"); Assert.Equal(2, options.MetadataReferences.Length); options = empty.WithReferences(typeof(int).GetTypeInfo().Assembly, typeof(int).GetTypeInfo().Assembly); Assert.Equal(2, options.MetadataReferences.Length); var assemblyRef = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.CSMethods).GetReference(); options = empty.WithReferences(assemblyRef, assemblyRef); Assert.Equal(2, options.MetadataReferences.Length); } [Fact] public void WithReferences_Errors() { var moduleRef = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference(); var options = ScriptOptions.Default.WithReferences(ImmutableArray<MetadataReference>.Empty); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((MetadataReference[])null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((IEnumerable<MetadataReference>)null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences(default(ImmutableArray<MetadataReference>))); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(new MetadataReference[] { null })); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(ImmutableArray.Create((MetadataReference)null))); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((Assembly[])null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((IEnumerable<Assembly>)null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences(default(ImmutableArray<Assembly>))); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(new Assembly[] { null })); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(ImmutableArray.Create((Assembly)null))); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((string[])null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences(default(ImmutableArray<string>))); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(new string[] { null })); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(ImmutableArray.Create((string)null))); } [Fact] public void AddNamespaces() { // we only check if the specified name is a valid CLR namespace name, it might not be a valid C#/VB namespace name: var options = ScriptOptions.Default. AddImports(""). AddImports("blah."). AddImports("b\0lah"). AddImports(".blah"). AddImports("b\0lah"). AddImports(".blah"); AssertEx.Equal(new[] { "", "blah.", "b\0lah", ".blah", "b\0lah", ".blah" }, options.Imports); } [Fact] public void AddImports_Errors() { var options = ScriptOptions.Default; Assert.Throws<ArgumentNullException>("imports", () => options.AddImports((string[])null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.AddImports(new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.AddImports((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.AddImports((IEnumerable<string>)new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.AddImports(default(ImmutableArray<string>))); Assert.Throws<ArgumentNullException>("imports[0]", () => options.AddImports(ImmutableArray.Create((string)null))); // we only check if the specified name is a valid CLR namespace name, it might not be a valid C#/VB namespace name: options.AddImports(""); options.AddImports("blah."); options.AddImports("b\0lah"); options.AddImports(".blah"); } [Fact] public void WithImports_Errors() { var options = ScriptOptions.Default; Assert.Throws<ArgumentNullException>("imports", () => options.WithImports((string[])null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.WithImports(new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.WithImports((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.WithImports((IEnumerable<string>)new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.WithImports(default(ImmutableArray<string>))); Assert.Throws<ArgumentNullException>("imports[0]", () => options.WithImports(ImmutableArray.Create((string)null))); // we only check if the specified name is a valid CLR namespace name, it might not be a valid C#/VB namespace name: options.WithImports(""); options.WithImports("blah."); options.WithImports("b\0lah"); options.WithImports(".blah"); } [Fact] public void Imports_Are_AppliedTo_CompilationOption() { var scriptOptions = ScriptOptions.Default.WithImports(new[] { "System", "System.IO" }); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.Imports, compilation.Options.GetImports()); } [Fact] public void WithEmitDebugInformation_SetsEmitDebugInformation() { Assert.True(ScriptOptions.Default.WithEmitDebugInformation(true).EmitDebugInformation); Assert.False(ScriptOptions.Default.WithEmitDebugInformation(false).EmitDebugInformation); Assert.False(ScriptOptions.Default.EmitDebugInformation); } [Fact] public void WithEmitDebugInformation_SameValueTwice_DoesNotCreateNewInstance() { var options = ScriptOptions.Default.WithEmitDebugInformation(true); Assert.Same(options, options.WithEmitDebugInformation(true)); } [Fact] public void WithFileEncoding_SetsWithFileEncoding() { var options = ScriptOptions.Default.WithFileEncoding(Encoding.ASCII); Assert.Equal(Encoding.ASCII, options.FileEncoding); } [Fact] public void WithFileEncoding_SameValueTwice_DoesNotCreateNewInstance() { var options = ScriptOptions.Default.WithFileEncoding(Encoding.ASCII); Assert.Same(options, options.WithFileEncoding(Encoding.ASCII)); } [Fact] public void WithAllowUnsafe_SetsAllowUnsafe() { Assert.True(ScriptOptions.Default.WithAllowUnsafe(true).AllowUnsafe); Assert.False(ScriptOptions.Default.WithAllowUnsafe(false).AllowUnsafe); Assert.True(ScriptOptions.Default.AllowUnsafe); } [Theory] [InlineData(true)] [InlineData(false)] public void WithAllowUnsafe_SameValueTwice_DoesNotCreateNewInstance(bool allowUnsafe) { var options = ScriptOptions.Default.WithAllowUnsafe(allowUnsafe); Assert.Same(options, options.WithAllowUnsafe(allowUnsafe)); } [Theory] [InlineData(true)] [InlineData(false)] public void AllowUnsafe_Is_AppliedTo_CompilationOption(bool allowUnsafe) { var scriptOptions = ScriptOptions.Default.WithAllowUnsafe(allowUnsafe); var compilation = (CSharpCompilation)CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.AllowUnsafe, compilation.Options.AllowUnsafe); } [Fact] public void WithCheckOverflow_SetsCheckOverflow() { Assert.True(ScriptOptions.Default.WithCheckOverflow(true).CheckOverflow); Assert.False(ScriptOptions.Default.WithCheckOverflow(false).CheckOverflow); Assert.False(ScriptOptions.Default.CheckOverflow); } [Theory] [InlineData(true)] [InlineData(false)] public void WithCheckOverflow_SameValueTwice_DoesNotCreateNewInstance(bool checkOverflow) { var options = ScriptOptions.Default.WithCheckOverflow(checkOverflow); Assert.Same(options, options.WithCheckOverflow(checkOverflow)); } [Theory] [InlineData(true)] [InlineData(false)] public void CheckOverflow_Is_AppliedTo_CompilationOption(bool checkOverflow) { var scriptOptions = ScriptOptions.Default.WithCheckOverflow(checkOverflow); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.CheckOverflow, compilation.Options.CheckOverflow); } [Theory] [InlineData(OptimizationLevel.Debug)] [InlineData(OptimizationLevel.Release)] public void WithOptimizationLevel_SetsOptimizationLevel(OptimizationLevel optimizationLevel) { Assert.Equal(ScriptOptions.Default.WithOptimizationLevel(optimizationLevel).OptimizationLevel, optimizationLevel); Assert.Equal(OptimizationLevel.Debug, ScriptOptions.Default.OptimizationLevel); } [Theory] [InlineData(OptimizationLevel.Debug)] [InlineData(OptimizationLevel.Release)] public void WithOptimizationLevel_SameValueTwice_DoesNotCreateNewInstance(OptimizationLevel optimizationLevel) { var options = ScriptOptions.Default.WithOptimizationLevel(optimizationLevel); Assert.Same(options, options.WithOptimizationLevel(optimizationLevel)); } [Theory] [InlineData(OptimizationLevel.Debug)] [InlineData(OptimizationLevel.Release)] public void OptimizationLevel_Is_AppliedTo_CompilationOption(OptimizationLevel optimizationLevel) { var scriptOptions = ScriptOptions.Default.WithOptimizationLevel(optimizationLevel); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.OptimizationLevel, compilation.Options.OptimizationLevel); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void WithWarningLevel_SetsWarningLevel(int warningLevel) { Assert.Equal(ScriptOptions.Default.WithWarningLevel(warningLevel).WarningLevel, warningLevel); Assert.Equal(4, ScriptOptions.Default.WarningLevel); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void WithWarningLevel_SameValueTwice_DoesNotCreateNewInstance(int warningLevel) { var options = ScriptOptions.Default.WithWarningLevel(warningLevel); Assert.Same(options, options.WithWarningLevel(warningLevel)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void WarningLevel_Is_AppliedTo_CompilationOption(int warningLevel) { var scriptOptions = ScriptOptions.Default.WithWarningLevel(warningLevel); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.WarningLevel, compilation.Options.WarningLevel); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Scripting.Test { public class ScriptOptionsTests : TestBase { [Fact] public void AddReferences() { var options = ScriptOptions.Default. AddReferences(typeof(int).GetTypeInfo().Assembly). AddReferences(typeof(int).GetTypeInfo().Assembly). AddReferences(MetadataReference.CreateFromAssemblyInternal(typeof(int).GetTypeInfo().Assembly)). AddReferences("System.Linq"). AddReferences("System.Linq"); Assert.Equal(GacFileResolver.IsAvailable ? 5 : 30, options.MetadataReferences.Length); } [Fact] public void AddReferences_Errors() { var moduleRef = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference(); var options = ScriptOptions.Default.WithReferences(ImmutableArray<MetadataReference>.Empty); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((MetadataReference[])null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences(new MetadataReference[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((IEnumerable<MetadataReference>)null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences((IEnumerable<MetadataReference>)new MetadataReference[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((Assembly[])null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences(new Assembly[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((IEnumerable<Assembly>)null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences((IEnumerable<Assembly>)new Assembly[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((string[])null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences(new string[] { null })); Assert.Throws<ArgumentNullException>("references", () => options.AddReferences((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("references[0]", () => options.AddReferences((IEnumerable<string>)new string[] { null })); } [Fact] public void WithReferences() { var empty = ScriptOptions.Default.WithReferences(ImmutableArray<MetadataReference>.Empty); var options = empty.WithReferences("System.Linq", "system.linq"); Assert.Equal(2, options.MetadataReferences.Length); options = empty.WithReferences(typeof(int).GetTypeInfo().Assembly, typeof(int).GetTypeInfo().Assembly); Assert.Equal(2, options.MetadataReferences.Length); var assemblyRef = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.CSMethods).GetReference(); options = empty.WithReferences(assemblyRef, assemblyRef); Assert.Equal(2, options.MetadataReferences.Length); } [Fact] public void WithReferences_Errors() { var moduleRef = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference(); var options = ScriptOptions.Default.WithReferences(ImmutableArray<MetadataReference>.Empty); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((MetadataReference[])null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((IEnumerable<MetadataReference>)null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences(default(ImmutableArray<MetadataReference>))); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(new MetadataReference[] { null })); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(ImmutableArray.Create((MetadataReference)null))); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((Assembly[])null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((IEnumerable<Assembly>)null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences(default(ImmutableArray<Assembly>))); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(new Assembly[] { null })); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(ImmutableArray.Create((Assembly)null))); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((string[])null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("references", () => options.WithReferences(default(ImmutableArray<string>))); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(new string[] { null })); Assert.Throws<ArgumentNullException>("references[0]", () => options.WithReferences(ImmutableArray.Create((string)null))); } [Fact] public void AddNamespaces() { // we only check if the specified name is a valid CLR namespace name, it might not be a valid C#/VB namespace name: var options = ScriptOptions.Default. AddImports(""). AddImports("blah."). AddImports("b\0lah"). AddImports(".blah"). AddImports("b\0lah"). AddImports(".blah"); AssertEx.Equal(new[] { "", "blah.", "b\0lah", ".blah", "b\0lah", ".blah" }, options.Imports); } [Fact] public void AddImports_Errors() { var options = ScriptOptions.Default; Assert.Throws<ArgumentNullException>("imports", () => options.AddImports((string[])null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.AddImports(new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.AddImports((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.AddImports((IEnumerable<string>)new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.AddImports(default(ImmutableArray<string>))); Assert.Throws<ArgumentNullException>("imports[0]", () => options.AddImports(ImmutableArray.Create((string)null))); // we only check if the specified name is a valid CLR namespace name, it might not be a valid C#/VB namespace name: options.AddImports(""); options.AddImports("blah."); options.AddImports("b\0lah"); options.AddImports(".blah"); } [Fact] public void WithImports_Errors() { var options = ScriptOptions.Default; Assert.Throws<ArgumentNullException>("imports", () => options.WithImports((string[])null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.WithImports(new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.WithImports((IEnumerable<string>)null)); Assert.Throws<ArgumentNullException>("imports[0]", () => options.WithImports((IEnumerable<string>)new string[] { null })); Assert.Throws<ArgumentNullException>("imports", () => options.WithImports(default(ImmutableArray<string>))); Assert.Throws<ArgumentNullException>("imports[0]", () => options.WithImports(ImmutableArray.Create((string)null))); // we only check if the specified name is a valid CLR namespace name, it might not be a valid C#/VB namespace name: options.WithImports(""); options.WithImports("blah."); options.WithImports("b\0lah"); options.WithImports(".blah"); } [Fact] public void Imports_Are_AppliedTo_CompilationOption() { var scriptOptions = ScriptOptions.Default.WithImports(new[] { "System", "System.IO" }); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.Imports, compilation.Options.GetImports()); } [Fact] public void WithEmitDebugInformation_SetsEmitDebugInformation() { Assert.True(ScriptOptions.Default.WithEmitDebugInformation(true).EmitDebugInformation); Assert.False(ScriptOptions.Default.WithEmitDebugInformation(false).EmitDebugInformation); Assert.False(ScriptOptions.Default.EmitDebugInformation); } [Fact] public void WithEmitDebugInformation_SameValueTwice_DoesNotCreateNewInstance() { var options = ScriptOptions.Default.WithEmitDebugInformation(true); Assert.Same(options, options.WithEmitDebugInformation(true)); } [Fact] public void WithFileEncoding_SetsWithFileEncoding() { var options = ScriptOptions.Default.WithFileEncoding(Encoding.ASCII); Assert.Equal(Encoding.ASCII, options.FileEncoding); } [Fact] public void WithFileEncoding_SameValueTwice_DoesNotCreateNewInstance() { var options = ScriptOptions.Default.WithFileEncoding(Encoding.ASCII); Assert.Same(options, options.WithFileEncoding(Encoding.ASCII)); } [Fact] public void WithAllowUnsafe_SetsAllowUnsafe() { Assert.True(ScriptOptions.Default.WithAllowUnsafe(true).AllowUnsafe); Assert.False(ScriptOptions.Default.WithAllowUnsafe(false).AllowUnsafe); Assert.True(ScriptOptions.Default.AllowUnsafe); } [Theory] [InlineData(true)] [InlineData(false)] public void WithAllowUnsafe_SameValueTwice_DoesNotCreateNewInstance(bool allowUnsafe) { var options = ScriptOptions.Default.WithAllowUnsafe(allowUnsafe); Assert.Same(options, options.WithAllowUnsafe(allowUnsafe)); } [Theory] [InlineData(true)] [InlineData(false)] public void AllowUnsafe_Is_AppliedTo_CompilationOption(bool allowUnsafe) { var scriptOptions = ScriptOptions.Default.WithAllowUnsafe(allowUnsafe); var compilation = (CSharpCompilation)CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.AllowUnsafe, compilation.Options.AllowUnsafe); } [Fact] public void WithCheckOverflow_SetsCheckOverflow() { Assert.True(ScriptOptions.Default.WithCheckOverflow(true).CheckOverflow); Assert.False(ScriptOptions.Default.WithCheckOverflow(false).CheckOverflow); Assert.False(ScriptOptions.Default.CheckOverflow); } [Theory] [InlineData(true)] [InlineData(false)] public void WithCheckOverflow_SameValueTwice_DoesNotCreateNewInstance(bool checkOverflow) { var options = ScriptOptions.Default.WithCheckOverflow(checkOverflow); Assert.Same(options, options.WithCheckOverflow(checkOverflow)); } [Theory] [InlineData(true)] [InlineData(false)] public void CheckOverflow_Is_AppliedTo_CompilationOption(bool checkOverflow) { var scriptOptions = ScriptOptions.Default.WithCheckOverflow(checkOverflow); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.CheckOverflow, compilation.Options.CheckOverflow); } [Theory] [InlineData(OptimizationLevel.Debug)] [InlineData(OptimizationLevel.Release)] public void WithOptimizationLevel_SetsOptimizationLevel(OptimizationLevel optimizationLevel) { Assert.Equal(ScriptOptions.Default.WithOptimizationLevel(optimizationLevel).OptimizationLevel, optimizationLevel); Assert.Equal(OptimizationLevel.Debug, ScriptOptions.Default.OptimizationLevel); } [Theory] [InlineData(OptimizationLevel.Debug)] [InlineData(OptimizationLevel.Release)] public void WithOptimizationLevel_SameValueTwice_DoesNotCreateNewInstance(OptimizationLevel optimizationLevel) { var options = ScriptOptions.Default.WithOptimizationLevel(optimizationLevel); Assert.Same(options, options.WithOptimizationLevel(optimizationLevel)); } [Theory] [InlineData(OptimizationLevel.Debug)] [InlineData(OptimizationLevel.Release)] public void OptimizationLevel_Is_AppliedTo_CompilationOption(OptimizationLevel optimizationLevel) { var scriptOptions = ScriptOptions.Default.WithOptimizationLevel(optimizationLevel); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.OptimizationLevel, compilation.Options.OptimizationLevel); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void WithWarningLevel_SetsWarningLevel(int warningLevel) { Assert.Equal(ScriptOptions.Default.WithWarningLevel(warningLevel).WarningLevel, warningLevel); Assert.Equal(4, ScriptOptions.Default.WarningLevel); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void WithWarningLevel_SameValueTwice_DoesNotCreateNewInstance(int warningLevel) { var options = ScriptOptions.Default.WithWarningLevel(warningLevel); Assert.Same(options, options.WithWarningLevel(warningLevel)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void WarningLevel_Is_AppliedTo_CompilationOption(int warningLevel) { var scriptOptions = ScriptOptions.Default.WithWarningLevel(warningLevel); var compilation = CSharpScript.Create(string.Empty, scriptOptions).GetCompilation(); Assert.Equal(scriptOptions.WarningLevel, compilation.Options.WarningLevel); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSCodeModelFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { [Export(typeof(ICodeModelFactory))] internal partial class CPSCodeModelFactory : ICodeModelFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CPSCodeModelFactory() { } public EnvDTE.CodeModel GetCodeModel(IWorkspaceProjectContext context, EnvDTE.Project project) => ((CPSProject)context).GetCodeModel(project); public EnvDTE.FileCodeModel GetFileCodeModel(IWorkspaceProjectContext context, EnvDTE.ProjectItem item) => ((CPSProject)context).GetFileCodeModel(item); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { [Export(typeof(ICodeModelFactory))] internal partial class CPSCodeModelFactory : ICodeModelFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CPSCodeModelFactory() { } public EnvDTE.CodeModel GetCodeModel(IWorkspaceProjectContext context, EnvDTE.Project project) => ((CPSProject)context).GetCodeModel(project); public EnvDTE.FileCodeModel GetFileCodeModel(IWorkspaceProjectContext context, EnvDTE.ProjectItem item) => ((CPSProject)context).GetFileCodeModel(item); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/ConvertForToForEach/AbstractConvertForToForEachCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertForToForEach { internal abstract class AbstractConvertForToForEachCodeRefactoringProvider< TStatementSyntax, TForStatementSyntax, TExpressionSyntax, TMemberAccessExpressionSyntax, TTypeNode, TVariableDeclaratorSyntax> : CodeRefactoringProvider where TStatementSyntax : SyntaxNode where TForStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TMemberAccessExpressionSyntax : SyntaxNode where TTypeNode : SyntaxNode where TVariableDeclaratorSyntax : SyntaxNode { protected abstract string GetTitle(); protected abstract SyntaxList<TStatementSyntax> GetBodyStatements(TForStatementSyntax forStatement); protected abstract bool IsValidVariableDeclarator(TVariableDeclaratorSyntax firstVariable); protected abstract bool TryGetForStatementComponents( TForStatementSyntax forStatement, out SyntaxToken iterationVariable, out TExpressionSyntax initializer, out TMemberAccessExpressionSyntax memberAccess, out TExpressionSyntax stepValueExpressionOpt, CancellationToken cancellationToken); protected abstract SyntaxNode ConvertForNode( TForStatementSyntax currentFor, TTypeNode? typeNode, SyntaxToken foreachIdentifier, TExpressionSyntax collectionExpression, ITypeSymbol iterationVariableType, OptionSet options); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var forStatement = await context.TryGetRelevantNodeAsync<TForStatementSyntax>().ConfigureAwait(false); if (forStatement == null) { return; } if (!TryGetForStatementComponents(forStatement, out var iterationVariable, out var initializer, out var memberAccess, out var stepValueExpressionOpt, cancellationToken)) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); syntaxFacts.GetPartsOfMemberAccessExpression(memberAccess, out var collectionExpressionNode, out var memberAccessNameNode); var collectionExpression = (TExpressionSyntax)collectionExpressionNode; syntaxFacts.GetNameAndArityOfSimpleName(memberAccessNameNode, out var memberAccessName, out _); if (memberAccessName is not nameof(Array.Length) and not nameof(IList.Count)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Make sure it's a single-variable for loop and that we're not a loop where we're // referencing some previously declared symbol. i.e // VB allows: // // dim i as integer // for i = 0 to ... // // We can't convert this as it would change important semantics. // NOTE: we could potentially update this if we saw that the variable was not used // after the for-loop. But, for now, we'll just be conservative and assume this means // the user wanted the 'i' for some other purpose and we should keep things as is. if (semanticModel.GetOperation(forStatement, cancellationToken) is not ILoopOperation operation || operation.Locals.Length != 1) { return; } // Make sure we're starting at 0. var initializerValue = semanticModel.GetConstantValue(initializer, cancellationToken); if (!(initializerValue.HasValue && initializerValue.Value is 0)) { return; } // Make sure we're incrementing by 1. if (stepValueExpressionOpt != null) { var stepValue = semanticModel.GetConstantValue(stepValueExpressionOpt); if (!(stepValue.HasValue && stepValue.Value is 1)) { return; } } var collectionType = semanticModel.GetTypeInfo(collectionExpression, cancellationToken); if (collectionType.Type == null || collectionType.Type.TypeKind == TypeKind.Error) { return; } var containingType = semanticModel.GetEnclosingNamedType(textSpan.Start, cancellationToken); if (containingType == null) { return; } var ienumerableType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); var ienumeratorType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T); // make sure the collection can be iterated. if (!TryGetIterationElementType( containingType, collectionType.Type, ienumerableType, ienumeratorType, out var iterationType)) { return; } // If the user uses the iteration variable for any other reason, we can't convert this. var bodyStatements = GetBodyStatements(forStatement); foreach (var statement in bodyStatements) { if (IterationVariableIsUsedForMoreThanCollectionIndex(statement)) { return; } } // Looks good. We can convert this. context.RegisterRefactoring( new MyCodeAction(GetTitle(), c => ConvertForToForEachAsync( document, forStatement, iterationVariable, collectionExpression, containingType, collectionType.Type, iterationType, c)), forStatement.Span); return; // local functions bool IterationVariableIsUsedForMoreThanCollectionIndex(SyntaxNode current) { if (syntaxFacts.IsIdentifierName(current)) { syntaxFacts.GetNameAndArityOfSimpleName(current, out var name, out _); if (name == iterationVariable.ValueText) { // found a reference. make sure it's only used inside something like // list[i] if (!syntaxFacts.IsSimpleArgument(current.Parent) || !syntaxFacts.IsElementAccessExpression(current.Parent?.Parent?.Parent)) { // used in something other than accessing into a collection. // can't convert this for-loop. return true; } var arguments = syntaxFacts.GetArgumentsOfArgumentList(current.Parent.Parent); if (arguments.Count != 1) { // was used in a multi-dimensional indexing. Can't conver this. return true; } var expr = syntaxFacts.GetExpressionOfElementAccessExpression(current.Parent.Parent.Parent); if (!syntaxFacts.AreEquivalent(expr, collectionExpression)) { // was indexing into something other than the collection. // can't convert this for-loop. return true; } // this usage of the for-variable is fine. } } foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) { if (IterationVariableIsUsedForMoreThanCollectionIndex(child.AsNode()!)) { return true; } } } return false; } } private static IEnumerable<TSymbol> TryFindMembersInThisOrBaseTypes<TSymbol>( INamedTypeSymbol containingType, ITypeSymbol type, string memberName) where TSymbol : class, ISymbol { var methods = type.GetAccessibleMembersInThisAndBaseTypes<TSymbol>(containingType); return methods.Where(m => m.Name == memberName); } private static TSymbol TryFindMemberInThisOrBaseTypes<TSymbol>( INamedTypeSymbol containingType, ITypeSymbol type, string memberName) where TSymbol : class, ISymbol { return TryFindMembersInThisOrBaseTypes<TSymbol>(containingType, type, memberName).FirstOrDefault(); } private static bool TryGetIterationElementType( INamedTypeSymbol containingType, ITypeSymbol collectionType, INamedTypeSymbol ienumerableType, INamedTypeSymbol ienumeratorType, [NotNullWhen(true)] out ITypeSymbol? iterationType) { if (collectionType is IArrayTypeSymbol arrayType) { iterationType = arrayType.ElementType; // We only support single-dimensional array iteration. return arrayType.Rank == 1; } // Check in the class/struct hierarchy first. var getEnumeratorMethod = TryFindMemberInThisOrBaseTypes<IMethodSymbol>( containingType, collectionType, WellKnownMemberNames.GetEnumeratorMethodName); if (getEnumeratorMethod != null) { return TryGetIterationElementTypeFromGetEnumerator( containingType, getEnumeratorMethod, ienumeratorType, out iterationType); } // couldn't find .GetEnumerator on the class/struct. Check the interface hierarchy. var instantiatedIEnumerableType = collectionType.GetAllInterfacesIncludingThis().FirstOrDefault( t => Equals(t.OriginalDefinition, ienumerableType)); if (instantiatedIEnumerableType != null) { iterationType = instantiatedIEnumerableType.TypeArguments[0]; return true; } iterationType = null; return false; } private static bool TryGetIterationElementTypeFromGetEnumerator( INamedTypeSymbol containingType, IMethodSymbol getEnumeratorMethod, INamedTypeSymbol ienumeratorType, [NotNullWhen(true)] out ITypeSymbol? iterationType) { var getEnumeratorReturnType = getEnumeratorMethod.ReturnType; // Check in the class/struct hierarchy first. var currentProperty = TryFindMemberInThisOrBaseTypes<IPropertySymbol>( containingType, getEnumeratorReturnType, WellKnownMemberNames.CurrentPropertyName); if (currentProperty != null) { iterationType = currentProperty.Type; return true; } // couldn't find .Current on the class/struct. Check the interface hierarchy. var instantiatedIEnumeratorType = getEnumeratorReturnType.GetAllInterfacesIncludingThis().FirstOrDefault( t => Equals(t.OriginalDefinition, ienumeratorType)); if (instantiatedIEnumeratorType != null) { iterationType = instantiatedIEnumeratorType.TypeArguments[0]; return true; } iterationType = null; return false; } private async Task<Document> ConvertForToForEachAsync( Document document, TForStatementSyntax forStatement, SyntaxToken iterationVariable, TExpressionSyntax collectionExpression, INamedTypeSymbol containingType, ITypeSymbol collectionType, ITypeSymbol iterationType, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var generator = SyntaxGenerator.GetGenerator(document); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, generator); // create a dummy "list[i]" expression. We'll use this to find all places to replace // in the current for statement. var indexExpression = generator.ElementAccessExpression( collectionExpression, generator.IdentifierName(iterationVariable)); // See if the first statement in the for loop is of the form: // var x = list[i] or // // If so, we'll use those as the iteration variables for the new foreach statement. var (typeNode, foreachIdentifier, declarationStatement) = TryDeconstructInitialDeclaration(); if (typeNode == null) { // user didn't provide an explicit type. Check if the index-type of the collection // is different from than .Current type of the enumerator. If so, add an explicit // type so that the foreach will coerce the types accordingly. var indexerType = GetIndexerType(containingType, collectionType); if (!Equals(indexerType, iterationType)) { typeNode = (TTypeNode)generator.TypeExpression( indexerType ?? semanticModel.Compilation.GetSpecialType(SpecialType.System_Object)); } } // If we couldn't find an appropriate existing variable to use as the foreach // variable, then generate one automatically. if (foreachIdentifier.RawKind == 0) { foreachIdentifier = semanticFacts.GenerateUniqueName( semanticModel, forStatement, containerOpt: null, baseName: "v", usedNames: Enumerable.Empty<string>(), cancellationToken); foreachIdentifier = foreachIdentifier.WithAdditionalAnnotations(RenameAnnotation.Create()); } // Create the expression we'll use to replace all matches in the for-body. var foreachIdentifierReference = foreachIdentifier.WithoutAnnotations(RenameAnnotation.Kind).WithoutTrivia(); // Walk the for statement, replacing any matches we find. FindAndReplaceMatches(forStatement); // Finally, remove the declaration statement if we found one. Move all its leading // trivia to the next statement. if (declarationStatement != null) { editor.RemoveNode(declarationStatement, SyntaxGenerator.DefaultRemoveOptions | SyntaxRemoveOptions.KeepLeadingTrivia); } var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); editor.ReplaceNode( forStatement, (currentFor, _) => ConvertForNode( (TForStatementSyntax)currentFor, typeNode, foreachIdentifier, collectionExpression, iterationType, options)); return document.WithSyntaxRoot(editor.GetChangedRoot()); // local functions (TTypeNode?, SyntaxToken, TStatementSyntax) TryDeconstructInitialDeclaration() { var bodyStatements = GetBodyStatements(forStatement); if (bodyStatements.Count >= 1) { var firstStatement = bodyStatements[0]; if (syntaxFacts.IsLocalDeclarationStatement(firstStatement)) { var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(firstStatement); if (variables.Count == 1) { var firstVariable = (TVariableDeclaratorSyntax)variables[0]; if (IsValidVariableDeclarator(firstVariable)) { var firstVariableInitializer = syntaxFacts.GetValueOfEqualsValueClause( syntaxFacts.GetInitializerOfVariableDeclarator(firstVariable)); if (syntaxFacts.AreEquivalent(firstVariableInitializer, indexExpression)) { var type = (TTypeNode?)syntaxFacts.GetTypeOfVariableDeclarator(firstVariable)?.WithoutLeadingTrivia(); var identifier = syntaxFacts.GetIdentifierOfVariableDeclarator(firstVariable); var statement = firstStatement; return (type, identifier, statement); } } } } } return default; } void FindAndReplaceMatches(SyntaxNode current) { if (SemanticEquivalence.AreEquivalent(semanticModel, current, collectionExpression)) { if (syntaxFacts.AreEquivalent(current.Parent, indexExpression)) { var indexMatch = current.GetRequiredParent(); // Found a match. replace with iteration variable. var replacementToken = foreachIdentifierReference; if (semanticFacts.IsWrittenTo(semanticModel, indexMatch, cancellationToken)) { replacementToken = replacementToken.WithAdditionalAnnotations( WarningAnnotation.Create(FeaturesResources.Warning_colon_Collection_was_modified_during_iteration)); } if (CrossesFunctionBoundary(current)) { replacementToken = replacementToken.WithAdditionalAnnotations( WarningAnnotation.Create(FeaturesResources.Warning_colon_Iteration_variable_crossed_function_boundary)); } editor.ReplaceNode( indexMatch, generator.IdentifierName(replacementToken).WithTriviaFrom(indexMatch)); } else { // Collection was used for some other purpose. If it's passed as an argument // to something, or is written to, or has a method invoked on it, we'll warn // that it's potentially changing and may break if you switch to a foreach loop. var shouldWarn = syntaxFacts.IsArgument(current.Parent); shouldWarn |= semanticFacts.IsWrittenTo(semanticModel, current, cancellationToken); shouldWarn |= syntaxFacts.IsAnyMemberAccessExpression(current.Parent) && syntaxFacts.IsInvocationExpression(current.Parent.Parent); if (shouldWarn) { editor.ReplaceNode( current, (node, _) => node.WithAdditionalAnnotations( WarningAnnotation.Create(FeaturesResources.Warning_colon_Iteration_variable_crossed_function_boundary))); } } return; } foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) { FindAndReplaceMatches(child.AsNode()!); } } } bool CrossesFunctionBoundary(SyntaxNode node) { var containingFunction = node.AncestorsAndSelf().FirstOrDefault( n => syntaxFacts.IsLocalFunctionStatement(n) || syntaxFacts.IsAnonymousFunction(n)); if (containingFunction == null) { return false; } return containingFunction.AncestorsAndSelf().Contains(forStatement); } } private static ITypeSymbol? GetIndexerType(INamedTypeSymbol containingType, ITypeSymbol collectionType) { if (collectionType is IArrayTypeSymbol arrayType) { return arrayType.Rank == 1 ? arrayType.ElementType : null; } var indexer = collectionType.GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType) .Where(IsViableIndexer) .FirstOrDefault(); if (indexer?.Type != null) { return indexer.Type; } if (collectionType.IsInterfaceType()) { var interfaces = collectionType.GetAllInterfacesIncludingThis(); indexer = interfaces.SelectMany(i => i.GetMembers().OfType<IPropertySymbol>().Where(IsViableIndexer)) .FirstOrDefault(); return indexer?.Type; } return null; } private static bool IsViableIndexer(IPropertySymbol property) => property.IsIndexer && property.Parameters.Length == 1 && property.Parameters[0].Type?.SpecialType == SpecialType.System_Int32; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertForToForEach { internal abstract class AbstractConvertForToForEachCodeRefactoringProvider< TStatementSyntax, TForStatementSyntax, TExpressionSyntax, TMemberAccessExpressionSyntax, TTypeNode, TVariableDeclaratorSyntax> : CodeRefactoringProvider where TStatementSyntax : SyntaxNode where TForStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TMemberAccessExpressionSyntax : SyntaxNode where TTypeNode : SyntaxNode where TVariableDeclaratorSyntax : SyntaxNode { protected abstract string GetTitle(); protected abstract SyntaxList<TStatementSyntax> GetBodyStatements(TForStatementSyntax forStatement); protected abstract bool IsValidVariableDeclarator(TVariableDeclaratorSyntax firstVariable); protected abstract bool TryGetForStatementComponents( TForStatementSyntax forStatement, out SyntaxToken iterationVariable, out TExpressionSyntax initializer, out TMemberAccessExpressionSyntax memberAccess, out TExpressionSyntax stepValueExpressionOpt, CancellationToken cancellationToken); protected abstract SyntaxNode ConvertForNode( TForStatementSyntax currentFor, TTypeNode? typeNode, SyntaxToken foreachIdentifier, TExpressionSyntax collectionExpression, ITypeSymbol iterationVariableType, OptionSet options); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var forStatement = await context.TryGetRelevantNodeAsync<TForStatementSyntax>().ConfigureAwait(false); if (forStatement == null) { return; } if (!TryGetForStatementComponents(forStatement, out var iterationVariable, out var initializer, out var memberAccess, out var stepValueExpressionOpt, cancellationToken)) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); syntaxFacts.GetPartsOfMemberAccessExpression(memberAccess, out var collectionExpressionNode, out var memberAccessNameNode); var collectionExpression = (TExpressionSyntax)collectionExpressionNode; syntaxFacts.GetNameAndArityOfSimpleName(memberAccessNameNode, out var memberAccessName, out _); if (memberAccessName is not nameof(Array.Length) and not nameof(IList.Count)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Make sure it's a single-variable for loop and that we're not a loop where we're // referencing some previously declared symbol. i.e // VB allows: // // dim i as integer // for i = 0 to ... // // We can't convert this as it would change important semantics. // NOTE: we could potentially update this if we saw that the variable was not used // after the for-loop. But, for now, we'll just be conservative and assume this means // the user wanted the 'i' for some other purpose and we should keep things as is. if (semanticModel.GetOperation(forStatement, cancellationToken) is not ILoopOperation operation || operation.Locals.Length != 1) { return; } // Make sure we're starting at 0. var initializerValue = semanticModel.GetConstantValue(initializer, cancellationToken); if (!(initializerValue.HasValue && initializerValue.Value is 0)) { return; } // Make sure we're incrementing by 1. if (stepValueExpressionOpt != null) { var stepValue = semanticModel.GetConstantValue(stepValueExpressionOpt); if (!(stepValue.HasValue && stepValue.Value is 1)) { return; } } var collectionType = semanticModel.GetTypeInfo(collectionExpression, cancellationToken); if (collectionType.Type == null || collectionType.Type.TypeKind == TypeKind.Error) { return; } var containingType = semanticModel.GetEnclosingNamedType(textSpan.Start, cancellationToken); if (containingType == null) { return; } var ienumerableType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); var ienumeratorType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T); // make sure the collection can be iterated. if (!TryGetIterationElementType( containingType, collectionType.Type, ienumerableType, ienumeratorType, out var iterationType)) { return; } // If the user uses the iteration variable for any other reason, we can't convert this. var bodyStatements = GetBodyStatements(forStatement); foreach (var statement in bodyStatements) { if (IterationVariableIsUsedForMoreThanCollectionIndex(statement)) { return; } } // Looks good. We can convert this. context.RegisterRefactoring( new MyCodeAction(GetTitle(), c => ConvertForToForEachAsync( document, forStatement, iterationVariable, collectionExpression, containingType, collectionType.Type, iterationType, c)), forStatement.Span); return; // local functions bool IterationVariableIsUsedForMoreThanCollectionIndex(SyntaxNode current) { if (syntaxFacts.IsIdentifierName(current)) { syntaxFacts.GetNameAndArityOfSimpleName(current, out var name, out _); if (name == iterationVariable.ValueText) { // found a reference. make sure it's only used inside something like // list[i] if (!syntaxFacts.IsSimpleArgument(current.Parent) || !syntaxFacts.IsElementAccessExpression(current.Parent?.Parent?.Parent)) { // used in something other than accessing into a collection. // can't convert this for-loop. return true; } var arguments = syntaxFacts.GetArgumentsOfArgumentList(current.Parent.Parent); if (arguments.Count != 1) { // was used in a multi-dimensional indexing. Can't conver this. return true; } var expr = syntaxFacts.GetExpressionOfElementAccessExpression(current.Parent.Parent.Parent); if (!syntaxFacts.AreEquivalent(expr, collectionExpression)) { // was indexing into something other than the collection. // can't convert this for-loop. return true; } // this usage of the for-variable is fine. } } foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) { if (IterationVariableIsUsedForMoreThanCollectionIndex(child.AsNode()!)) { return true; } } } return false; } } private static IEnumerable<TSymbol> TryFindMembersInThisOrBaseTypes<TSymbol>( INamedTypeSymbol containingType, ITypeSymbol type, string memberName) where TSymbol : class, ISymbol { var methods = type.GetAccessibleMembersInThisAndBaseTypes<TSymbol>(containingType); return methods.Where(m => m.Name == memberName); } private static TSymbol TryFindMemberInThisOrBaseTypes<TSymbol>( INamedTypeSymbol containingType, ITypeSymbol type, string memberName) where TSymbol : class, ISymbol { return TryFindMembersInThisOrBaseTypes<TSymbol>(containingType, type, memberName).FirstOrDefault(); } private static bool TryGetIterationElementType( INamedTypeSymbol containingType, ITypeSymbol collectionType, INamedTypeSymbol ienumerableType, INamedTypeSymbol ienumeratorType, [NotNullWhen(true)] out ITypeSymbol? iterationType) { if (collectionType is IArrayTypeSymbol arrayType) { iterationType = arrayType.ElementType; // We only support single-dimensional array iteration. return arrayType.Rank == 1; } // Check in the class/struct hierarchy first. var getEnumeratorMethod = TryFindMemberInThisOrBaseTypes<IMethodSymbol>( containingType, collectionType, WellKnownMemberNames.GetEnumeratorMethodName); if (getEnumeratorMethod != null) { return TryGetIterationElementTypeFromGetEnumerator( containingType, getEnumeratorMethod, ienumeratorType, out iterationType); } // couldn't find .GetEnumerator on the class/struct. Check the interface hierarchy. var instantiatedIEnumerableType = collectionType.GetAllInterfacesIncludingThis().FirstOrDefault( t => Equals(t.OriginalDefinition, ienumerableType)); if (instantiatedIEnumerableType != null) { iterationType = instantiatedIEnumerableType.TypeArguments[0]; return true; } iterationType = null; return false; } private static bool TryGetIterationElementTypeFromGetEnumerator( INamedTypeSymbol containingType, IMethodSymbol getEnumeratorMethod, INamedTypeSymbol ienumeratorType, [NotNullWhen(true)] out ITypeSymbol? iterationType) { var getEnumeratorReturnType = getEnumeratorMethod.ReturnType; // Check in the class/struct hierarchy first. var currentProperty = TryFindMemberInThisOrBaseTypes<IPropertySymbol>( containingType, getEnumeratorReturnType, WellKnownMemberNames.CurrentPropertyName); if (currentProperty != null) { iterationType = currentProperty.Type; return true; } // couldn't find .Current on the class/struct. Check the interface hierarchy. var instantiatedIEnumeratorType = getEnumeratorReturnType.GetAllInterfacesIncludingThis().FirstOrDefault( t => Equals(t.OriginalDefinition, ienumeratorType)); if (instantiatedIEnumeratorType != null) { iterationType = instantiatedIEnumeratorType.TypeArguments[0]; return true; } iterationType = null; return false; } private async Task<Document> ConvertForToForEachAsync( Document document, TForStatementSyntax forStatement, SyntaxToken iterationVariable, TExpressionSyntax collectionExpression, INamedTypeSymbol containingType, ITypeSymbol collectionType, ITypeSymbol iterationType, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var generator = SyntaxGenerator.GetGenerator(document); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, generator); // create a dummy "list[i]" expression. We'll use this to find all places to replace // in the current for statement. var indexExpression = generator.ElementAccessExpression( collectionExpression, generator.IdentifierName(iterationVariable)); // See if the first statement in the for loop is of the form: // var x = list[i] or // // If so, we'll use those as the iteration variables for the new foreach statement. var (typeNode, foreachIdentifier, declarationStatement) = TryDeconstructInitialDeclaration(); if (typeNode == null) { // user didn't provide an explicit type. Check if the index-type of the collection // is different from than .Current type of the enumerator. If so, add an explicit // type so that the foreach will coerce the types accordingly. var indexerType = GetIndexerType(containingType, collectionType); if (!Equals(indexerType, iterationType)) { typeNode = (TTypeNode)generator.TypeExpression( indexerType ?? semanticModel.Compilation.GetSpecialType(SpecialType.System_Object)); } } // If we couldn't find an appropriate existing variable to use as the foreach // variable, then generate one automatically. if (foreachIdentifier.RawKind == 0) { foreachIdentifier = semanticFacts.GenerateUniqueName( semanticModel, forStatement, containerOpt: null, baseName: "v", usedNames: Enumerable.Empty<string>(), cancellationToken); foreachIdentifier = foreachIdentifier.WithAdditionalAnnotations(RenameAnnotation.Create()); } // Create the expression we'll use to replace all matches in the for-body. var foreachIdentifierReference = foreachIdentifier.WithoutAnnotations(RenameAnnotation.Kind).WithoutTrivia(); // Walk the for statement, replacing any matches we find. FindAndReplaceMatches(forStatement); // Finally, remove the declaration statement if we found one. Move all its leading // trivia to the next statement. if (declarationStatement != null) { editor.RemoveNode(declarationStatement, SyntaxGenerator.DefaultRemoveOptions | SyntaxRemoveOptions.KeepLeadingTrivia); } var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); editor.ReplaceNode( forStatement, (currentFor, _) => ConvertForNode( (TForStatementSyntax)currentFor, typeNode, foreachIdentifier, collectionExpression, iterationType, options)); return document.WithSyntaxRoot(editor.GetChangedRoot()); // local functions (TTypeNode?, SyntaxToken, TStatementSyntax) TryDeconstructInitialDeclaration() { var bodyStatements = GetBodyStatements(forStatement); if (bodyStatements.Count >= 1) { var firstStatement = bodyStatements[0]; if (syntaxFacts.IsLocalDeclarationStatement(firstStatement)) { var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(firstStatement); if (variables.Count == 1) { var firstVariable = (TVariableDeclaratorSyntax)variables[0]; if (IsValidVariableDeclarator(firstVariable)) { var firstVariableInitializer = syntaxFacts.GetValueOfEqualsValueClause( syntaxFacts.GetInitializerOfVariableDeclarator(firstVariable)); if (syntaxFacts.AreEquivalent(firstVariableInitializer, indexExpression)) { var type = (TTypeNode?)syntaxFacts.GetTypeOfVariableDeclarator(firstVariable)?.WithoutLeadingTrivia(); var identifier = syntaxFacts.GetIdentifierOfVariableDeclarator(firstVariable); var statement = firstStatement; return (type, identifier, statement); } } } } } return default; } void FindAndReplaceMatches(SyntaxNode current) { if (SemanticEquivalence.AreEquivalent(semanticModel, current, collectionExpression)) { if (syntaxFacts.AreEquivalent(current.Parent, indexExpression)) { var indexMatch = current.GetRequiredParent(); // Found a match. replace with iteration variable. var replacementToken = foreachIdentifierReference; if (semanticFacts.IsWrittenTo(semanticModel, indexMatch, cancellationToken)) { replacementToken = replacementToken.WithAdditionalAnnotations( WarningAnnotation.Create(FeaturesResources.Warning_colon_Collection_was_modified_during_iteration)); } if (CrossesFunctionBoundary(current)) { replacementToken = replacementToken.WithAdditionalAnnotations( WarningAnnotation.Create(FeaturesResources.Warning_colon_Iteration_variable_crossed_function_boundary)); } editor.ReplaceNode( indexMatch, generator.IdentifierName(replacementToken).WithTriviaFrom(indexMatch)); } else { // Collection was used for some other purpose. If it's passed as an argument // to something, or is written to, or has a method invoked on it, we'll warn // that it's potentially changing and may break if you switch to a foreach loop. var shouldWarn = syntaxFacts.IsArgument(current.Parent); shouldWarn |= semanticFacts.IsWrittenTo(semanticModel, current, cancellationToken); shouldWarn |= syntaxFacts.IsAnyMemberAccessExpression(current.Parent) && syntaxFacts.IsInvocationExpression(current.Parent.Parent); if (shouldWarn) { editor.ReplaceNode( current, (node, _) => node.WithAdditionalAnnotations( WarningAnnotation.Create(FeaturesResources.Warning_colon_Iteration_variable_crossed_function_boundary))); } } return; } foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) { FindAndReplaceMatches(child.AsNode()!); } } } bool CrossesFunctionBoundary(SyntaxNode node) { var containingFunction = node.AncestorsAndSelf().FirstOrDefault( n => syntaxFacts.IsLocalFunctionStatement(n) || syntaxFacts.IsAnonymousFunction(n)); if (containingFunction == null) { return false; } return containingFunction.AncestorsAndSelf().Contains(forStatement); } } private static ITypeSymbol? GetIndexerType(INamedTypeSymbol containingType, ITypeSymbol collectionType) { if (collectionType is IArrayTypeSymbol arrayType) { return arrayType.Rank == 1 ? arrayType.ElementType : null; } var indexer = collectionType.GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType) .Where(IsViableIndexer) .FirstOrDefault(); if (indexer?.Type != null) { return indexer.Type; } if (collectionType.IsInterfaceType()) { var interfaces = collectionType.GetAllInterfacesIncludingThis(); indexer = interfaces.SelectMany(i => i.GetMembers().OfType<IPropertySymbol>().Where(IsViableIndexer)) .FirstOrDefault(); return indexer?.Type; } return null; } private static bool IsViableIndexer(IPropertySymbol property) => property.IsIndexer && property.Parameters.Length == 1 && property.Parameters[0].Type?.SpecialType == SpecialType.System_Int32; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/CSharp/Portable/BraceCompletion/StringLiteralBraceCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion { [Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared] internal class StringLiteralBraceCompletionService : AbstractBraceCompletionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringLiteralBraceCompletionService() { } protected override char OpeningBrace => DoubleQuote.OpenCharacter; protected override char ClosingBrace => DoubleQuote.CloseCharacter; public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken) => AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken); public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken) { // Only potentially valid for string literal completion if not in an interpolated string brace completion context. if (OpeningBrace == brace && await InterpolatedStringBraceCompletionService.IsPositionInInterpolatedStringContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false)) { return false; } return await base.CanProvideBraceCompletionAsync(brace, openingPosition, document, cancellationToken).ConfigureAwait(false); } protected override bool IsValidOpeningBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override bool IsValidClosingBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override Task<bool> IsValidOpenBraceTokenAtPositionAsync(SyntaxToken token, int position, Document document, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (ParentIsSkippedTokensTriviaOrNull(syntaxFactsService, token) || !IsValidOpeningBraceToken(token)) { return SpecializedTasks.False; } if (token.SpanStart == position) { return SpecializedTasks.True; } // The character at the position is a double quote but the token's span start we found at the position // doesn't match the position. Check if we're in a verbatim string token @" where the token span start // is the @ character and the " is one past the token start. return Task.FromResult(token.SpanStart + 1 == position && token.IsVerbatimStringLiteral()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion { [Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared] internal class StringLiteralBraceCompletionService : AbstractBraceCompletionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringLiteralBraceCompletionService() { } protected override char OpeningBrace => DoubleQuote.OpenCharacter; protected override char ClosingBrace => DoubleQuote.CloseCharacter; public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken) => AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken); public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken) { // Only potentially valid for string literal completion if not in an interpolated string brace completion context. if (OpeningBrace == brace && await InterpolatedStringBraceCompletionService.IsPositionInInterpolatedStringContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false)) { return false; } return await base.CanProvideBraceCompletionAsync(brace, openingPosition, document, cancellationToken).ConfigureAwait(false); } protected override bool IsValidOpeningBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override bool IsValidClosingBraceToken(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken); protected override Task<bool> IsValidOpenBraceTokenAtPositionAsync(SyntaxToken token, int position, Document document, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (ParentIsSkippedTokensTriviaOrNull(syntaxFactsService, token) || !IsValidOpeningBraceToken(token)) { return SpecializedTasks.False; } if (token.SpanStart == position) { return SpecializedTasks.True; } // The character at the position is a double quote but the token's span start we found at the position // doesn't match the position. Check if we're in a verbatim string token @" where the token span start // is the @ character and the " is one past the token start. return Task.FromResult(token.SpanStart + 1 == position && token.IsVerbatimStringLiteral()); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/CSharpTest2/Recommendations/OrderByKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class OrderByKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtEndOfPreviousClause() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNewClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y where x > y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousContinuationClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y group x by y into g $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBetweenClauses() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$ from z in w")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOrderBy() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y orderby $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class OrderByKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtEndOfPreviousClause() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNewClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y where x > y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousContinuationClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y group x by y into g $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBetweenClauses() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$ from z in w")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOrderBy() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y orderby $$")); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Analyzers/CSharp/Tests/UseLocalFunction/UseLocalFunctionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseLocalFunction; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseLocalFunction { public partial class UseLocalFunctionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseLocalFunctionTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseLocalFunctionDiagnosticAnalyzer(), GetCSharpUseLocalFunctionCodeFixProvider()); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingBeforeCSharp7() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingIfWrittenAfter() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; fibonacci = null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingIfWrittenInside() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { fibonacci = null; if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForErrorType() { await TestMissingAsync( @"class C { void M() { // Func can't be bound. Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForMultipleVariables() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }, fib2 = x => x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForField() { await TestMissingAsync( @"using System; class C { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SimpleLambda_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_AnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_Block_ExtraParens() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = ((Func<int, int>)(v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); })); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_AnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(v => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_WrongName() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fib = null; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_InitializedToOtherValue() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = GetCallback(); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_NoInitializer() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultLiteral() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = default; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }", // 7.1 is required for default literals, so 7.2 should be sufficient // and is used in other tests new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = default(Func<int, int>); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression_var() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = default(Func<int, int>); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_AnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = v => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> {|FixAllInDocument:fibonacci|} = v => { Func<bool, bool> isTrue = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> fibonacci = v => { Func<bool, bool> {|FixAllInDocument:isTrue|} = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll3() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> fibonacci = null; fibonacci = v => { Func<bool, bool> {|FixAllInDocument:isTrue|} = null; isTrue = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll4() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> {|FixAllInDocument:fibonacci|} = null; fibonacci = v => { Func<int, int> fibonacciHelper = null; fibonacciHelper = n => fibonacci.Invoke(n - 1) + fibonacci(arg: n - 2); return fibonacciHelper(v); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { int fibonacciHelper(int n) => fibonacci(n - 1) + fibonacci(v: n - 2); return fibonacciHelper(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestTrivia() { await TestInRegularAndScript1Async( @"using System; class C { void M() { // Leading trivia Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; // Trailing trivia } }", @"using System; class C { void M() { // Leading trivia static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } // Trailing trivia } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestInWithParameters() { await TestInRegularAndScript1Async( @" delegate void D(in int p); class C { void M() { D [||]lambda = (in int p) => throw null; } }", @" delegate void D(in int p); class C { void M() { void lambda(in int p) => throw null; } }", // Run with 7.2 to get read-only references new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestRefReadOnlyWithReturnType() { await TestInRegularAndScript1Async( @" delegate ref readonly int D(); class C { void M() { D [||]lambda = () => throw null; } }", @" delegate ref readonly int D(); class C { void M() { static ref readonly int lambda() => throw null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestMissingIfConvertedToNonDelegate() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task> [||]f = x => { return Task.CompletedTask; }; Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(object expected, object actual) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToDelegate() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task> [||]f = x => { return Task.CompletedTask; }; Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(Func<string, Task> expected, object actual) { } }", @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { static Task f(string x) { return Task.CompletedTask; } Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(Func<string, Task> expected, object actual) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestNotAvailableIfConvertedToSystemDelegate() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Delegate expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestNotAvailableIfConvertedToSystemMulticastDelegate() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(MulticastDelegate expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate0() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Func<object, string> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(object x) => """"; M(f); } public static void M(Func<object, string> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(object x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<string, string> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(string x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate3() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, object> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static object f(object x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfAdded() { await TestMissingAsync( @"using System; using System.Linq.Expressions; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; var doubleDelegate = local + local; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfUsedInMemberAccess1() { await TestMissingAsync( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; var str = local.ToString(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestMissingIfUsedInMemberAccess2() { await TestMissingAsync( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate[||]local = x => x; Console.Write(local.Invoke(t)); var str = local.ToString(); local.Invoke(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfUsedInExpressionTree() { await TestMissingAsync( @"using System; using System.Linq.Expressions; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; Expression<Action> expression = () => local(null); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24344, "https://github.com/dotnet/roslyn/issues/24344")] public async Task TestMissingIfUsedInExpressionTree2() { await TestMissingAsync( @"using System; using System.Linq.Expressions; public class C { void Method(Action action) { } Expression<Action> Example() { Action [||]action = () => Method(null); return () => Method(action); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod1() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; local.Invoke(); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { static T local(T x = null) => x; local(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod2() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod3() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); var val = local.Invoke(t); local.Invoke(t); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); var val = local(t); local(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod4() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); var val = local.Invoke(t); local(t); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); var val = local(t); local(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] public async Task TestWithRecursiveInvokeMethod1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]local = null; local = () => local.Invoke(); } }", @"using System; class C { void M() { static void local() => local(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] public async Task TestWithRecursiveInvokeMethod2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]local = null; local = () => { local.Invoke(); } } }", @"using System; class C { void M() { static void local() { local(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364935495")] public async Task TestWithNestedInvokeMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string, string> [||]a = s => s; a.Invoke(a.Invoke(null)); } }", @"using System; class C { void M() { static string a(string s) => s; a(a(null)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNestedRecursiveInvokeMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string, string> [||]a = null; a = s => a.Invoke(a.Invoke(s)); } }", @"using System; class C { void M() { static string a(string s) => a(a(s)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDefaultParameter1() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = (s) => s; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364655480")] public async Task TestWithDefaultParameter2() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = (string s) => s; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDefaultParameter3() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = delegate (string s) { return s; }; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") { return s; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364764542")] public async Task TestWithUnmatchingParameterList1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]x = (a, b) => { }; } }", @"using System; class C { void M() { static void x(object a, object b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithUnmatchingParameterList2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]x = (string a, int b) => { }; } }", @"using System; class C { void M() { static void x(string a, int b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncLambdaExpression() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task> [||]f = async () => await Task.Yield(); } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task f() => await Task.Yield(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncAnonymousMethod() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task<int>> [||]f = async delegate () { return 0; }; } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task<int> f() { return 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithParameterlessAnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { EventHandler [||]handler = delegate { }; E += handler; } event EventHandler E; }", @"using System; class C { void M() { static void handler(object sender, EventArgs e) { } E += handler; } event EventHandler E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24764, "https://github.com/dotnet/roslyn/issues/24764")] public async Task TestWithNamedArguments1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2, a3) => { }; x(arg1: null, 0, 0); x.Invoke(arg1: null, 0, 0); } }", @"using System; class C { void M() { static void x(string a1, int a2, int a3) { } x(a1: null, 0, 0); x(a1: null, 0, 0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24764, "https://github.com/dotnet/roslyn/issues/24764")] public async Task TestWithNamedArguments2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2, a3) => { x(null, arg3: 0, arg2: 0); x.Invoke(null, arg3: 0, arg2: 0); }; } }", @"using System; class C { void M() { static void x(string a1, int a2, int a3) { x(null, a3: 0, a2: 0); x(null, a3: 0, a2: 0); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedArgumentsAndBrokenCode1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (int a1, string a2, string a3, a4) => { }; x(null, arg3: 0, arg2: 0, arg4: 0); x.Invoke(null, arg3: 0, arg2: 0, arg4: 0); x.Invoke(0, null, null, null, null, null); } }", @"using System; class C { void M() { static void x(int a1, string a2, string a3, object a4) { } x(null, a3: 0, a2: 0, arg4: 0); x(null, a3: 0, a2: 0, arg4: 0); x(0, null, null, null, null, null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedArgumentsAndBrokenCode2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2) => { x(null, arg3: 0, arg2: 0); x.Invoke(null, arg3: 0, arg2: 0); x.Invoke(); }; } }", @"using System; class C { void M() { static void x(string a1, int a2) { x(null, arg3: 0, a2: 0); x(null, arg3: 0, a2: 0); x(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedAndDefaultArguments() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { MyDelegate [||]x = null; x = (a1, a2, a3) => { x(null, arg3: 42); return x.Invoke(null, arg3: 42); }; } }", @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { static string x(string a1, int a2 = 2, int a3 = 3) { x(null, a3: 42); return x(null, a3: 42); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedAndDefaultArgumentsAndNestedRecursiveInvocations_FixAll() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { var x = (MyDelegate)delegate { MyDelegate {|FixAllInDocument:a|} = null; a = (string a1, int a2, int a3) => { MyDelegate b = null; b = (b1, b2, b3) => b.Invoke(arg1: b(null), arg2: a(arg1: a.Invoke(null)).Length, arg3: 42) + b(arg1: b.Invoke(null), arg3: a(arg1: a.Invoke(null)).Length, arg2: 42); return b(arg1: a1, b(arg1: a1).Length); }; return a(arg1: null); }; x(arg1: null); } }", @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { string x(string arg1, int arg2 = 2, int arg3 = 3) { string a(string a1, int a2 = 2, int a3 = 3) { string b(string b1, int b2 = 2, int b3 = 3) => b(b1: b(null), b2: a(a1: a(null)).Length, b3: 42) + b(b1: b(null), b3: a(a1: a(null)).Length, b2: 42); return b(b1: a1, b(b1: a1).Length); } return a(a1: null); } x(arg1: null); } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action [||]onUpdateSolutionCancel = () => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = async a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2MultiToken() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { Func<int, int[]> [||]onUpdateSolutionCancel = a => { return null; }; } }", @"using System; class C { void Goo() { static int[] onUpdateSolutionCancel(int a) { return null; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2MultiTokenAsync() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void Goo() { Func<int, Task<int[]>> [||]onUpdateSolutionCancel = async a => { return null; }; } }", @"using System; using System.Threading.Tasks; class C { void Goo() { static async Task<int[]> onUpdateSolutionCancel(int a) { return null; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine3() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = (int a) => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine4() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine4Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = async delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action)(() => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(a => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine2Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(async a => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine3() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)((int a) => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine4() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(delegate (int a) { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine4Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(async delegate (int a) { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = () => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine2Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = async a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine3() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = (int a) => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine4() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine4Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = async delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged1() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Class<T> { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged2() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Goo<T> { public class Class { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged3() { await TestMissingAsync( @"public class Class<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public void Caller() { void Some<T>(T t) { MyDelegate [||]local = x => x; Callee(local); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged4() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Goo<T> { public class Class<U> { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } } }"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/27950"), Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestAvailableIfTypeParameterNotChanged1() { await TestInRegularAndScript1Async( @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<T> : DelegateEnclosing<T> { static void Callee(MyDelegate d) => d(default); public void Caller() { MyDelegate [||]local = x => x; Callee(local); } }", @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<T> : DelegateEnclosing<T> { static void Callee(MyDelegate d) => d(default); public void Caller() { static T local(T x) => x; Callee(local); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestAvailableIfTypeParameterNotChanged2() { await TestInRegularAndScript1Async( @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<U> : DelegateEnclosing<U> { static void Callee(MyDelegate d) => d(default); public void Caller() { MyDelegate [||]local = x => x; Callee(local); } }", @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<U> : DelegateEnclosing<U> { static void Callee(MyDelegate d) => d(default); public void Caller() { static U local(U x) => x; Callee(local); } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedIfAssignedToVar() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string> [||]f = () => null; var f2 = f; } }", @"using System; class C { void M() { static string f() => null; var f2 = (Func<string>)f; } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForGenericTypeInference1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForGenericTypeInference2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } void Method(string o) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } void Method(string o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForOverloadResolution() { await TestInRegularAndScript1Async( @"using System; delegate string CustomDelegate(); class C { void M() { Func<string> [||]f = () => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }", @"using System; delegate string CustomDelegate(); class C { void M() { static string f() => null; Method((Func<string>)f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithoutCastIfUnnecessaryForOverloadResolution() { await TestInRegularAndScript1Async( @"using System; delegate string CustomDelegate(object arg); class C { void M() { Func<string> [||]f = () => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }", @"using System; delegate string CustomDelegate(object arg); class C { void M() { static string f() => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration() { await TestMissingAsync( @"using System; class C { void M() { Func<string> [||]f = () => null); Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration2() { await TestMissingAsync( @"using System; class C { void M() { Func<string> [||]f) = () => null; Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration3() { await TestMissingAsync( @"using System; class C { void M() { Func<string>) [||]f = () => null; Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithInvalidUnrelatedCode() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o)) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o)) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithInvalidUnrelatedCode2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; (Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { static string f(int _) => null; (Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithObsoleteCode() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => S(); Method(f); } [System.Obsolete] string S() { return null; } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { string f(int _) => S(); Method((Func<int, string>)f); } [System.Obsolete] string S() { return null; } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDeclarationWarning() { await TestInRegularAndScript1Async( @"using System; class C { void M() { #warning Declaration Warning Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { #warning Declaration Warning static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMakeStaticIfNoCaptures() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestDoNotMakeStaticIfCaptures() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { M(); if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { int fibonacci(int v) { M(); if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncLambdaExpression_MakeStatic() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task> [||]f = async () => await Task.Yield(); } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task f() => await Task.Yield(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNullableParameterAndReturn() { await TestInRegularAndScript1Async( @"#nullable enable using System; class Program { static void Main(string[] args) { Func<string?, string?> [||]f = s => s; } }", @"#nullable enable using System; class Program { static void Main(string[] args) { static string? f(string? s) => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDiscardParameters() { await TestInRegularAndScript1Async( @" class Program { static void Main(string[] args) { System.Func<int, string, int, long> [||]f = (_, _, a) => 1; } }", @" class Program { static void Main(string[] args) { static long f(int _, string _, int a) => 1; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseLocalFunction; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseLocalFunction { public partial class UseLocalFunctionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseLocalFunctionTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseLocalFunctionDiagnosticAnalyzer(), GetCSharpUseLocalFunctionCodeFixProvider()); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingBeforeCSharp7() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingIfWrittenAfter() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; fibonacci = null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingIfWrittenInside() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { fibonacci = null; if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForErrorType() { await TestMissingAsync( @"class C { void M() { // Func can't be bound. Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForMultipleVariables() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }, fib2 = x => x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForField() { await TestMissingAsync( @"using System; class C { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SimpleLambda_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_AnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_Block_ExtraParens() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = ((Func<int, int>)(v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); })); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_AnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(v => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_WrongName() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fib = null; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_InitializedToOtherValue() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = GetCallback(); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_NoInitializer() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultLiteral() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = default; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }", // 7.1 is required for default literals, so 7.2 should be sufficient // and is used in other tests new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = default(Func<int, int>); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression_var() { await TestInRegularAndScript1Async( @"using System; class C { void M() { var [||]fibonacci = default(Func<int, int>); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_AnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = v => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> {|FixAllInDocument:fibonacci|} = v => { Func<bool, bool> isTrue = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> fibonacci = v => { Func<bool, bool> {|FixAllInDocument:isTrue|} = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll3() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> fibonacci = null; fibonacci = v => { Func<bool, bool> {|FixAllInDocument:isTrue|} = null; isTrue = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll4() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> {|FixAllInDocument:fibonacci|} = null; fibonacci = v => { Func<int, int> fibonacciHelper = null; fibonacciHelper = n => fibonacci.Invoke(n - 1) + fibonacci(arg: n - 2); return fibonacciHelper(v); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { int fibonacciHelper(int n) => fibonacci(n - 1) + fibonacci(v: n - 2); return fibonacciHelper(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestTrivia() { await TestInRegularAndScript1Async( @"using System; class C { void M() { // Leading trivia Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; // Trailing trivia } }", @"using System; class C { void M() { // Leading trivia static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } // Trailing trivia } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestInWithParameters() { await TestInRegularAndScript1Async( @" delegate void D(in int p); class C { void M() { D [||]lambda = (in int p) => throw null; } }", @" delegate void D(in int p); class C { void M() { void lambda(in int p) => throw null; } }", // Run with 7.2 to get read-only references new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestRefReadOnlyWithReturnType() { await TestInRegularAndScript1Async( @" delegate ref readonly int D(); class C { void M() { D [||]lambda = () => throw null; } }", @" delegate ref readonly int D(); class C { void M() { static ref readonly int lambda() => throw null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestMissingIfConvertedToNonDelegate() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task> [||]f = x => { return Task.CompletedTask; }; Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(object expected, object actual) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToDelegate() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task> [||]f = x => { return Task.CompletedTask; }; Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(Func<string, Task> expected, object actual) { } }", @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { static Task f(string x) { return Task.CompletedTask; } Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(Func<string, Task> expected, object actual) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestNotAvailableIfConvertedToSystemDelegate() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Delegate expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestNotAvailableIfConvertedToSystemMulticastDelegate() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(MulticastDelegate expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate0() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Func<object, string> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(object x) => """"; M(f); } public static void M(Func<object, string> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(object x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<string, string> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(string x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate3() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, object> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static object f(object x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfAdded() { await TestMissingAsync( @"using System; using System.Linq.Expressions; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; var doubleDelegate = local + local; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfUsedInMemberAccess1() { await TestMissingAsync( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; var str = local.ToString(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestMissingIfUsedInMemberAccess2() { await TestMissingAsync( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate[||]local = x => x; Console.Write(local.Invoke(t)); var str = local.ToString(); local.Invoke(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfUsedInExpressionTree() { await TestMissingAsync( @"using System; using System.Linq.Expressions; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; Expression<Action> expression = () => local(null); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24344, "https://github.com/dotnet/roslyn/issues/24344")] public async Task TestMissingIfUsedInExpressionTree2() { await TestMissingAsync( @"using System; using System.Linq.Expressions; public class C { void Method(Action action) { } Expression<Action> Example() { Action [||]action = () => Method(null); return () => Method(action); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod1() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; local.Invoke(); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { static T local(T x = null) => x; local(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod2() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod3() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); var val = local.Invoke(t); local.Invoke(t); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); var val = local(t); local(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod4() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); var val = local.Invoke(t); local(t); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); var val = local(t); local(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] public async Task TestWithRecursiveInvokeMethod1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]local = null; local = () => local.Invoke(); } }", @"using System; class C { void M() { static void local() => local(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] public async Task TestWithRecursiveInvokeMethod2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]local = null; local = () => { local.Invoke(); } } }", @"using System; class C { void M() { static void local() { local(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364935495")] public async Task TestWithNestedInvokeMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string, string> [||]a = s => s; a.Invoke(a.Invoke(null)); } }", @"using System; class C { void M() { static string a(string s) => s; a(a(null)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNestedRecursiveInvokeMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string, string> [||]a = null; a = s => a.Invoke(a.Invoke(s)); } }", @"using System; class C { void M() { static string a(string s) => a(a(s)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDefaultParameter1() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = (s) => s; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364655480")] public async Task TestWithDefaultParameter2() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = (string s) => s; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDefaultParameter3() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = delegate (string s) { return s; }; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") { return s; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364764542")] public async Task TestWithUnmatchingParameterList1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]x = (a, b) => { }; } }", @"using System; class C { void M() { static void x(object a, object b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithUnmatchingParameterList2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]x = (string a, int b) => { }; } }", @"using System; class C { void M() { static void x(string a, int b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncLambdaExpression() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task> [||]f = async () => await Task.Yield(); } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task f() => await Task.Yield(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncAnonymousMethod() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task<int>> [||]f = async delegate () { return 0; }; } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task<int> f() { return 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithParameterlessAnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { EventHandler [||]handler = delegate { }; E += handler; } event EventHandler E; }", @"using System; class C { void M() { static void handler(object sender, EventArgs e) { } E += handler; } event EventHandler E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24764, "https://github.com/dotnet/roslyn/issues/24764")] public async Task TestWithNamedArguments1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2, a3) => { }; x(arg1: null, 0, 0); x.Invoke(arg1: null, 0, 0); } }", @"using System; class C { void M() { static void x(string a1, int a2, int a3) { } x(a1: null, 0, 0); x(a1: null, 0, 0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24764, "https://github.com/dotnet/roslyn/issues/24764")] public async Task TestWithNamedArguments2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2, a3) => { x(null, arg3: 0, arg2: 0); x.Invoke(null, arg3: 0, arg2: 0); }; } }", @"using System; class C { void M() { static void x(string a1, int a2, int a3) { x(null, a3: 0, a2: 0); x(null, a3: 0, a2: 0); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedArgumentsAndBrokenCode1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (int a1, string a2, string a3, a4) => { }; x(null, arg3: 0, arg2: 0, arg4: 0); x.Invoke(null, arg3: 0, arg2: 0, arg4: 0); x.Invoke(0, null, null, null, null, null); } }", @"using System; class C { void M() { static void x(int a1, string a2, string a3, object a4) { } x(null, a3: 0, a2: 0, arg4: 0); x(null, a3: 0, a2: 0, arg4: 0); x(0, null, null, null, null, null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedArgumentsAndBrokenCode2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2) => { x(null, arg3: 0, arg2: 0); x.Invoke(null, arg3: 0, arg2: 0); x.Invoke(); }; } }", @"using System; class C { void M() { static void x(string a1, int a2) { x(null, arg3: 0, a2: 0); x(null, arg3: 0, a2: 0); x(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedAndDefaultArguments() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { MyDelegate [||]x = null; x = (a1, a2, a3) => { x(null, arg3: 42); return x.Invoke(null, arg3: 42); }; } }", @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { static string x(string a1, int a2 = 2, int a3 = 3) { x(null, a3: 42); return x(null, a3: 42); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedAndDefaultArgumentsAndNestedRecursiveInvocations_FixAll() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { var x = (MyDelegate)delegate { MyDelegate {|FixAllInDocument:a|} = null; a = (string a1, int a2, int a3) => { MyDelegate b = null; b = (b1, b2, b3) => b.Invoke(arg1: b(null), arg2: a(arg1: a.Invoke(null)).Length, arg3: 42) + b(arg1: b.Invoke(null), arg3: a(arg1: a.Invoke(null)).Length, arg2: 42); return b(arg1: a1, b(arg1: a1).Length); }; return a(arg1: null); }; x(arg1: null); } }", @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { string x(string arg1, int arg2 = 2, int arg3 = 3) { string a(string a1, int a2 = 2, int a3 = 3) { string b(string b1, int b2 = 2, int b3 = 3) => b(b1: b(null), b2: a(a1: a(null)).Length, b3: 42) + b(b1: b(null), b3: a(a1: a(null)).Length, b2: 42); return b(b1: a1, b(b1: a1).Length); } return a(a1: null); } x(arg1: null); } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action [||]onUpdateSolutionCancel = () => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = async a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2MultiToken() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { Func<int, int[]> [||]onUpdateSolutionCancel = a => { return null; }; } }", @"using System; class C { void Goo() { static int[] onUpdateSolutionCancel(int a) { return null; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2MultiTokenAsync() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void Goo() { Func<int, Task<int[]>> [||]onUpdateSolutionCancel = async a => { return null; }; } }", @"using System; using System.Threading.Tasks; class C { void Goo() { static async Task<int[]> onUpdateSolutionCancel(int a) { return null; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine3() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = (int a) => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine4() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine4Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = async delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action)(() => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(a => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine2Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(async a => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine3() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)((int a) => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine4() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(delegate (int a) { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine4Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(async delegate (int a) { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine1() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = () => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine2() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine2Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = async a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine3() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = (int a) => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine4() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine4Async() { await TestInRegularAndScript1Async( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = async delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged1() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Class<T> { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged2() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Goo<T> { public class Class { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged3() { await TestMissingAsync( @"public class Class<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public void Caller() { void Some<T>(T t) { MyDelegate [||]local = x => x; Callee(local); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged4() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Goo<T> { public class Class<U> { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } } }"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/27950"), Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestAvailableIfTypeParameterNotChanged1() { await TestInRegularAndScript1Async( @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<T> : DelegateEnclosing<T> { static void Callee(MyDelegate d) => d(default); public void Caller() { MyDelegate [||]local = x => x; Callee(local); } }", @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<T> : DelegateEnclosing<T> { static void Callee(MyDelegate d) => d(default); public void Caller() { static T local(T x) => x; Callee(local); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestAvailableIfTypeParameterNotChanged2() { await TestInRegularAndScript1Async( @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<U> : DelegateEnclosing<U> { static void Callee(MyDelegate d) => d(default); public void Caller() { MyDelegate [||]local = x => x; Callee(local); } }", @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<U> : DelegateEnclosing<U> { static void Callee(MyDelegate d) => d(default); public void Caller() { static U local(U x) => x; Callee(local); } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedIfAssignedToVar() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string> [||]f = () => null; var f2 = f; } }", @"using System; class C { void M() { static string f() => null; var f2 = (Func<string>)f; } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForGenericTypeInference1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForGenericTypeInference2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } void Method(string o) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } void Method(string o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForOverloadResolution() { await TestInRegularAndScript1Async( @"using System; delegate string CustomDelegate(); class C { void M() { Func<string> [||]f = () => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }", @"using System; delegate string CustomDelegate(); class C { void M() { static string f() => null; Method((Func<string>)f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithoutCastIfUnnecessaryForOverloadResolution() { await TestInRegularAndScript1Async( @"using System; delegate string CustomDelegate(object arg); class C { void M() { Func<string> [||]f = () => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }", @"using System; delegate string CustomDelegate(object arg); class C { void M() { static string f() => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration() { await TestMissingAsync( @"using System; class C { void M() { Func<string> [||]f = () => null); Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration2() { await TestMissingAsync( @"using System; class C { void M() { Func<string> [||]f) = () => null; Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration3() { await TestMissingAsync( @"using System; class C { void M() { Func<string>) [||]f = () => null; Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithInvalidUnrelatedCode() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o)) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o)) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithInvalidUnrelatedCode2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; (Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { static string f(int _) => null; (Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithObsoleteCode() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => S(); Method(f); } [System.Obsolete] string S() { return null; } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { string f(int _) => S(); Method((Func<int, string>)f); } [System.Obsolete] string S() { return null; } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDeclarationWarning() { await TestInRegularAndScript1Async( @"using System; class C { void M() { #warning Declaration Warning Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { #warning Declaration Warning static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMakeStaticIfNoCaptures() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestDoNotMakeStaticIfCaptures() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { M(); if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { int fibonacci(int v) { M(); if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncLambdaExpression_MakeStatic() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task> [||]f = async () => await Task.Yield(); } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task f() => await Task.Yield(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNullableParameterAndReturn() { await TestInRegularAndScript1Async( @"#nullable enable using System; class Program { static void Main(string[] args) { Func<string?, string?> [||]f = s => s; } }", @"#nullable enable using System; class Program { static void Main(string[] args) { static string? f(string? s) => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDiscardParameters() { await TestInRegularAndScript1Async( @" class Program { static void Main(string[] args) { System.Func<int, string, int, long> [||]f = (_, _, a) => 1; } }", @" class Program { static void Main(string[] args) { static long f(int _, string _, int a) => 1; } }"); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Analyzers/CSharp/Tests/ValidateFormatString/ValidateFormatStringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.ValidateFormatString; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.ValidateFormatString; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ValidateFormatString { public class ValidateFormatStringTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ValidateFormatStringTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpValidateFormatStringDiagnosticAnalyzer(), null); private OptionsCollection OptionOff() => new OptionsCollection(GetLanguage()) { { ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, false }, }; private OptionsCollection OptionOn() => new OptionsCollection(GetLanguage()) { { ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, true }, }; [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task OnePlaceholder() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0[||]} works"", ""test""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task TwoPlaceholders() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0[||]} {1} works"", ""test"", ""also""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ThreePlaceholders() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0} {1[||]} works {2} "", ""test"", ""also"", ""well""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FourPlaceholders() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {1} is {2} my {6[||]} test "", ""teststring1"", ""teststring2"", ""teststring3"", ""teststring4"", ""teststring5"", ""teststring6"", ""teststring7""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ObjectArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { object[] objectArray = { 1.25, ""2"", ""teststring""}; string.Format(""This {0} {1} {2[||]} works"", objectArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task MultipleObjectArrays() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { object[] objectArray = { 1.25, ""2"", ""teststring""}; string.Format(""This {0} {1} {2[||]} works"", objectArray, objectArray, objectArray, objectArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IntArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2, 3}; string.Format(""This {0[||]} works"", intArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task StringArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string[] stringArray = {""test1"", ""test2"", ""test3""}; string.Format(""This {0} {1} {2[||]} works"", stringArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task LiteralArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0[||]} {1} {2} {3} works"", new [] {""test1"", ""test2"", ""test3"", ""test4""}); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task StringArrayOutOfBounds_NoDiagnostic() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string[] stringArray = {""test1"", ""test2""}; string.Format(""This {0} {1} {2[||]} works"", stringArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndOnePlaceholder() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0[||]:C2} per ounce"", 2.45); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndTwoPlaceholders() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0[||]:C2} per {1} "", 2.45, ""ounce""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndThreePlaceholders() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0} {[||]1} {2} "", 2.45, ""per"", ""ounce""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndFourPlaceholders() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0} {1[||]} {2} {3} "", 2.45, ""per"", ""ounce"", ""today only""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndObjectArray() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { object[] objectArray = { 1.25, ""2"", ""teststring""}; string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This {0} {1} {[||]2} works"", objectArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithComma() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{0[||],6}"", 34); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithColon() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{[||]0:N0}"", 34); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithCommaAndColon() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""Test {0,[||]15:N0} output"", 34); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithPlaceholderAtBeginning() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{0[||]} is my test case"", ""This""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithPlaceholderAtEnd() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This is my {0[||]}"", ""test""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithDoubleBraces() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format("" {{ 2}} This {1[||]} is {2} {{ my {0} test }} "", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithDoubleBracesAtBeginning() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{{ 2}} This {1[||]} is {2} {{ my {0} test }} "", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithDoubleBracesAtEnd() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format("" {{ 2}} This {1[||]} is {2} {{ my {0} test }}"", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithTripleBraces() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format("" {{{2}} This {1[||]} is {2} {{ my {0} test }}"", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParameters() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(arg0: ""test"", arg1: ""also"", format: ""This {0} {[||]1} works""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParametersWithIFormatProvider() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(arg0: ""test"", provider: new CultureInfo(""pt-BR"", useUserOverride: false), format: ""This {0[||]} works""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamespaceAliasForStringClass() { await TestDiagnosticMissingAsync(@" using stringAlias = System.String; class Program { static void Main(string[] args) { stringAlias.Format(""This {0[||]} works"", ""test""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task MethodCallAsAnArgumentToAnotherMethod() { await TestDiagnosticMissingAsync(@" using System.IO; class Program { static void Main(string[] args) { Console.WriteLine(string.Format(format: ""This {0[||]} works"", arg0:""test"")); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task VerbatimMultipleLines() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(@""This {0} {1} {2[||]} works"", ""multiple"", ""line"", ""test"")); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task Interpolated() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { var Name = ""Peter""; var Age = 30; string.Format($""{Name,[||] 20} is {Age:D3} ""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task Empty() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""[||]""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task LeftParenOnly() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format([||]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ParenthesesOnly() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format([||]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task EmptyString() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""[||]""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FormatOnly_NoStringDot() { await TestDiagnosticMissingAsync(@" using static System.String class Program { static void Main(string[] args) { Format(""[||]""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParameters_BlankName() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format( : ""value""[||])); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task DuplicateNamedArgs() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(format:""This [||] "", format:"" test ""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task GenericIdentifier() { await TestDiagnosticMissingAsync(@"using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Generics_CSharp { public class String<T> { public void Format<T>(string teststr) { Console.WriteLine(teststr); } } class Generics { static void Main(string[] args) { String<int> testList = new String<int>(); testList.Format<int>(""Test[||]String""); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ClassNamedString() { await TestDiagnosticMissingAsync(@"using System; namespace System { public class String { public static String Format(string format, object arg0) { return new String(); } } } class C { static void Main(string[] args) { Console.WriteLine(String.Format(""test {[||]5} "", 1)); } } "); } #if CODE_STYLE [InlineData(false, true)] // Option has no effect on CodeStyle layer CI execution as it is not an editorconfig option. #else [InlineData(false, false)] #endif [InlineData(true, true)] [Theory, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task TestOption(bool optionOn, bool expectDiagnostic) { var source = @" class Program { static void Main(string[] args) { string.Format(""This [|{1}|] is my test"", ""teststring1""); } }"; var options = optionOn ? OptionOn() : OptionOff(); if (!expectDiagnostic) { await TestDiagnosticMissingAsync(source, new TestParameters(options: options)); } else { await TestDiagnosticInfoAsync(source, options, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task OnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This [|{1}|] is my test"", ""teststring1""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task TwoPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This [|{2}|] is my test"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ThreePlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This{0}{1}{2}[|{3}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FourPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This{0}{1}{2}{3}[|{4}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3"", ""teststring4""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task iFormatProviderAndOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This [|{1}|] is my test"", ""teststring1""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task iFormatProviderAndTwoPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This [|{2}|] is my test"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndThreePlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This{0}{1}{2}[|{3}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndFourPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This{0}{1}{2}{3}[|{4}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3"", ""teststring4""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task PlaceholderAtBeginningWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""[|{1}|]is my test"", ""teststring1""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task PlaceholderAtEndWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""is my test [|{2}|]"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task DoubleBracesAtBeginningWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""}}is my test [|{2}|]"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task DoubleBracesAtEndWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""is my test [|{2}|]{{"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParametersOneOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(arg0: ""test"", arg1: ""also"", format: ""This {0} [|{2}|] works""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParametersWithIFormatProviderOneOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(arg0: ""test"", arg1: ""also"", format: ""This {0} [|{2}|] works"", provider: new CultureInfo(""pt-BR"", useUserOverride: false)) } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FormatOnly_NoStringDot_OneOutOfBounds() { await TestDiagnosticInfoAsync(@" using static System.String class Program { static void Main(string[] args) { Format(""This {0} [|{2}|] squiggles"", ""test"", ""gets""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task Net45TestOutOfBounds() { var input = @" < Workspace > < Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferencesNet45=""true""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System.Globalization; class Program { static void Main(string[] args) { string.Format(""This [|{1}|] is my test"", ""teststring1""); } } ]]> </Document> </Project> </Workspace>"; await TestDiagnosticInfoAsync(input, options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task VerbatimMultipleLinesPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(@""This {0} {1} [|{3}|] works"", ""multiple"", ""line"", ""test"")); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IntArrayOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} [|{1}|] {2} works"", intArray); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FirstPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} [|{1}|] {2} works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task SecondPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} {1} [|{2}|] works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FirstOfMultipleSameNamedPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} [|{2}|] {2} works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task SecondOfMultipleSameNamedPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} {2} [|{2}|] works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task EmptyPlaceholder() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This [|{}|] "", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [WorkItem(29398, "https://github.com/dotnet/roslyn/issues/29398")] [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task LocalFunctionNamedFormat() { await TestDiagnosticMissingAsync(@"public class C { public void M() { Forma[||]t(); void Format() { } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.ValidateFormatString; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.ValidateFormatString; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ValidateFormatString { public class ValidateFormatStringTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ValidateFormatStringTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpValidateFormatStringDiagnosticAnalyzer(), null); private OptionsCollection OptionOff() => new OptionsCollection(GetLanguage()) { { ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, false }, }; private OptionsCollection OptionOn() => new OptionsCollection(GetLanguage()) { { ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, true }, }; [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task OnePlaceholder() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0[||]} works"", ""test""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task TwoPlaceholders() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0[||]} {1} works"", ""test"", ""also""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ThreePlaceholders() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0} {1[||]} works {2} "", ""test"", ""also"", ""well""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FourPlaceholders() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {1} is {2} my {6[||]} test "", ""teststring1"", ""teststring2"", ""teststring3"", ""teststring4"", ""teststring5"", ""teststring6"", ""teststring7""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ObjectArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { object[] objectArray = { 1.25, ""2"", ""teststring""}; string.Format(""This {0} {1} {2[||]} works"", objectArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task MultipleObjectArrays() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { object[] objectArray = { 1.25, ""2"", ""teststring""}; string.Format(""This {0} {1} {2[||]} works"", objectArray, objectArray, objectArray, objectArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IntArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2, 3}; string.Format(""This {0[||]} works"", intArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task StringArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string[] stringArray = {""test1"", ""test2"", ""test3""}; string.Format(""This {0} {1} {2[||]} works"", stringArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task LiteralArray() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This {0[||]} {1} {2} {3} works"", new [] {""test1"", ""test2"", ""test3"", ""test4""}); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task StringArrayOutOfBounds_NoDiagnostic() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string[] stringArray = {""test1"", ""test2""}; string.Format(""This {0} {1} {2[||]} works"", stringArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndOnePlaceholder() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0[||]:C2} per ounce"", 2.45); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndTwoPlaceholders() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0[||]:C2} per {1} "", 2.45, ""ounce""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndThreePlaceholders() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0} {[||]1} {2} "", 2.45, ""per"", ""ounce""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndFourPlaceholders() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { testStr = string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""The current price is {0} {1[||]} {2} {3} "", 2.45, ""per"", ""ounce"", ""today only""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndObjectArray() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { object[] objectArray = { 1.25, ""2"", ""teststring""}; string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This {0} {1} {[||]2} works"", objectArray); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithComma() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{0[||],6}"", 34); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithColon() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{[||]0:N0}"", 34); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithCommaAndColon() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""Test {0,[||]15:N0} output"", 34); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithPlaceholderAtBeginning() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{0[||]} is my test case"", ""This""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithPlaceholderAtEnd() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""This is my {0[||]}"", ""test""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithDoubleBraces() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format("" {{ 2}} This {1[||]} is {2} {{ my {0} test }} "", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithDoubleBracesAtBeginning() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""{{ 2}} This {1[||]} is {2} {{ my {0} test }} "", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithDoubleBracesAtEnd() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format("" {{ 2}} This {1[||]} is {2} {{ my {0} test }}"", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task WithTripleBraces() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format("" {{{2}} This {1[||]} is {2} {{ my {0} test }}"", ""teststring1"", ""teststring2"", ""teststring3""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParameters() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(arg0: ""test"", arg1: ""also"", format: ""This {0} {[||]1} works""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParametersWithIFormatProvider() { await TestDiagnosticMissingAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(arg0: ""test"", provider: new CultureInfo(""pt-BR"", useUserOverride: false), format: ""This {0[||]} works""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamespaceAliasForStringClass() { await TestDiagnosticMissingAsync(@" using stringAlias = System.String; class Program { static void Main(string[] args) { stringAlias.Format(""This {0[||]} works"", ""test""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task MethodCallAsAnArgumentToAnotherMethod() { await TestDiagnosticMissingAsync(@" using System.IO; class Program { static void Main(string[] args) { Console.WriteLine(string.Format(format: ""This {0[||]} works"", arg0:""test"")); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task VerbatimMultipleLines() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(@""This {0} {1} {2[||]} works"", ""multiple"", ""line"", ""test"")); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task Interpolated() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { var Name = ""Peter""; var Age = 30; string.Format($""{Name,[||] 20} is {Age:D3} ""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task Empty() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""[||]""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task LeftParenOnly() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format([||]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ParenthesesOnly() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format([||]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task EmptyString() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(""[||]""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FormatOnly_NoStringDot() { await TestDiagnosticMissingAsync(@" using static System.String class Program { static void Main(string[] args) { Format(""[||]""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParameters_BlankName() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format( : ""value""[||])); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task DuplicateNamedArgs() { await TestDiagnosticMissingAsync(@" class Program { static void Main(string[] args) { string.Format(format:""This [||] "", format:"" test ""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task GenericIdentifier() { await TestDiagnosticMissingAsync(@"using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Generics_CSharp { public class String<T> { public void Format<T>(string teststr) { Console.WriteLine(teststr); } } class Generics { static void Main(string[] args) { String<int> testList = new String<int>(); testList.Format<int>(""Test[||]String""); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ClassNamedString() { await TestDiagnosticMissingAsync(@"using System; namespace System { public class String { public static String Format(string format, object arg0) { return new String(); } } } class C { static void Main(string[] args) { Console.WriteLine(String.Format(""test {[||]5} "", 1)); } } "); } #if CODE_STYLE [InlineData(false, true)] // Option has no effect on CodeStyle layer CI execution as it is not an editorconfig option. #else [InlineData(false, false)] #endif [InlineData(true, true)] [Theory, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task TestOption(bool optionOn, bool expectDiagnostic) { var source = @" class Program { static void Main(string[] args) { string.Format(""This [|{1}|] is my test"", ""teststring1""); } }"; var options = optionOn ? OptionOn() : OptionOff(); if (!expectDiagnostic) { await TestDiagnosticMissingAsync(source, new TestParameters(options: options)); } else { await TestDiagnosticInfoAsync(source, options, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task OnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This [|{1}|] is my test"", ""teststring1""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task TwoPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This [|{2}|] is my test"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task ThreePlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This{0}{1}{2}[|{3}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FourPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(""This{0}{1}{2}{3}[|{4}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3"", ""teststring4""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task iFormatProviderAndOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This [|{1}|] is my test"", ""teststring1""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task iFormatProviderAndTwoPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This [|{2}|] is my test"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndThreePlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This{0}{1}{2}[|{3}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IFormatProviderAndFourPlaceholdersWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(new CultureInfo(""pt-BR"", useUserOverride: false), ""This{0}{1}{2}{3}[|{4}|] is my test"", ""teststring1"", ""teststring2"", ""teststring3"", ""teststring4""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task PlaceholderAtBeginningWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""[|{1}|]is my test"", ""teststring1""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task PlaceholderAtEndWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""is my test [|{2}|]"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task DoubleBracesAtBeginningWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""}}is my test [|{2}|]"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task DoubleBracesAtEndWithOnePlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format( ""is my test [|{2}|]{{"", ""teststring1"", ""teststring2""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParametersOneOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(arg0: ""test"", arg1: ""also"", format: ""This {0} [|{2}|] works""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task NamedParametersWithIFormatProviderOneOutOfBounds() { await TestDiagnosticInfoAsync(@" using System.Globalization; class Program { static void Main(string[] args) { string.Format(arg0: ""test"", arg1: ""also"", format: ""This {0} [|{2}|] works"", provider: new CultureInfo(""pt-BR"", useUserOverride: false)) } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FormatOnly_NoStringDot_OneOutOfBounds() { await TestDiagnosticInfoAsync(@" using static System.String class Program { static void Main(string[] args) { Format(""This {0} [|{2}|] squiggles"", ""test"", ""gets""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task Net45TestOutOfBounds() { var input = @" < Workspace > < Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferencesNet45=""true""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System.Globalization; class Program { static void Main(string[] args) { string.Format(""This [|{1}|] is my test"", ""teststring1""); } } ]]> </Document> </Project> </Workspace>"; await TestDiagnosticInfoAsync(input, options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task VerbatimMultipleLinesPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { string.Format(@""This {0} {1} [|{3}|] works"", ""multiple"", ""line"", ""test"")); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task IntArrayOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} [|{1}|] {2} works"", intArray); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FirstPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} [|{1}|] {2} works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task SecondPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} {1} [|{2}|] works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task FirstOfMultipleSameNamedPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} [|{2}|] {2} works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task SecondOfMultipleSameNamedPlaceholderOutOfBounds() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This {0} {2} [|{2}|] works"", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task EmptyPlaceholder() { await TestDiagnosticInfoAsync(@" class Program { static void Main(string[] args) { int[] intArray = {1, 2}; string.Format(""This [|{}|] "", ""TestString""); } }", options: null, diagnosticId: IDEDiagnosticIds.ValidateFormatStringDiagnosticID, diagnosticSeverity: DiagnosticSeverity.Info, diagnosticMessage: AnalyzersResources.Format_string_contains_invalid_placeholder); } [WorkItem(29398, "https://github.com/dotnet/roslyn/issues/29398")] [Fact, Trait(Traits.Feature, Traits.Features.ValidateFormatString)] public async Task LocalFunctionNamedFormat() { await TestDiagnosticMissingAsync(@"public class C { public void M() { Forma[||]t(); void Format() { } } }"); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceParameterCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.IntroduceVariable; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.IntroduceParameter), Shared] internal partial class CSharpIntroduceParameterCodeRefactoringProvider : AbstractIntroduceParameterService< ExpressionSyntax, InvocationExpressionSyntax, ObjectCreationExpressionSyntax, IdentifierNameSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpIntroduceParameterCodeRefactoringProvider() { } protected override SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol) { return ExpressionGenerator.GenerateExpression(parameterSymbol.Type, parameterSymbol.ExplicitDefaultValue, canUseFieldReference: true); } protected override SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl) { return variableDecl.Parent?.Parent as LocalDeclarationStatementSyntax; } protected override bool IsDestructor(IMethodSymbol methodSymbol) { return false; } protected override SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments) => ((ArgumentListSyntax)argumentList).WithArguments(arguments); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.IntroduceVariable; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.IntroduceParameter), Shared] internal partial class CSharpIntroduceParameterCodeRefactoringProvider : AbstractIntroduceParameterService< ExpressionSyntax, InvocationExpressionSyntax, ObjectCreationExpressionSyntax, IdentifierNameSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpIntroduceParameterCodeRefactoringProvider() { } protected override SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol) { return ExpressionGenerator.GenerateExpression(parameterSymbol.Type, parameterSymbol.ExplicitDefaultValue, canUseFieldReference: true); } protected override SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl) { return variableDecl.Parent?.Parent as LocalDeclarationStatementSyntax; } protected override bool IsDestructor(IMethodSymbol methodSymbol) { return false; } protected override SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments) => ((ArgumentListSyntax)argumentList).WithArguments(arguments); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/CodeFixes/AddExplicitCast/InheritanceDistanceComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CodeFixes.AddExplicitCast { /// <summary> /// The item is the pair of target argument expression and its conversion type /// <para/> /// Sort pairs using conversion types by inheritance distance from the base type in ascending order, /// i.e., less specific type has higher priority because it has less probability to make mistakes /// <para/> /// For example: /// class Base { } /// class Derived1 : Base { } /// class Derived2 : Derived1 { } /// /// void Foo(Derived1 d1) { } /// void Foo(Derived2 d2) { } /// /// Base b = new Derived1(); /// Foo([||]b); /// /// operations: /// 1. Convert type to 'Derived1' /// 2. Convert type to 'Derived2' /// /// 'Derived1' is less specific than 'Derived2' compared to 'Base' /// </summary> internal sealed class InheritanceDistanceComparer<TExpressionSyntax> : IComparer<(TExpressionSyntax syntax, ITypeSymbol symbol)> where TExpressionSyntax : SyntaxNode { private readonly SemanticModel _semanticModel; public InheritanceDistanceComparer(SemanticModel semanticModel) { _semanticModel = semanticModel; } public int Compare((TExpressionSyntax syntax, ITypeSymbol symbol) x, (TExpressionSyntax syntax, ITypeSymbol symbol) y) { // if the argument is different, keep the original order if (!x.syntax.Equals(y.syntax)) { return 0; } else { var baseType = _semanticModel.GetTypeInfo(x.syntax).Type; var xDist = GetInheritanceDistance(baseType, x.symbol); var yDist = GetInheritanceDistance(baseType, y.symbol); return xDist.CompareTo(yDist); } } /// <summary> /// Calculate the inheritance distance between baseType and derivedType. /// </summary> private int GetInheritanceDistanceRecursive(ITypeSymbol baseType, ITypeSymbol? derivedType) { if (derivedType == null) return int.MaxValue; if (derivedType.Equals(baseType)) return 0; var distance = GetInheritanceDistanceRecursive(baseType, derivedType.BaseType); if (derivedType.Interfaces.Length != 0) { foreach (var interfaceType in derivedType.Interfaces) { distance = Math.Min(GetInheritanceDistanceRecursive(baseType, interfaceType), distance); } } return distance == int.MaxValue ? distance : distance + 1; } /// <summary> /// Wrapper function of [GetInheritanceDistance], also consider the class with explicit conversion operator /// has the highest priority. /// </summary> private int GetInheritanceDistance(ITypeSymbol? baseType, ITypeSymbol castType) { if (baseType is null) return 0; var conversion = _semanticModel.Compilation.ClassifyCommonConversion(baseType, castType); // If the node has the explicit conversion operator, then it has the shortest distance // since explicit conversion operator is defined by users and has the highest priority var distance = conversion.IsUserDefined ? 0 : GetInheritanceDistanceRecursive(baseType, castType); return distance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CodeFixes.AddExplicitCast { /// <summary> /// The item is the pair of target argument expression and its conversion type /// <para/> /// Sort pairs using conversion types by inheritance distance from the base type in ascending order, /// i.e., less specific type has higher priority because it has less probability to make mistakes /// <para/> /// For example: /// class Base { } /// class Derived1 : Base { } /// class Derived2 : Derived1 { } /// /// void Foo(Derived1 d1) { } /// void Foo(Derived2 d2) { } /// /// Base b = new Derived1(); /// Foo([||]b); /// /// operations: /// 1. Convert type to 'Derived1' /// 2. Convert type to 'Derived2' /// /// 'Derived1' is less specific than 'Derived2' compared to 'Base' /// </summary> internal sealed class InheritanceDistanceComparer<TExpressionSyntax> : IComparer<(TExpressionSyntax syntax, ITypeSymbol symbol)> where TExpressionSyntax : SyntaxNode { private readonly SemanticModel _semanticModel; public InheritanceDistanceComparer(SemanticModel semanticModel) { _semanticModel = semanticModel; } public int Compare((TExpressionSyntax syntax, ITypeSymbol symbol) x, (TExpressionSyntax syntax, ITypeSymbol symbol) y) { // if the argument is different, keep the original order if (!x.syntax.Equals(y.syntax)) { return 0; } else { var baseType = _semanticModel.GetTypeInfo(x.syntax).Type; var xDist = GetInheritanceDistance(baseType, x.symbol); var yDist = GetInheritanceDistance(baseType, y.symbol); return xDist.CompareTo(yDist); } } /// <summary> /// Calculate the inheritance distance between baseType and derivedType. /// </summary> private int GetInheritanceDistanceRecursive(ITypeSymbol baseType, ITypeSymbol? derivedType) { if (derivedType == null) return int.MaxValue; if (derivedType.Equals(baseType)) return 0; var distance = GetInheritanceDistanceRecursive(baseType, derivedType.BaseType); if (derivedType.Interfaces.Length != 0) { foreach (var interfaceType in derivedType.Interfaces) { distance = Math.Min(GetInheritanceDistanceRecursive(baseType, interfaceType), distance); } } return distance == int.MaxValue ? distance : distance + 1; } /// <summary> /// Wrapper function of [GetInheritanceDistance], also consider the class with explicit conversion operator /// has the highest priority. /// </summary> private int GetInheritanceDistance(ITypeSymbol? baseType, ITypeSymbol castType) { if (baseType is null) return 0; var conversion = _semanticModel.Compilation.ClassifyCommonConversion(baseType, castType); // If the node has the explicit conversion operator, then it has the shortest distance // since explicit conversion operator is defined by users and has the highest priority var distance = conversion.IsUserDefined ? 0 : GetInheritanceDistanceRecursive(baseType, castType); return distance; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpCommandLineParserService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ICommandLineParserService), LanguageNames.CSharp), Shared] internal sealed class CSharpCommandLineParserService : ICommandLineParserService { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpCommandLineParserService() { } public CommandLineArguments Parse(IEnumerable<string> arguments, string baseDirectory, bool isInteractive, string sdkDirectory) { #if SCRIPTING var parser = isInteractive ? CSharpCommandLineParser.Interactive : CSharpCommandLineParser.Default; #else var parser = CSharpCommandLineParser.Default; #endif return parser.Parse(arguments, baseDirectory, sdkDirectory); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ICommandLineParserService), LanguageNames.CSharp), Shared] internal sealed class CSharpCommandLineParserService : ICommandLineParserService { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpCommandLineParserService() { } public CommandLineArguments Parse(IEnumerable<string> arguments, string baseDirectory, bool isInteractive, string sdkDirectory) { #if SCRIPTING var parser = isInteractive ? CSharpCommandLineParser.Interactive : CSharpCommandLineParser.Default; #else var parser = CSharpCommandLineParser.Default; #endif return parser.Parse(arguments, baseDirectory, sdkDirectory); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/IntegrationTest/TestUtilities/LightBulbHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { public static class LightBulbHelper { public static Task<bool> WaitForLightBulbSessionAsync(ILightBulbBroker broker, IWpfTextView view) { var startTime = DateTimeOffset.Now; return Helper.RetryAsync(async () => { if (broker.IsLightBulbSessionActive(view)) { return true; } if (DateTimeOffset.Now > startTime + Helper.HangMitigatingTimeout) { throw new InvalidOperationException("Expected a light bulb session to appear."); } // checking whether there is any suggested action is async up to editor layer and our waiter doesn't track up to that point. // so here, we have no other way than sleep (with timeout) to see LB is available. await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(true); return broker.IsLightBulbSessionActive(view); }, TimeSpan.Zero); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { public static class LightBulbHelper { public static Task<bool> WaitForLightBulbSessionAsync(ILightBulbBroker broker, IWpfTextView view) { var startTime = DateTimeOffset.Now; return Helper.RetryAsync(async () => { if (broker.IsLightBulbSessionActive(view)) { return true; } if (DateTimeOffset.Now > startTime + Helper.HangMitigatingTimeout) { throw new InvalidOperationException("Expected a light bulb session to appear."); } // checking whether there is any suggested action is async up to editor layer and our waiter doesn't track up to that point. // so here, we have no other way than sleep (with timeout) to see LB is available. await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(true); return broker.IsLightBulbSessionActive(view); }, TimeSpan.Zero); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/Core/Portable/CodeActions/Annotations/NavigationAnnotation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Apply this annotation to an appropriate Syntax element to request that it should be /// navigated to by the user after a code action is applied. If present the host should /// try to place the user's caret at the beginning of the element. /// </summary> /// <remarks> /// By using a <see cref="SyntaxAnnotation"/> this navigation location will be resilient /// to the transformations performed by the <see cref="CodeAction"/> infrastructure. /// Namely it will be resilient to the formatting, reduction or case correction that /// automatically occures. This allows a code action to specify a desired location for /// the user caret to be placed without knowing what actual position that location will /// end up at when the action is finally applied. /// </remarks> internal static class NavigationAnnotation { public const string Kind = "CodeAction_Navigation"; public static SyntaxAnnotation Create() => new(Kind); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Apply this annotation to an appropriate Syntax element to request that it should be /// navigated to by the user after a code action is applied. If present the host should /// try to place the user's caret at the beginning of the element. /// </summary> /// <remarks> /// By using a <see cref="SyntaxAnnotation"/> this navigation location will be resilient /// to the transformations performed by the <see cref="CodeAction"/> infrastructure. /// Namely it will be resilient to the formatting, reduction or case correction that /// automatically occures. This allows a code action to specify a desired location for /// the user caret to be placed without knowing what actual position that location will /// end up at when the action is finally applied. /// </remarks> internal static class NavigationAnnotation { public const string Kind = "CodeAction_Navigation"; public static SyntaxAnnotation Create() => new(Kind); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/CSharp/Portable/ExtractMethod/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal static class Extensions { [return: NotNullIfNotNull("node")] public static ExpressionSyntax? GetUnparenthesizedExpression(this ExpressionSyntax? node) { if (!(node is ParenthesizedExpressionSyntax parenthesizedExpression)) { return node; } return GetUnparenthesizedExpression(parenthesizedExpression.Expression); } public static StatementSyntax? GetStatementUnderContainer(this SyntaxNode node) { Contract.ThrowIfNull(node); for (var current = node; current is object; current = current.Parent) { if (current.Parent != null && current.Parent.IsStatementContainerNode()) { return current as StatementSyntax; } } return null; } public static StatementSyntax GetParentLabeledStatementIfPossible(this SyntaxNode node) => (StatementSyntax)((node.Parent is LabeledStatementSyntax) ? node.Parent : node); public static bool IsStatementContainerNode([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node is BlockSyntax || node is SwitchSectionSyntax; public static BlockSyntax? GetBlockBody(this SyntaxNode? node) { switch (node) { case BaseMethodDeclarationSyntax m: return m.Body; case AccessorDeclarationSyntax a: return a.Body; case SimpleLambdaExpressionSyntax s: return s.Body as BlockSyntax; case ParenthesizedLambdaExpressionSyntax p: return p.Body as BlockSyntax; case AnonymousMethodExpressionSyntax a: return a.Block; default: return null; } } public static bool UnderValidContext(this SyntaxNode node) { Contract.ThrowIfNull(node); if (!node.GetAncestorsOrThis<SyntaxNode>().Any(predicate)) { return false; } if (node.FromScript() || node.GetAncestor<TypeDeclarationSyntax>() != null) { return true; } return false; bool predicate(SyntaxNode n) { if (n is BaseMethodDeclarationSyntax or AccessorDeclarationSyntax or BlockSyntax or GlobalStatementSyntax) { return true; } if (n is ConstructorInitializerSyntax constructorInitializer) { return constructorInitializer.ContainsInArgument(node.Span); } return false; } } public static bool ContainedInValidType(this SyntaxNode node) { Contract.ThrowIfNull(node); foreach (var ancestor in node.AncestorsAndSelf()) { if (ancestor is TypeDeclarationSyntax) { return true; } if (ancestor is NamespaceDeclarationSyntax) { return false; } } return true; } public static bool UnderValidContext(this SyntaxToken token) => token.GetAncestors<SyntaxNode>().Any(n => n.CheckTopLevel(token.Span)); public static bool PartOfConstantInitializerExpression(this SyntaxNode node) { return node.PartOfConstantInitializerExpression<FieldDeclarationSyntax>(n => n.Modifiers) || node.PartOfConstantInitializerExpression<LocalDeclarationStatementSyntax>(n => n.Modifiers); } private static bool PartOfConstantInitializerExpression<T>(this SyntaxNode node, Func<T, SyntaxTokenList> modifiersGetter) where T : SyntaxNode { var decl = node.GetAncestor<T>(); if (decl == null) { return false; } if (!modifiersGetter(decl).Any(t => t.Kind() == SyntaxKind.ConstKeyword)) { return false; } // we are under decl with const modifier, check we are part of initializer expression var equal = node.GetAncestor<EqualsValueClauseSyntax>(); if (equal == null) { return false; } return equal.Value != null && equal.Value.Span.Contains(node.Span); } public static bool ContainArgumentlessThrowWithoutEnclosingCatch(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan) { foreach (var token in tokens) { if (token.Kind() != SyntaxKind.ThrowKeyword) { continue; } if (!(token.Parent is ThrowStatementSyntax throwStatement) || throwStatement.Expression != null) { continue; } var catchClause = token.GetAncestor<CatchClauseSyntax>(); if (catchClause == null || !textSpan.Contains(catchClause.Span)) { return true; } } return false; } public static bool ContainPreprocessorCrossOver(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan) { var activeRegions = 0; var activeIfs = 0; foreach (var trivia in tokens.GetAllTrivia()) { if (!textSpan.Contains(trivia.Span)) { continue; } switch (trivia.Kind()) { case SyntaxKind.RegionDirectiveTrivia: activeRegions++; break; case SyntaxKind.EndRegionDirectiveTrivia: if (activeRegions <= 0) { return true; } activeRegions--; break; case SyntaxKind.IfDirectiveTrivia: activeIfs++; break; case SyntaxKind.EndIfDirectiveTrivia: if (activeIfs <= 0) { return true; } activeIfs--; break; case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: if (activeIfs <= 0) { return true; } break; } } return activeIfs != 0 || activeRegions != 0; } public static IEnumerable<SyntaxTrivia> GetAllTrivia(this IEnumerable<SyntaxToken> tokens) { foreach (var token in tokens) { foreach (var trivia in token.LeadingTrivia) { yield return trivia; } foreach (var trivia in token.TrailingTrivia) { yield return trivia; } } } public static bool HasSyntaxAnnotation(this HashSet<SyntaxAnnotation> set, SyntaxNode node) => set.Any(a => node.GetAnnotatedNodesAndTokens(a).Any()); public static bool HasHybridTriviaBetween(this SyntaxToken token1, SyntaxToken token2) { if (token1.TrailingTrivia.Any(t => !t.IsElastic())) { return true; } if (token2.LeadingTrivia.Any(t => !t.IsElastic())) { return true; } return false; } public static bool IsArrayInitializer([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node is InitializerExpressionSyntax && node.Parent is EqualsValueClauseSyntax; public static bool IsExpressionInCast([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node is ExpressionSyntax && node.Parent is CastExpressionSyntax; public static bool IsObjectType(this ITypeSymbol? type) => type == null || type.SpecialType == SpecialType.System_Object; public static bool BetweenFieldAndNonFieldMember(this SyntaxToken token1, SyntaxToken token2) { if (token1.RawKind != (int)SyntaxKind.SemicolonToken || !(token1.Parent is FieldDeclarationSyntax)) { return false; } var field = token2.GetAncestor<FieldDeclarationSyntax>(); return field == null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal static class Extensions { [return: NotNullIfNotNull("node")] public static ExpressionSyntax? GetUnparenthesizedExpression(this ExpressionSyntax? node) { if (!(node is ParenthesizedExpressionSyntax parenthesizedExpression)) { return node; } return GetUnparenthesizedExpression(parenthesizedExpression.Expression); } public static StatementSyntax? GetStatementUnderContainer(this SyntaxNode node) { Contract.ThrowIfNull(node); for (var current = node; current is object; current = current.Parent) { if (current.Parent != null && current.Parent.IsStatementContainerNode()) { return current as StatementSyntax; } } return null; } public static StatementSyntax GetParentLabeledStatementIfPossible(this SyntaxNode node) => (StatementSyntax)((node.Parent is LabeledStatementSyntax) ? node.Parent : node); public static bool IsStatementContainerNode([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node is BlockSyntax || node is SwitchSectionSyntax; public static BlockSyntax? GetBlockBody(this SyntaxNode? node) { switch (node) { case BaseMethodDeclarationSyntax m: return m.Body; case AccessorDeclarationSyntax a: return a.Body; case SimpleLambdaExpressionSyntax s: return s.Body as BlockSyntax; case ParenthesizedLambdaExpressionSyntax p: return p.Body as BlockSyntax; case AnonymousMethodExpressionSyntax a: return a.Block; default: return null; } } public static bool UnderValidContext(this SyntaxNode node) { Contract.ThrowIfNull(node); if (!node.GetAncestorsOrThis<SyntaxNode>().Any(predicate)) { return false; } if (node.FromScript() || node.GetAncestor<TypeDeclarationSyntax>() != null) { return true; } return false; bool predicate(SyntaxNode n) { if (n is BaseMethodDeclarationSyntax or AccessorDeclarationSyntax or BlockSyntax or GlobalStatementSyntax) { return true; } if (n is ConstructorInitializerSyntax constructorInitializer) { return constructorInitializer.ContainsInArgument(node.Span); } return false; } } public static bool ContainedInValidType(this SyntaxNode node) { Contract.ThrowIfNull(node); foreach (var ancestor in node.AncestorsAndSelf()) { if (ancestor is TypeDeclarationSyntax) { return true; } if (ancestor is NamespaceDeclarationSyntax) { return false; } } return true; } public static bool UnderValidContext(this SyntaxToken token) => token.GetAncestors<SyntaxNode>().Any(n => n.CheckTopLevel(token.Span)); public static bool PartOfConstantInitializerExpression(this SyntaxNode node) { return node.PartOfConstantInitializerExpression<FieldDeclarationSyntax>(n => n.Modifiers) || node.PartOfConstantInitializerExpression<LocalDeclarationStatementSyntax>(n => n.Modifiers); } private static bool PartOfConstantInitializerExpression<T>(this SyntaxNode node, Func<T, SyntaxTokenList> modifiersGetter) where T : SyntaxNode { var decl = node.GetAncestor<T>(); if (decl == null) { return false; } if (!modifiersGetter(decl).Any(t => t.Kind() == SyntaxKind.ConstKeyword)) { return false; } // we are under decl with const modifier, check we are part of initializer expression var equal = node.GetAncestor<EqualsValueClauseSyntax>(); if (equal == null) { return false; } return equal.Value != null && equal.Value.Span.Contains(node.Span); } public static bool ContainArgumentlessThrowWithoutEnclosingCatch(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan) { foreach (var token in tokens) { if (token.Kind() != SyntaxKind.ThrowKeyword) { continue; } if (!(token.Parent is ThrowStatementSyntax throwStatement) || throwStatement.Expression != null) { continue; } var catchClause = token.GetAncestor<CatchClauseSyntax>(); if (catchClause == null || !textSpan.Contains(catchClause.Span)) { return true; } } return false; } public static bool ContainPreprocessorCrossOver(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan) { var activeRegions = 0; var activeIfs = 0; foreach (var trivia in tokens.GetAllTrivia()) { if (!textSpan.Contains(trivia.Span)) { continue; } switch (trivia.Kind()) { case SyntaxKind.RegionDirectiveTrivia: activeRegions++; break; case SyntaxKind.EndRegionDirectiveTrivia: if (activeRegions <= 0) { return true; } activeRegions--; break; case SyntaxKind.IfDirectiveTrivia: activeIfs++; break; case SyntaxKind.EndIfDirectiveTrivia: if (activeIfs <= 0) { return true; } activeIfs--; break; case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: if (activeIfs <= 0) { return true; } break; } } return activeIfs != 0 || activeRegions != 0; } public static IEnumerable<SyntaxTrivia> GetAllTrivia(this IEnumerable<SyntaxToken> tokens) { foreach (var token in tokens) { foreach (var trivia in token.LeadingTrivia) { yield return trivia; } foreach (var trivia in token.TrailingTrivia) { yield return trivia; } } } public static bool HasSyntaxAnnotation(this HashSet<SyntaxAnnotation> set, SyntaxNode node) => set.Any(a => node.GetAnnotatedNodesAndTokens(a).Any()); public static bool HasHybridTriviaBetween(this SyntaxToken token1, SyntaxToken token2) { if (token1.TrailingTrivia.Any(t => !t.IsElastic())) { return true; } if (token2.LeadingTrivia.Any(t => !t.IsElastic())) { return true; } return false; } public static bool IsArrayInitializer([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node is InitializerExpressionSyntax && node.Parent is EqualsValueClauseSyntax; public static bool IsExpressionInCast([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node is ExpressionSyntax && node.Parent is CastExpressionSyntax; public static bool IsObjectType(this ITypeSymbol? type) => type == null || type.SpecialType == SpecialType.System_Object; public static bool BetweenFieldAndNonFieldMember(this SyntaxToken token1, SyntaxToken token2) { if (token1.RawKind != (int)SyntaxKind.SemicolonToken || !(token1.Parent is FieldDeclarationSyntax)) { return false; } var field = token2.GetAncestor<FieldDeclarationSyntax>(); return field == null; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Test/Utilities/AsynchronousOperationListenerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class AsynchronousOperationListenerTests { /// <summary> /// A delay which is not expected to be reached in practice. /// </summary> private static readonly TimeSpan s_unexpectedDelay = TimeSpan.FromSeconds(60); private class SleepHelper : IDisposable { private readonly CancellationTokenSource _tokenSource; private readonly List<Task> _tasks = new List<Task>(); public SleepHelper() => _tokenSource = new CancellationTokenSource(); public void Dispose() { Task[] tasks; lock (_tasks) { _tokenSource.Cancel(); tasks = _tasks.ToArray(); } try { Task.WaitAll(tasks); } catch (AggregateException e) { foreach (var inner in e.InnerExceptions) { Assert.IsType<TaskCanceledException>(inner); } } GC.SuppressFinalize(this); } public void Sleep(TimeSpan timeToSleep) { Task task; lock (_tasks) { task = Task.Factory.StartNew(() => { while (true) { _tokenSource.Token.ThrowIfCancellationRequested(); Thread.Sleep(TimeSpan.FromMilliseconds(10)); } }, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); _tasks.Add(task); } task.Wait((int)timeToSleep.TotalMilliseconds); } } [Fact] public void Operation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromSeconds(1)); done = true; }); task.CompletesAsyncOperation(asyncToken); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "The operation should have completed"); } [Fact] public void QueuedOperation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); done = true; }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Should have waited for the queued operation to finish!"); } [Fact] public void Cancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var continued = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(s_unexpectedDelay); continued = true; }); asyncToken2.Dispose(); queuedTask.Start(TaskScheduler.Default); done = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Cancelling should have completed the current task."); Assert.False(continued, "Continued Task when it shouldn't have."); } [Fact] public void Nested() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var innerDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); using (listener.BeginAsyncOperation("Test")) { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); innerDone = true; } sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(innerDone, "Should have completed the inner task"); Assert.True(outerDone, "Should have completed the outer task"); } [Fact] public void MultipleEnqueues() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var firstQueuedDone = false; var secondQueuedDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var firstQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken3 = listener.BeginAsyncOperation("Test"); var secondQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondQueuedDone = true; }); secondQueueTask.CompletesAsyncOperation(asyncToken3); secondQueueTask.Start(TaskScheduler.Default); firstQueuedDone = true; }); firstQueueTask.CompletesAsyncOperation(asyncToken2); firstQueueTask.Start(TaskScheduler.Default); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(outerDone, "The outer task should have finished!"); Assert.True(firstQueuedDone, "The first queued task should have finished"); Assert.True(secondQueuedDone, "The second queued task should have finished"); } [Fact] public void IgnoredCancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = new TaskCompletionSource<VoidResult>(); var queuedFinished = new TaskCompletionSource<VoidResult>(); var cancelledFinished = new TaskCompletionSource<VoidResult>(); var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { using (listener.BeginAsyncOperation("Test")) { var cancelledTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromSeconds(10)); cancelledFinished.SetResult(default); }); signal.Set(); cancelledTask.Start(TaskScheduler.Default); } // Now that we've canceled the first request, queue another one to make sure we wait for it. var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { queuedFinished.SetResult(default); }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); done.SetResult(default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done.Task.IsCompleted, "Cancelling should have completed the current task."); Assert.True(queuedFinished.Task.IsCompleted, "Continued didn't run, but it was supposed to ignore the cancel."); Assert.False(cancelledFinished.Task.IsCompleted, "We waited for the cancelled task to finish."); } [Fact] public void SecondCompletion() { using var sleepHelper = new SleepHelper(); var signal1 = new ManualResetEventSlim(); var signal2 = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var firstDone = false; var secondDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var firstTask = Task.Factory.StartNew(() => { signal1.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); firstDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); firstTask.CompletesAsyncOperation(asyncToken1); firstTask.Wait(); var asyncToken2 = listener.BeginAsyncOperation("Test"); var secondTask = Task.Factory.StartNew(() => { signal2.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); secondTask.CompletesAsyncOperation(asyncToken2); // give it two signals since second one might not have started when WaitTask.Wait is called - race condition Wait(listener, signal1, signal2); Assert.True(firstDone, "First didn't finish"); Assert.True(secondDone, "Should have waited for the second task"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal1, ManualResetEventSlim signal2) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal1.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); Assert.True(signal2.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class AsynchronousOperationListenerTests { /// <summary> /// A delay which is not expected to be reached in practice. /// </summary> private static readonly TimeSpan s_unexpectedDelay = TimeSpan.FromSeconds(60); private class SleepHelper : IDisposable { private readonly CancellationTokenSource _tokenSource; private readonly List<Task> _tasks = new List<Task>(); public SleepHelper() => _tokenSource = new CancellationTokenSource(); public void Dispose() { Task[] tasks; lock (_tasks) { _tokenSource.Cancel(); tasks = _tasks.ToArray(); } try { Task.WaitAll(tasks); } catch (AggregateException e) { foreach (var inner in e.InnerExceptions) { Assert.IsType<TaskCanceledException>(inner); } } GC.SuppressFinalize(this); } public void Sleep(TimeSpan timeToSleep) { Task task; lock (_tasks) { task = Task.Factory.StartNew(() => { while (true) { _tokenSource.Token.ThrowIfCancellationRequested(); Thread.Sleep(TimeSpan.FromMilliseconds(10)); } }, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); _tasks.Add(task); } task.Wait((int)timeToSleep.TotalMilliseconds); } } [Fact] public void Operation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromSeconds(1)); done = true; }); task.CompletesAsyncOperation(asyncToken); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "The operation should have completed"); } [Fact] public void QueuedOperation() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); done = true; }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Should have waited for the queued operation to finish!"); } [Fact] public void Cancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = false; var continued = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(s_unexpectedDelay); continued = true; }); asyncToken2.Dispose(); queuedTask.Start(TaskScheduler.Default); done = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done, "Cancelling should have completed the current task."); Assert.False(continued, "Continued Task when it shouldn't have."); } [Fact] public void Nested() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var innerDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); using (listener.BeginAsyncOperation("Test")) { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); innerDone = true; } sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(innerDone, "Should have completed the inner task"); Assert.True(outerDone, "Should have completed the outer task"); } [Fact] public void MultipleEnqueues() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var outerDone = false; var firstQueuedDone = false; var secondQueuedDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var firstQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken3 = listener.BeginAsyncOperation("Test"); var secondQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondQueuedDone = true; }); secondQueueTask.CompletesAsyncOperation(asyncToken3); secondQueueTask.Start(TaskScheduler.Default); firstQueuedDone = true; }); firstQueueTask.CompletesAsyncOperation(asyncToken2); firstQueueTask.Start(TaskScheduler.Default); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(outerDone, "The outer task should have finished!"); Assert.True(firstQueuedDone, "The first queued task should have finished"); Assert.True(secondQueuedDone, "The second queued task should have finished"); } [Fact] public void IgnoredCancel() { using var sleepHelper = new SleepHelper(); var signal = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var done = new TaskCompletionSource<VoidResult>(); var queuedFinished = new TaskCompletionSource<VoidResult>(); var cancelledFinished = new TaskCompletionSource<VoidResult>(); var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { using (listener.BeginAsyncOperation("Test")) { var cancelledTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromSeconds(10)); cancelledFinished.SetResult(default); }); signal.Set(); cancelledTask.Start(TaskScheduler.Default); } // Now that we've canceled the first request, queue another one to make sure we wait for it. var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { queuedFinished.SetResult(default); }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(TaskScheduler.Default); done.SetResult(default); }); task.CompletesAsyncOperation(asyncToken1); task.Start(TaskScheduler.Default); Wait(listener, signal); Assert.True(done.Task.IsCompleted, "Cancelling should have completed the current task."); Assert.True(queuedFinished.Task.IsCompleted, "Continued didn't run, but it was supposed to ignore the cancel."); Assert.False(cancelledFinished.Task.IsCompleted, "We waited for the cancelled task to finish."); } [Fact] public void SecondCompletion() { using var sleepHelper = new SleepHelper(); var signal1 = new ManualResetEventSlim(); var signal2 = new ManualResetEventSlim(); var listener = new AsynchronousOperationListener(); var firstDone = false; var secondDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var firstTask = Task.Factory.StartNew(() => { signal1.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); firstDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); firstTask.CompletesAsyncOperation(asyncToken1); firstTask.Wait(); var asyncToken2 = listener.BeginAsyncOperation("Test"); var secondTask = Task.Factory.StartNew(() => { signal2.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); secondTask.CompletesAsyncOperation(asyncToken2); // give it two signals since second one might not have started when WaitTask.Wait is called - race condition Wait(listener, signal1, signal2); Assert.True(firstDone, "First didn't finish"); Assert.True(secondDone, "Should have waited for the second task"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } private static void Wait(AsynchronousOperationListener listener, ManualResetEventSlim signal1, ManualResetEventSlim signal2) { // Note: WaitTask will return immediately if there is no outstanding work. Due to // threadpool scheduling, we may get here before that other thread has started to run. // That's why each task set's a signal to say that it has begun and we first wait for // that, and then start waiting. Assert.True(signal1.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); Assert.True(signal2.Wait(s_unexpectedDelay), "Shouldn't have hit timeout waiting for task to begin"); var waitTask = listener.ExpeditedWaitAsync(); Assert.True(waitTask.Wait(s_unexpectedDelay), "Wait shouldn't have needed to timeout"); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Portable/Compiler/AnonymousTypeMethodBodySynthesizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // Object..ctor(); // this.backingField_1 = arg1; // ... // this.backingField_N = argN; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); int paramCount = this.ParameterCount; // List of statements BoundStatement[] statements = new BoundStatement[paramCount + 2]; int statementIndex = 0; // explicit base constructor call Debug.Assert(ContainingType.BaseTypeNoUseSiteDiagnostics.SpecialType == SpecialType.System_Object); BoundExpression call = MethodCompiler.GenerateBaseParameterlessConstructorInitializer(this, diagnostics); if (call == null) { // This may happen if Object..ctor is not found or is inaccessible return; } statements[statementIndex++] = F.ExpressionStatement(call); if (paramCount > 0) { AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; Debug.Assert(anonymousType.Properties.Length == paramCount); // Assign fields for (int index = 0; index < this.ParameterCount; index++) { // Generate 'field' = 'parameter' statement statements[statementIndex++] = F.Assignment(F.Field(F.This(), anonymousType.Properties[index].BackingField), F.Parameter(_parameters[index])); } } // Final return statement statements[statementIndex++] = F.Return(); // Create a bound block F.CloseMethod(F.Block(statements)); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // return this.backingField; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); F.CloseMethod(F.Block(F.Return(F.Field(F.This(), _property.BackingField)))); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypeEqualsMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // $anonymous$ local = value as $anonymous$; // return (object)local == this || (local != null // && System.Collections.Generic.EqualityComparer<T_1>.Default.Equals(this.backingFld_1, local.backingFld_1) // ... // && System.Collections.Generic.EqualityComparer<T_N>.Default.Equals(this.backingFld_N, local.backingFld_N)); // } // Type and type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // local BoundAssignmentOperator assignmentToTemp; BoundLocal boundLocal = F.StoreToTemp(F.As(F.Parameter(_parameters[0]), anonymousType), out assignmentToTemp); // Generate: statement <= 'local = value as $anonymous$' BoundStatement assignment = F.ExpressionStatement(assignmentToTemp); // Generate expression for return statement // retExpression <= 'local != null' BoundExpression retExpression = F.Binary(BinaryOperatorKind.ObjectNotEqual, manager.System_Boolean, F.Convert(manager.System_Object, boundLocal), F.Null(manager.System_Object)); // Compare fields if (anonymousType.Properties.Length > 0) { var fields = ArrayBuilder<FieldSymbol>.GetInstance(anonymousType.Properties.Length); foreach (var prop in anonymousType.Properties) { fields.Add(prop.BackingField); } retExpression = MethodBodySynthesizer.GenerateFieldEquals(retExpression, boundLocal, fields, F); fields.Free(); } // Compare references retExpression = F.LogicalOr(F.ObjectEqual(F.This(), boundLocal), retExpression); // Final return statement BoundStatement retStatement = F.Return(retExpression); // Create a bound block F.CloseMethod(F.Block(ImmutableArray.Create<LocalSymbol>(boundLocal.LocalSymbol), assignment, retStatement)); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeGetHashCodeMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // HASH_FACTOR = 0xa5555529; // INIT_HASH = (...((0 * HASH_FACTOR) + GetFNVHashCode(backingFld_1.Name)) * HASH_FACTOR // + GetFNVHashCode(backingFld_2.Name)) * HASH_FACTOR // + ... // + GetFNVHashCode(backingFld_N.Name) // // { // return (...((INITIAL_HASH * HASH_FACTOR) + EqualityComparer<T_1>.Default.GetHashCode(this.backingFld_1)) * HASH_FACTOR // + EqualityComparer<T_2>.Default.GetHashCode(this.backingFld_2)) * HASH_FACTOR // ... // + EqualityComparer<T_N>.Default.GetHashCode(this.backingFld_N) // } // // Where GetFNVHashCode is the FNV-1a hash code. // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // INIT_HASH int initHash = 0; foreach (var property in anonymousType.Properties) { initHash = unchecked(initHash * MethodBodySynthesizer.HASH_FACTOR + Hash.GetFNVHashCode(property.BackingField.Name)); } // Generate expression for return statement // retExpression <= 'INITIAL_HASH' BoundExpression retExpression = F.Literal(initHash); // prepare symbols MethodSymbol equalityComparer_GetHashCode = manager.System_Collections_Generic_EqualityComparer_T__GetHashCode; MethodSymbol equalityComparer_get_Default = manager.System_Collections_Generic_EqualityComparer_T__get_Default; // bound HASH_FACTOR BoundLiteral boundHashFactor = null; // Process fields for (int index = 0; index < anonymousType.Properties.Length; index++) { retExpression = MethodBodySynthesizer.GenerateHashCombine(retExpression, equalityComparer_GetHashCode, equalityComparer_get_Default, ref boundHashFactor, F.Field(F.This(), anonymousType.Properties[index].BackingField), F); } // Create a bound block F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeToStringMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // return String.Format( // "{ <name1> = {0}", <name2> = {1}", ... <nameN> = {N-1}", // this.backingFld_1, // this.backingFld_2, // ... // this.backingFld_N // } // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // build arguments int fieldCount = anonymousType.Properties.Length; BoundExpression retExpression = null; if (fieldCount > 0) { // we do have fields, so have to use String.Format(...) BoundExpression[] arguments = new BoundExpression[fieldCount]; // process properties PooledStringBuilder formatString = PooledStringBuilder.GetInstance(); for (int i = 0; i < fieldCount; i++) { AnonymousTypePropertySymbol property = anonymousType.Properties[i]; // build format string formatString.Builder.AppendFormat(i == 0 ? "{{{{ {0} = {{{1}}}" : ", {0} = {{{1}}}", property.Name, i); // build argument arguments[i] = F.Convert(manager.System_Object, new BoundLoweredConditionalAccess(F.Syntax, F.Field(F.This(), property.BackingField), null, F.Call(new BoundConditionalReceiver( F.Syntax, id: i, type: property.BackingField.Type), manager.System_Object__ToString), null, id: i, type: manager.System_String), Conversion.ImplicitReference); } formatString.Builder.Append(" }}"); // add format string argument BoundExpression format = F.Literal(formatString.ToStringAndFree()); // Generate expression for return statement // retExpression <= System.String.Format(args) var formatMethod = manager.System_String__Format_IFormatProvider; retExpression = F.StaticCall(manager.System_String, formatMethod, F.Null(formatMethod.Parameters[0].Type), format, F.ArrayOrEmpty(manager.System_Object, arguments)); } else { // this is an empty anonymous type, just return "{ }" retExpression = F.Literal("{ }"); } F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // Object..ctor(); // this.backingField_1 = arg1; // ... // this.backingField_N = argN; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); int paramCount = this.ParameterCount; // List of statements BoundStatement[] statements = new BoundStatement[paramCount + 2]; int statementIndex = 0; // explicit base constructor call Debug.Assert(ContainingType.BaseTypeNoUseSiteDiagnostics.SpecialType == SpecialType.System_Object); BoundExpression call = MethodCompiler.GenerateBaseParameterlessConstructorInitializer(this, diagnostics); if (call == null) { // This may happen if Object..ctor is not found or is inaccessible return; } statements[statementIndex++] = F.ExpressionStatement(call); if (paramCount > 0) { AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; Debug.Assert(anonymousType.Properties.Length == paramCount); // Assign fields for (int index = 0; index < this.ParameterCount; index++) { // Generate 'field' = 'parameter' statement statements[statementIndex++] = F.Assignment(F.Field(F.This(), anonymousType.Properties[index].BackingField), F.Parameter(_parameters[index])); } } // Final return statement statements[statementIndex++] = F.Return(); // Create a bound block F.CloseMethod(F.Block(statements)); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { // Method body: // // { // return this.backingField; // } SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); F.CloseMethod(F.Block(F.Return(F.Field(F.This(), _property.BackingField)))); } internal override bool HasSpecialName { get { return true; } } } private sealed partial class AnonymousTypeEqualsMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // $anonymous$ local = value as $anonymous$; // return (object)local == this || (local != null // && System.Collections.Generic.EqualityComparer<T_1>.Default.Equals(this.backingFld_1, local.backingFld_1) // ... // && System.Collections.Generic.EqualityComparer<T_N>.Default.Equals(this.backingFld_N, local.backingFld_N)); // } // Type and type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // local BoundAssignmentOperator assignmentToTemp; BoundLocal boundLocal = F.StoreToTemp(F.As(F.Parameter(_parameters[0]), anonymousType), out assignmentToTemp); // Generate: statement <= 'local = value as $anonymous$' BoundStatement assignment = F.ExpressionStatement(assignmentToTemp); // Generate expression for return statement // retExpression <= 'local != null' BoundExpression retExpression = F.Binary(BinaryOperatorKind.ObjectNotEqual, manager.System_Boolean, F.Convert(manager.System_Object, boundLocal), F.Null(manager.System_Object)); // Compare fields if (anonymousType.Properties.Length > 0) { var fields = ArrayBuilder<FieldSymbol>.GetInstance(anonymousType.Properties.Length); foreach (var prop in anonymousType.Properties) { fields.Add(prop.BackingField); } retExpression = MethodBodySynthesizer.GenerateFieldEquals(retExpression, boundLocal, fields, F); fields.Free(); } // Compare references retExpression = F.LogicalOr(F.ObjectEqual(F.This(), boundLocal), retExpression); // Final return statement BoundStatement retStatement = F.Return(retExpression); // Create a bound block F.CloseMethod(F.Block(ImmutableArray.Create<LocalSymbol>(boundLocal.LocalSymbol), assignment, retStatement)); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeGetHashCodeMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // HASH_FACTOR = 0xa5555529; // INIT_HASH = (...((0 * HASH_FACTOR) + GetFNVHashCode(backingFld_1.Name)) * HASH_FACTOR // + GetFNVHashCode(backingFld_2.Name)) * HASH_FACTOR // + ... // + GetFNVHashCode(backingFld_N.Name) // // { // return (...((INITIAL_HASH * HASH_FACTOR) + EqualityComparer<T_1>.Default.GetHashCode(this.backingFld_1)) * HASH_FACTOR // + EqualityComparer<T_2>.Default.GetHashCode(this.backingFld_2)) * HASH_FACTOR // ... // + EqualityComparer<T_N>.Default.GetHashCode(this.backingFld_N) // } // // Where GetFNVHashCode is the FNV-1a hash code. // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // INIT_HASH int initHash = 0; foreach (var property in anonymousType.Properties) { initHash = unchecked(initHash * MethodBodySynthesizer.HASH_FACTOR + Hash.GetFNVHashCode(property.BackingField.Name)); } // Generate expression for return statement // retExpression <= 'INITIAL_HASH' BoundExpression retExpression = F.Literal(initHash); // prepare symbols MethodSymbol equalityComparer_GetHashCode = manager.System_Collections_Generic_EqualityComparer_T__GetHashCode; MethodSymbol equalityComparer_get_Default = manager.System_Collections_Generic_EqualityComparer_T__get_Default; // bound HASH_FACTOR BoundLiteral boundHashFactor = null; // Process fields for (int index = 0; index < anonymousType.Properties.Length; index++) { retExpression = MethodBodySynthesizer.GenerateHashCombine(retExpression, equalityComparer_GetHashCode, equalityComparer_get_Default, ref boundHashFactor, F.Field(F.This(), anonymousType.Properties[index].BackingField), F); } // Create a bound block F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } private sealed partial class AnonymousTypeToStringMethodSymbol : SynthesizedMethodBase { internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { AnonymousTypeManager manager = ((AnonymousTypeTemplateSymbol)this.ContainingType).Manager; SyntheticBoundNodeFactory F = this.CreateBoundNodeFactory(compilationState, diagnostics); // Method body: // // { // return String.Format( // "{ <name1> = {0}", <name2> = {1}", ... <nameN> = {N-1}", // this.backingFld_1, // this.backingFld_2, // ... // this.backingFld_N // } // Type expression AnonymousTypeTemplateSymbol anonymousType = (AnonymousTypeTemplateSymbol)this.ContainingType; // build arguments int fieldCount = anonymousType.Properties.Length; BoundExpression retExpression = null; if (fieldCount > 0) { // we do have fields, so have to use String.Format(...) BoundExpression[] arguments = new BoundExpression[fieldCount]; // process properties PooledStringBuilder formatString = PooledStringBuilder.GetInstance(); for (int i = 0; i < fieldCount; i++) { AnonymousTypePropertySymbol property = anonymousType.Properties[i]; // build format string formatString.Builder.AppendFormat(i == 0 ? "{{{{ {0} = {{{1}}}" : ", {0} = {{{1}}}", property.Name, i); // build argument arguments[i] = F.Convert(manager.System_Object, new BoundLoweredConditionalAccess(F.Syntax, F.Field(F.This(), property.BackingField), null, F.Call(new BoundConditionalReceiver( F.Syntax, id: i, type: property.BackingField.Type), manager.System_Object__ToString), null, id: i, type: manager.System_String), Conversion.ImplicitReference); } formatString.Builder.Append(" }}"); // add format string argument BoundExpression format = F.Literal(formatString.ToStringAndFree()); // Generate expression for return statement // retExpression <= System.String.Format(args) var formatMethod = manager.System_String__Format_IFormatProvider; retExpression = F.StaticCall(manager.System_String, formatMethod, F.Null(formatMethod.Parameters[0].Type), format, F.ArrayOrEmpty(manager.System_Object, arguments)); } else { // this is an empty anonymous type, just return "{ }" retExpression = F.Literal("{ }"); } F.CloseMethod(F.Block(F.Return(retExpression))); } internal override bool HasSpecialName { get { return false; } } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Core/Implementation/Workspaces/ProjectCacheServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces { [ExportWorkspaceServiceFactory(typeof(IProjectCacheHostService), ServiceLayer.Editor)] [Shared] internal partial class ProjectCacheHostServiceFactory : IWorkspaceServiceFactory { private static readonly TimeSpan s_implicitCacheTimeout = TimeSpan.FromMilliseconds(10000); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectCacheHostServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices.Workspace.Kind != WorkspaceKind.Host) { return new ProjectCacheService(workspaceServices.Workspace); } var service = new ProjectCacheService(workspaceServices.Workspace, s_implicitCacheTimeout); // Also clear the cache when the solution is cleared or removed. workspaceServices.Workspace.WorkspaceChanged += (s, e) => { if (e.Kind == WorkspaceChangeKind.SolutionCleared || e.Kind == WorkspaceChangeKind.SolutionRemoved) { service.ClearImplicitCache(); } }; return service; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces { [ExportWorkspaceServiceFactory(typeof(IProjectCacheHostService), ServiceLayer.Editor)] [Shared] internal partial class ProjectCacheHostServiceFactory : IWorkspaceServiceFactory { private static readonly TimeSpan s_implicitCacheTimeout = TimeSpan.FromMilliseconds(10000); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectCacheHostServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (workspaceServices.Workspace.Kind != WorkspaceKind.Host) { return new ProjectCacheService(workspaceServices.Workspace); } var service = new ProjectCacheService(workspaceServices.Workspace, s_implicitCacheTimeout); // Also clear the cache when the solution is cleared or removed. workspaceServices.Workspace.WorkspaceChanged += (s, e) => { if (e.Kind == WorkspaceChangeKind.SolutionCleared || e.Kind == WorkspaceChangeKind.SolutionRemoved) { service.ClearImplicitCache(); } }; return service; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/CSharp/Test/ProjectSystemShim/CPS/CSharpReferencesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { using static CSharpHelpers; [UseExportProvider] public class CSharpReferenceTests { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task AddRemoveProjectAndMetadataReference_CPS() { using var environment = new TestEnvironment(); var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll"); var project2 = await CreateCSharpCPSProjectAsync(environment, "project2", commandLineArguments: @"/out:c:\project2.dll"); var project3 = await CreateCSharpCPSProjectAsync(environment, "project3", commandLineArguments: @"/out:c:\project3.dll"); var project4 = await CreateCSharpCPSProjectAsync(environment, "project4"); // Add project reference project3.AddProjectReference(project1, new MetadataReferenceProperties()); // Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference project3.AddMetadataReference(@"c:\project2.dll", new MetadataReferenceProperties()); // Add project reference with no output path project3.AddProjectReference(project4, new MetadataReferenceProperties()); // Add metadata reference var metadaRefFilePath = @"c:\someAssembly.dll"; project3.AddMetadataReference(metadaRefFilePath, new MetadataReferenceProperties(embedInteropTypes: true)); IEnumerable<ProjectReference> GetProject3ProjectReferences() { return environment.Workspace .CurrentSolution.GetProject(project3.Id).ProjectReferences; } IEnumerable<PortableExecutableReference> GetProject3MetadataReferences() { return environment.Workspace.CurrentSolution.GetProject(project3.Id) .MetadataReferences .Cast<PortableExecutableReference>(); } Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id)); Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id)); Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id)); Assert.True(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath)); // Change output path for project reference and verify the reference. ((IWorkspaceProjectContext)project4).BinOutputPath = @"C:\project4.dll"; Assert.Equal(@"C:\project4.dll", project4.BinOutputPath); Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id)); // Remove project reference project3.RemoveProjectReference(project1); // Remove project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference project3.RemoveMetadataReference(@"c:\project2.dll"); // Remove metadata reference project3.RemoveMetadataReference(metadaRefFilePath); Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id)); Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id)); Assert.False(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath)); project1.Dispose(); project2.Dispose(); project4.Dispose(); project3.Dispose(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RemoveProjectConvertsProjectReferencesBack() { using var environment = new TestEnvironment(); var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll"); var project2 = await CreateCSharpCPSProjectAsync(environment, "project2"); // Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference project2.AddMetadataReference(@"c:\project1.dll", new MetadataReferenceProperties()); Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences); // Remove project1. project2's reference should have been converted back project1.Dispose(); Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences); Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).MetadataReferences); project2.Dispose(); } [WpfFact] [WorkItem(461967, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/461967")] [WorkItem(727173, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/727173")] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task AddingMetadataReferenceToProjectThatCannotCompileInTheIdeKeepsMetadataReference() { using var environment = new TestEnvironment(typeof(NoCompilationLanguageServiceFactory)); var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll"); var project2 = await CreateNonCompilableProjectAsync(environment, "project2", @"C:\project2.fsproj"); project2.BinOutputPath = "c:\\project2.dll"; project1.AddMetadataReference(project2.BinOutputPath, MetadataReferenceProperties.Assembly); // We should not have converted that to a project reference, because we would have no way to produce the compilation Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project1.Id).AllProjectReferences); project2.Dispose(); project1.Dispose(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task AddRemoveAnalyzerReference_CPS() { using var environment = new TestEnvironment(); using var project = await CreateCSharpCPSProjectAsync(environment, "project1"); // Add analyzer reference var analyzerAssemblyFullPath = @"c:\someAssembly.dll"; bool AnalyzersContainsAnalyzer() { return environment.Workspace.CurrentSolution.Projects.Single() .AnalyzerReferences.Cast<AnalyzerReference>() .Any(a => a.FullPath == analyzerAssemblyFullPath); } project.AddAnalyzerReference(analyzerAssemblyFullPath); Assert.True(AnalyzersContainsAnalyzer()); // Remove analyzer reference project.RemoveAnalyzerReference(analyzerAssemblyFullPath); Assert.False(AnalyzersContainsAnalyzer()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { using static CSharpHelpers; [UseExportProvider] public class CSharpReferenceTests { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task AddRemoveProjectAndMetadataReference_CPS() { using var environment = new TestEnvironment(); var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll"); var project2 = await CreateCSharpCPSProjectAsync(environment, "project2", commandLineArguments: @"/out:c:\project2.dll"); var project3 = await CreateCSharpCPSProjectAsync(environment, "project3", commandLineArguments: @"/out:c:\project3.dll"); var project4 = await CreateCSharpCPSProjectAsync(environment, "project4"); // Add project reference project3.AddProjectReference(project1, new MetadataReferenceProperties()); // Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference project3.AddMetadataReference(@"c:\project2.dll", new MetadataReferenceProperties()); // Add project reference with no output path project3.AddProjectReference(project4, new MetadataReferenceProperties()); // Add metadata reference var metadaRefFilePath = @"c:\someAssembly.dll"; project3.AddMetadataReference(metadaRefFilePath, new MetadataReferenceProperties(embedInteropTypes: true)); IEnumerable<ProjectReference> GetProject3ProjectReferences() { return environment.Workspace .CurrentSolution.GetProject(project3.Id).ProjectReferences; } IEnumerable<PortableExecutableReference> GetProject3MetadataReferences() { return environment.Workspace.CurrentSolution.GetProject(project3.Id) .MetadataReferences .Cast<PortableExecutableReference>(); } Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id)); Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id)); Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id)); Assert.True(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath)); // Change output path for project reference and verify the reference. ((IWorkspaceProjectContext)project4).BinOutputPath = @"C:\project4.dll"; Assert.Equal(@"C:\project4.dll", project4.BinOutputPath); Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id)); // Remove project reference project3.RemoveProjectReference(project1); // Remove project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference project3.RemoveMetadataReference(@"c:\project2.dll"); // Remove metadata reference project3.RemoveMetadataReference(metadaRefFilePath); Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id)); Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id)); Assert.False(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath)); project1.Dispose(); project2.Dispose(); project4.Dispose(); project3.Dispose(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RemoveProjectConvertsProjectReferencesBack() { using var environment = new TestEnvironment(); var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll"); var project2 = await CreateCSharpCPSProjectAsync(environment, "project2"); // Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference project2.AddMetadataReference(@"c:\project1.dll", new MetadataReferenceProperties()); Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences); // Remove project1. project2's reference should have been converted back project1.Dispose(); Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences); Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).MetadataReferences); project2.Dispose(); } [WpfFact] [WorkItem(461967, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/461967")] [WorkItem(727173, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/727173")] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task AddingMetadataReferenceToProjectThatCannotCompileInTheIdeKeepsMetadataReference() { using var environment = new TestEnvironment(typeof(NoCompilationLanguageServiceFactory)); var project1 = await CreateCSharpCPSProjectAsync(environment, "project1", commandLineArguments: @"/out:c:\project1.dll"); var project2 = await CreateNonCompilableProjectAsync(environment, "project2", @"C:\project2.fsproj"); project2.BinOutputPath = "c:\\project2.dll"; project1.AddMetadataReference(project2.BinOutputPath, MetadataReferenceProperties.Assembly); // We should not have converted that to a project reference, because we would have no way to produce the compilation Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project1.Id).AllProjectReferences); project2.Dispose(); project1.Dispose(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task AddRemoveAnalyzerReference_CPS() { using var environment = new TestEnvironment(); using var project = await CreateCSharpCPSProjectAsync(environment, "project1"); // Add analyzer reference var analyzerAssemblyFullPath = @"c:\someAssembly.dll"; bool AnalyzersContainsAnalyzer() { return environment.Workspace.CurrentSolution.Projects.Single() .AnalyzerReferences.Cast<AnalyzerReference>() .Any(a => a.FullPath == analyzerAssemblyFullPath); } project.AddAnalyzerReference(analyzerAssemblyFullPath); Assert.True(AnalyzersContainsAnalyzer()); // Remove analyzer reference project.RemoveAnalyzerReference(analyzerAssemblyFullPath); Assert.False(AnalyzersContainsAnalyzer()); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/MSBuildTaskTests/CsiTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public sealed class CsiTests { [Fact] public void SingleSource() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); Assert.Equal("/i- test.csx", csi.GenerateResponseFileContents()); } [Fact] public void Features() { Action<string> test = (s) => { var csi = new Csi(); csi.Features = s; csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); Assert.Equal("/i- /features:a /features:b test.csx", csi.GenerateResponseFileContents()); }; test("a;b"); test("a,b"); test("a b"); test(",a;b "); test(";a;;b;"); test(",a,,b,"); } [Fact] public void FeaturesEmpty() { foreach (var cur in new[] { "", null }) { var csi = new Csi(); csi.Features = cur; csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); Assert.Equal("/i- test.csx", csi.GenerateResponseFileContents()); } } [Fact] public void ScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new[] { "-Arg1", "-Arg2" }; Assert.Equal("/i- test.csx -Arg1 -Arg2", csi.GenerateResponseFileContents()); } [Fact] public void ScriptArgumentsNeedQuotes() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new[] { @"C:\Some Path\Some File.ini", @"C:\Some Path\Some Other File.bak" }; Assert.Equal(@"/i- test.csx ""C:\Some Path\Some File.ini"" ""C:\Some Path\Some Other File.bak""", csi.GenerateResponseFileContents()); } [Fact] public void QuotedScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new[] { @"""C:\Some Path\Some File.ini""", @"""C:\Some Path\Some Other File.bak""" }; Assert.Equal(@"/i- test.csx ""\""C:\Some Path\Some File.ini\"""" ""\""C:\Some Path\Some Other File.bak\""""", csi.GenerateResponseFileContents()); } [Fact] public void NoScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = null; Assert.Equal(@"/i- test.csx", csi.GenerateResponseFileContents()); } [Fact] public void EmptyScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new string[0]; Assert.Equal(@"/i- test.csx", csi.GenerateResponseFileContents()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public sealed class CsiTests { [Fact] public void SingleSource() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); Assert.Equal("/i- test.csx", csi.GenerateResponseFileContents()); } [Fact] public void Features() { Action<string> test = (s) => { var csi = new Csi(); csi.Features = s; csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); Assert.Equal("/i- /features:a /features:b test.csx", csi.GenerateResponseFileContents()); }; test("a;b"); test("a,b"); test("a b"); test(",a;b "); test(";a;;b;"); test(",a,,b,"); } [Fact] public void FeaturesEmpty() { foreach (var cur in new[] { "", null }) { var csi = new Csi(); csi.Features = cur; csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); Assert.Equal("/i- test.csx", csi.GenerateResponseFileContents()); } } [Fact] public void ScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new[] { "-Arg1", "-Arg2" }; Assert.Equal("/i- test.csx -Arg1 -Arg2", csi.GenerateResponseFileContents()); } [Fact] public void ScriptArgumentsNeedQuotes() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new[] { @"C:\Some Path\Some File.ini", @"C:\Some Path\Some Other File.bak" }; Assert.Equal(@"/i- test.csx ""C:\Some Path\Some File.ini"" ""C:\Some Path\Some Other File.bak""", csi.GenerateResponseFileContents()); } [Fact] public void QuotedScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new[] { @"""C:\Some Path\Some File.ini""", @"""C:\Some Path\Some Other File.bak""" }; Assert.Equal(@"/i- test.csx ""\""C:\Some Path\Some File.ini\"""" ""\""C:\Some Path\Some Other File.bak\""""", csi.GenerateResponseFileContents()); } [Fact] public void NoScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = null; Assert.Equal(@"/i- test.csx", csi.GenerateResponseFileContents()); } [Fact] public void EmptyScriptArguments() { var csi = new Csi(); csi.Source = MSBuildUtil.CreateTaskItem("test.csx"); csi.ScriptArguments = new string[0]; Assert.Equal(@"/i- test.csx", csi.GenerateResponseFileContents()); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/CSharpTest2/Recommendations/EnumKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EnumKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstractPublic() => await VerifyAbsenceAsync(@"abstract public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEnum() => await VerifyAbsenceAsync(@"enum $$"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EnumKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstractPublic() => await VerifyAbsenceAsync(@"abstract public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEnum() => await VerifyAbsenceAsync(@"enum $$"); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/Lists/NamespaceListItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class NamespaceListItem : SymbolListItem<INamespaceSymbol> { public NamespaceListItem(ProjectId projectId, INamespaceSymbol namespaceSymbol, string displayText, string fullNameText, string searchText) : base(projectId, namespaceSymbol, displayText, fullNameText, searchText, isHidden: false) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class NamespaceListItem : SymbolListItem<INamespaceSymbol> { public NamespaceListItem(ProjectId projectId, INamespaceSymbol namespaceSymbol, string displayText, string fullNameText, string searchText) : base(projectId, namespaceSymbol, displayText, fullNameText, searchText, isHidden: false) { } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerDisplayAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // C:\Enlistments\Roslyn2\_Download\Concord\0.0.1+b140327.201033\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrDebuggerDisplayAttribute : DkmClrEvalAttribute { public string Name { get; internal set; } public string TypeName { get; internal set; } public string Value { get; internal set; } public DkmClrDebuggerDisplayAttribute(string targetMember) : base(targetMember) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // C:\Enlistments\Roslyn2\_Download\Concord\0.0.1+b140327.201033\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrDebuggerDisplayAttribute : DkmClrEvalAttribute { public string Name { get; internal set; } public string TypeName { get; internal set; } public string Value { get; internal set; } public DkmClrDebuggerDisplayAttribute(string targetMember) : base(targetMember) { } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Test/Core/CompilerTraitAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Xunit; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { [TraitDiscoverer("Microsoft.CodeAnalysis.Test.Utilities.CompilerTraitDiscoverer", assemblyName: "Roslyn.Test.Utilities")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public sealed class CompilerTraitAttribute : Attribute, ITraitAttribute { public CompilerFeature[] Features { get; } public CompilerTraitAttribute(params CompilerFeature[] features) { Features = features; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Xunit; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { [TraitDiscoverer("Microsoft.CodeAnalysis.Test.Utilities.CompilerTraitDiscoverer", assemblyName: "Roslyn.Test.Utilities")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public sealed class CompilerTraitAttribute : Attribute, ITraitAttribute { public CompilerFeature[] Features { get; } public CompilerTraitAttribute(params CompilerFeature[] features) { Features = features; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/Portable/MemoryExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.CodeAnalysis { internal static class MemoryExtensions { public static int IndexOfAny(this ReadOnlySpan<char> span, char[] characters) { for (int i = 0; i < span.Length; i++) { var c = span[i]; foreach (var target in characters) { if (c == target) { return i; } } } return -1; } #if !NETCOREAPP internal static ReadOnlyMemory<char> TrimStart(this ReadOnlyMemory<char> memory) { var span = memory.Span; var index = 0; while (index < span.Length && char.IsWhiteSpace(span[index])) { index++; } return memory.Slice(index, span.Length); } internal static ReadOnlyMemory<char> TrimEnd(this ReadOnlyMemory<char> memory) { var span = memory.Span; var length = span.Length; while (length - 1 >= 0 && char.IsWhiteSpace(span[length - 1])) { length--; } return memory.Slice(0, length); } internal static ReadOnlyMemory<char> Trim(this ReadOnlyMemory<char> memory) => memory.TrimStart().TrimEnd(); #endif internal static bool IsNullOrEmpty(this ReadOnlyMemory<char>? memory) => memory is not { Length: > 0 }; internal static bool IsNullOrWhiteSpace(this ReadOnlyMemory<char>? memory) => memory is not { } m || IsWhiteSpace(m); internal static bool IsWhiteSpace(this ReadOnlyMemory<char> memory) { var span = memory.Span; foreach (var c in span) { if (!char.IsWhiteSpace(c)) { return false; } } return true; } internal static bool StartsWith(this ReadOnlyMemory<char> memory, char c) => memory.Length > 0 && memory.Span[0] == c; internal static ReadOnlyMemory<char> Unquote(this ReadOnlyMemory<char> memory) { var span = memory.Span; if (span.Length > 1 && span[0] == '"' && span[span.Length - 1] == '"') { return memory.Slice(1, memory.Length - 2); } return memory; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.CodeAnalysis { internal static class MemoryExtensions { public static int IndexOfAny(this ReadOnlySpan<char> span, char[] characters) { for (int i = 0; i < span.Length; i++) { var c = span[i]; foreach (var target in characters) { if (c == target) { return i; } } } return -1; } #if !NETCOREAPP internal static ReadOnlyMemory<char> TrimStart(this ReadOnlyMemory<char> memory) { var span = memory.Span; var index = 0; while (index < span.Length && char.IsWhiteSpace(span[index])) { index++; } return memory.Slice(index, span.Length); } internal static ReadOnlyMemory<char> TrimEnd(this ReadOnlyMemory<char> memory) { var span = memory.Span; var length = span.Length; while (length - 1 >= 0 && char.IsWhiteSpace(span[length - 1])) { length--; } return memory.Slice(0, length); } internal static ReadOnlyMemory<char> Trim(this ReadOnlyMemory<char> memory) => memory.TrimStart().TrimEnd(); #endif internal static bool IsNullOrEmpty(this ReadOnlyMemory<char>? memory) => memory is not { Length: > 0 }; internal static bool IsNullOrWhiteSpace(this ReadOnlyMemory<char>? memory) => memory is not { } m || IsWhiteSpace(m); internal static bool IsWhiteSpace(this ReadOnlyMemory<char> memory) { var span = memory.Span; foreach (var c in span) { if (!char.IsWhiteSpace(c)) { return false; } } return true; } internal static bool StartsWith(this ReadOnlyMemory<char> memory, char c) => memory.Length > 0 && memory.Span[0] == c; internal static ReadOnlyMemory<char> Unquote(this ReadOnlyMemory<char> memory) { var span = memory.Span; if (span.Length > 1 && span[0] == '"' && span[span.Length - 1] == '"') { return memory.Slice(1, memory.Length - 2); } return memory; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/EditorConfigSettings/SettingsEditorPane.SearchTask.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal sealed partial class SettingsEditorPane { internal class SearchTask : VsSearchTask { private readonly IThreadingContext _threadingContext; private readonly IWpfTableControl[] _controls; public SearchTask(uint dwCookie, IVsSearchQuery pSearchQuery, IVsSearchCallback pSearchCallback, IWpfTableControl[] controls, IThreadingContext threadingContext) : base(dwCookie, pSearchQuery, pSearchCallback) { _threadingContext = threadingContext; _controls = controls; } protected override void OnStartSearch() { _ = _threadingContext.JoinableTaskFactory.RunAsync( async () => { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); foreach (var control in _controls) { _ = control.SetFilter(string.Empty, new SearchFilter(SearchQuery, control)); } await TaskScheduler.Default; uint resultCount = 0; foreach (var control in _controls) { var results = await control.ForceUpdateAsync().ConfigureAwait(false); resultCount += (uint)results.FilteredAndSortedEntries.Count; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); SearchCallback.ReportComplete(this, dwResultsFound: resultCount); }); } protected override void OnStopSearch() { _ = _threadingContext.JoinableTaskFactory.RunAsync( async () => { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); foreach (var control in _controls) { _ = control.SetFilter(string.Empty, null); } }); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal sealed partial class SettingsEditorPane { internal class SearchTask : VsSearchTask { private readonly IThreadingContext _threadingContext; private readonly IWpfTableControl[] _controls; public SearchTask(uint dwCookie, IVsSearchQuery pSearchQuery, IVsSearchCallback pSearchCallback, IWpfTableControl[] controls, IThreadingContext threadingContext) : base(dwCookie, pSearchQuery, pSearchCallback) { _threadingContext = threadingContext; _controls = controls; } protected override void OnStartSearch() { _ = _threadingContext.JoinableTaskFactory.RunAsync( async () => { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); foreach (var control in _controls) { _ = control.SetFilter(string.Empty, new SearchFilter(SearchQuery, control)); } await TaskScheduler.Default; uint resultCount = 0; foreach (var control in _controls) { var results = await control.ForceUpdateAsync().ConfigureAwait(false); resultCount += (uint)results.FilteredAndSortedEntries.Count; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); SearchCallback.ReportComplete(this, dwResultsFound: resultCount); }); } protected override void OnStopSearch() { _ = _threadingContext.JoinableTaskFactory.RunAsync( async () => { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); foreach (var control in _controls) { _ = control.SetFilter(string.Empty, null); } }); } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/Remote/ServiceHub/Services/WorkspaceTelemetry/RemoteWorkspaceTelemetryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { [ExportWorkspaceService(typeof(IWorkspaceTelemetryService)), Shared] internal sealed class RemoteWorkspaceTelemetryService : AbstractWorkspaceTelemetryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteWorkspaceTelemetryService() { } protected override ILogger CreateLogger(TelemetrySession telemetrySession) => AggregateLogger.Create( new VSTelemetryLogger(telemetrySession), Logger.GetLogger()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { [ExportWorkspaceService(typeof(IWorkspaceTelemetryService)), Shared] internal sealed class RemoteWorkspaceTelemetryService : AbstractWorkspaceTelemetryService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteWorkspaceTelemetryService() { } protected override ILogger CreateLogger(TelemetrySession telemetrySession) => AggregateLogger.Create( new VSTelemetryLogger(telemetrySession), Logger.GetLogger()); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Core/Implementation/Interactive/SendToInteractiveSubmissionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Interactive { /// <summary> /// Implementers of this interface are responsible for retrieving source code that /// should be sent to the REPL given the user's selection. /// /// If the user does not make a selection then a line should be selected. /// If the user selects code that fails to be parsed then the selection gets expanded /// to a syntax node. /// </summary> internal abstract class AbstractSendToInteractiveSubmissionProvider : ISendToInteractiveSubmissionProvider { /// <summary>Expands the selection span of an invalid selection to a span that should be sent to REPL.</summary> protected abstract IEnumerable<TextSpan> GetExecutableSyntaxTreeNodeSelection(TextSpan selectedSpan, SyntaxNode node); /// <summary>Returns whether the submission can be parsed in interactive.</summary> protected abstract bool CanParseSubmission(string code); string ISendToInteractiveSubmissionProvider.GetSelectedText(IEditorOptions editorOptions, EditorCommandArgs args, CancellationToken cancellationToken) { var selectedSpans = args.TextView.Selection.IsEmpty ? GetExpandedLineAsync(editorOptions, args, cancellationToken).WaitAndGetResult(cancellationToken) : args.TextView.Selection.GetSnapshotSpansOnBuffer(args.SubjectBuffer).Where(ss => ss.Length > 0); return GetSubmissionFromSelectedSpans(editorOptions, selectedSpans); } /// <summary>Returns the span for the selected line. Extends it if it is a part of a multi line statement or declaration.</summary> private Task<IEnumerable<SnapshotSpan>> GetExpandedLineAsync(IEditorOptions editorOptions, EditorCommandArgs args, CancellationToken cancellationToken) { var selectedSpans = GetSelectedLine(args.TextView); var candidateSubmission = GetSubmissionFromSelectedSpans(editorOptions, selectedSpans); return CanParseSubmission(candidateSubmission) ? Task.FromResult(selectedSpans) : ExpandSelectionAsync(selectedSpans, args, cancellationToken); } /// <summary>Returns the span for the currently selected line.</summary> private static IEnumerable<SnapshotSpan> GetSelectedLine(ITextView textView) { var snapshotLine = textView.Caret.Position.VirtualBufferPosition.Position.GetContainingLine(); var span = new SnapshotSpan(snapshotLine.Start, snapshotLine.LengthIncludingLineBreak); return new NormalizedSnapshotSpanCollection(span); } private async Task<IEnumerable<SnapshotSpan>> GetExecutableSyntaxTreeNodeSelectionAsync( TextSpan selectionSpan, EditorCommandArgs args, ITextSnapshot snapshot, CancellationToken cancellationToken) { var doc = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var semanticDocument = await SemanticDocument.CreateAsync(doc, cancellationToken).ConfigureAwait(false); var root = semanticDocument.Root; return GetExecutableSyntaxTreeNodeSelection(selectionSpan, root) .Select(span => new SnapshotSpan(snapshot, span.Start, span.Length)); } private async Task<IEnumerable<SnapshotSpan>> ExpandSelectionAsync(IEnumerable<SnapshotSpan> selectedSpans, EditorCommandArgs args, CancellationToken cancellationToken) { var selectedSpansStart = selectedSpans.Min(span => span.Start); var selectedSpansEnd = selectedSpans.Max(span => span.End); var snapshot = args.TextView.TextSnapshot; var newSpans = await GetExecutableSyntaxTreeNodeSelectionAsync( TextSpan.FromBounds(selectedSpansStart, selectedSpansEnd), args, snapshot, cancellationToken).ConfigureAwait(false); return newSpans.Any() ? newSpans.Select(n => new SnapshotSpan(snapshot, n.Span.Start, n.Span.Length)) : selectedSpans; } private static string GetSubmissionFromSelectedSpans(IEditorOptions editorOptions, IEnumerable<SnapshotSpan> selectedSpans) => string.Join(editorOptions.GetNewLineCharacter(), selectedSpans.Select(ss => ss.GetText())); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Interactive { /// <summary> /// Implementers of this interface are responsible for retrieving source code that /// should be sent to the REPL given the user's selection. /// /// If the user does not make a selection then a line should be selected. /// If the user selects code that fails to be parsed then the selection gets expanded /// to a syntax node. /// </summary> internal abstract class AbstractSendToInteractiveSubmissionProvider : ISendToInteractiveSubmissionProvider { /// <summary>Expands the selection span of an invalid selection to a span that should be sent to REPL.</summary> protected abstract IEnumerable<TextSpan> GetExecutableSyntaxTreeNodeSelection(TextSpan selectedSpan, SyntaxNode node); /// <summary>Returns whether the submission can be parsed in interactive.</summary> protected abstract bool CanParseSubmission(string code); string ISendToInteractiveSubmissionProvider.GetSelectedText(IEditorOptions editorOptions, EditorCommandArgs args, CancellationToken cancellationToken) { var selectedSpans = args.TextView.Selection.IsEmpty ? GetExpandedLineAsync(editorOptions, args, cancellationToken).WaitAndGetResult(cancellationToken) : args.TextView.Selection.GetSnapshotSpansOnBuffer(args.SubjectBuffer).Where(ss => ss.Length > 0); return GetSubmissionFromSelectedSpans(editorOptions, selectedSpans); } /// <summary>Returns the span for the selected line. Extends it if it is a part of a multi line statement or declaration.</summary> private Task<IEnumerable<SnapshotSpan>> GetExpandedLineAsync(IEditorOptions editorOptions, EditorCommandArgs args, CancellationToken cancellationToken) { var selectedSpans = GetSelectedLine(args.TextView); var candidateSubmission = GetSubmissionFromSelectedSpans(editorOptions, selectedSpans); return CanParseSubmission(candidateSubmission) ? Task.FromResult(selectedSpans) : ExpandSelectionAsync(selectedSpans, args, cancellationToken); } /// <summary>Returns the span for the currently selected line.</summary> private static IEnumerable<SnapshotSpan> GetSelectedLine(ITextView textView) { var snapshotLine = textView.Caret.Position.VirtualBufferPosition.Position.GetContainingLine(); var span = new SnapshotSpan(snapshotLine.Start, snapshotLine.LengthIncludingLineBreak); return new NormalizedSnapshotSpanCollection(span); } private async Task<IEnumerable<SnapshotSpan>> GetExecutableSyntaxTreeNodeSelectionAsync( TextSpan selectionSpan, EditorCommandArgs args, ITextSnapshot snapshot, CancellationToken cancellationToken) { var doc = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var semanticDocument = await SemanticDocument.CreateAsync(doc, cancellationToken).ConfigureAwait(false); var root = semanticDocument.Root; return GetExecutableSyntaxTreeNodeSelection(selectionSpan, root) .Select(span => new SnapshotSpan(snapshot, span.Start, span.Length)); } private async Task<IEnumerable<SnapshotSpan>> ExpandSelectionAsync(IEnumerable<SnapshotSpan> selectedSpans, EditorCommandArgs args, CancellationToken cancellationToken) { var selectedSpansStart = selectedSpans.Min(span => span.Start); var selectedSpansEnd = selectedSpans.Max(span => span.End); var snapshot = args.TextView.TextSnapshot; var newSpans = await GetExecutableSyntaxTreeNodeSelectionAsync( TextSpan.FromBounds(selectedSpansStart, selectedSpansEnd), args, snapshot, cancellationToken).ConfigureAwait(false); return newSpans.Any() ? newSpans.Select(n => new SnapshotSpan(snapshot, n.Span.Start, n.Span.Length)) : selectedSpans; } private static string GetSubmissionFromSelectedSpans(IEditorOptions editorOptions, IEnumerable<SnapshotSpan> selectedSpans) => string.Join(editorOptions.GetNewLineCharacter(), selectedSpans.Select(ss => ss.GetText())); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/Portable/Emit/EditAndContinue/AddedOrChangedMethodInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal readonly struct AddedOrChangedMethodInfo { public readonly DebugId MethodId; // locals: public readonly ImmutableArray<EncLocalInfo> Locals; // lambdas, closures: public readonly ImmutableArray<LambdaDebugInfo> LambdaDebugInfo; public readonly ImmutableArray<ClosureDebugInfo> ClosureDebugInfo; // state machines: public readonly string? StateMachineTypeName; public readonly ImmutableArray<EncHoistedLocalInfo> StateMachineHoistedLocalSlotsOpt; public readonly ImmutableArray<Cci.ITypeReference?> StateMachineAwaiterSlotsOpt; public AddedOrChangedMethodInfo( DebugId methodId, ImmutableArray<EncLocalInfo> locals, ImmutableArray<LambdaDebugInfo> lambdaDebugInfo, ImmutableArray<ClosureDebugInfo> closureDebugInfo, string? stateMachineTypeName, ImmutableArray<EncHoistedLocalInfo> stateMachineHoistedLocalSlotsOpt, ImmutableArray<Cci.ITypeReference?> stateMachineAwaiterSlotsOpt) { // An updated method will carry its id over, // an added method id has generation set to the current generation ordinal. Debug.Assert(methodId.Generation >= 0); // each state machine has to have awaiters: Debug.Assert(stateMachineAwaiterSlotsOpt.IsDefault == (stateMachineTypeName == null)); // a state machine might not have hoisted variables: Debug.Assert(stateMachineHoistedLocalSlotsOpt.IsDefault || (stateMachineTypeName != null)); MethodId = methodId; Locals = locals; LambdaDebugInfo = lambdaDebugInfo; ClosureDebugInfo = closureDebugInfo; StateMachineTypeName = stateMachineTypeName; StateMachineHoistedLocalSlotsOpt = stateMachineHoistedLocalSlotsOpt; StateMachineAwaiterSlotsOpt = stateMachineAwaiterSlotsOpt; } public AddedOrChangedMethodInfo MapTypes(SymbolMatcher map) { var mappedLocals = ImmutableArray.CreateRange(Locals, MapLocalInfo, map); var mappedHoistedLocalSlots = StateMachineHoistedLocalSlotsOpt.IsDefault ? default : ImmutableArray.CreateRange(StateMachineHoistedLocalSlotsOpt, MapHoistedLocalSlot, map); var mappedAwaiterSlots = StateMachineAwaiterSlotsOpt.IsDefault ? default : ImmutableArray.CreateRange(StateMachineAwaiterSlotsOpt, static (typeRef, map) => (typeRef is null) ? null : map.MapReference(typeRef), map); return new AddedOrChangedMethodInfo(MethodId, mappedLocals, LambdaDebugInfo, ClosureDebugInfo, StateMachineTypeName, mappedHoistedLocalSlots, mappedAwaiterSlots); } private static EncLocalInfo MapLocalInfo(EncLocalInfo info, SymbolMatcher map) { Debug.Assert(!info.IsDefault); if (info.Type is null) { Debug.Assert(info.Signature != null); return info; } var typeRef = map.MapReference(info.Type); RoslynDebug.AssertNotNull(typeRef); return new EncLocalInfo(info.SlotInfo, typeRef, info.Constraints, info.Signature); } private static EncHoistedLocalInfo MapHoistedLocalSlot(EncHoistedLocalInfo info, SymbolMatcher map) { if (info.Type is null) { return info; } var typeRef = map.MapReference(info.Type); RoslynDebug.AssertNotNull(typeRef); return new EncHoistedLocalInfo(info.SlotInfo, typeRef); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal readonly struct AddedOrChangedMethodInfo { public readonly DebugId MethodId; // locals: public readonly ImmutableArray<EncLocalInfo> Locals; // lambdas, closures: public readonly ImmutableArray<LambdaDebugInfo> LambdaDebugInfo; public readonly ImmutableArray<ClosureDebugInfo> ClosureDebugInfo; // state machines: public readonly string? StateMachineTypeName; public readonly ImmutableArray<EncHoistedLocalInfo> StateMachineHoistedLocalSlotsOpt; public readonly ImmutableArray<Cci.ITypeReference?> StateMachineAwaiterSlotsOpt; public AddedOrChangedMethodInfo( DebugId methodId, ImmutableArray<EncLocalInfo> locals, ImmutableArray<LambdaDebugInfo> lambdaDebugInfo, ImmutableArray<ClosureDebugInfo> closureDebugInfo, string? stateMachineTypeName, ImmutableArray<EncHoistedLocalInfo> stateMachineHoistedLocalSlotsOpt, ImmutableArray<Cci.ITypeReference?> stateMachineAwaiterSlotsOpt) { // An updated method will carry its id over, // an added method id has generation set to the current generation ordinal. Debug.Assert(methodId.Generation >= 0); // each state machine has to have awaiters: Debug.Assert(stateMachineAwaiterSlotsOpt.IsDefault == (stateMachineTypeName == null)); // a state machine might not have hoisted variables: Debug.Assert(stateMachineHoistedLocalSlotsOpt.IsDefault || (stateMachineTypeName != null)); MethodId = methodId; Locals = locals; LambdaDebugInfo = lambdaDebugInfo; ClosureDebugInfo = closureDebugInfo; StateMachineTypeName = stateMachineTypeName; StateMachineHoistedLocalSlotsOpt = stateMachineHoistedLocalSlotsOpt; StateMachineAwaiterSlotsOpt = stateMachineAwaiterSlotsOpt; } public AddedOrChangedMethodInfo MapTypes(SymbolMatcher map) { var mappedLocals = ImmutableArray.CreateRange(Locals, MapLocalInfo, map); var mappedHoistedLocalSlots = StateMachineHoistedLocalSlotsOpt.IsDefault ? default : ImmutableArray.CreateRange(StateMachineHoistedLocalSlotsOpt, MapHoistedLocalSlot, map); var mappedAwaiterSlots = StateMachineAwaiterSlotsOpt.IsDefault ? default : ImmutableArray.CreateRange(StateMachineAwaiterSlotsOpt, static (typeRef, map) => (typeRef is null) ? null : map.MapReference(typeRef), map); return new AddedOrChangedMethodInfo(MethodId, mappedLocals, LambdaDebugInfo, ClosureDebugInfo, StateMachineTypeName, mappedHoistedLocalSlots, mappedAwaiterSlots); } private static EncLocalInfo MapLocalInfo(EncLocalInfo info, SymbolMatcher map) { Debug.Assert(!info.IsDefault); if (info.Type is null) { Debug.Assert(info.Signature != null); return info; } var typeRef = map.MapReference(info.Type); RoslynDebug.AssertNotNull(typeRef); return new EncLocalInfo(info.SlotInfo, typeRef, info.Constraints, info.Signature); } private static EncHoistedLocalInfo MapHoistedLocalSlot(EncHoistedLocalInfo info, SymbolMatcher map) { if (info.Type is null) { return info; } var typeRef = map.MapReference(info.Type); RoslynDebug.AssertNotNull(typeRef); return new EncHoistedLocalInfo(info.SlotInfo, typeRef); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Test/Core/Pe/BrokenStream.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; namespace Roslyn.Test.Utilities { internal class BrokenStream : Stream { public enum BreakHowType { ThrowOnSetPosition, ThrowOnWrite, ThrowOnSetLength, CancelOnWrite } public BreakHowType BreakHow; public Exception ThrownException { get; private set; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { if (BreakHow == BreakHowType.ThrowOnSetPosition) { ThrownException = new NotSupportedException(); throw ThrownException; } } } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { if (BreakHow == BreakHowType.ThrowOnSetLength) { ThrownException = new IOException(); throw ThrownException; } } public override void Write(byte[] buffer, int offset, int count) { if (BreakHow == BreakHowType.ThrowOnWrite) { ThrownException = new IOException(); throw ThrownException; } else if (BreakHow == BreakHowType.CancelOnWrite) { ThrownException = new OperationCanceledException(); throw ThrownException; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; namespace Roslyn.Test.Utilities { internal class BrokenStream : Stream { public enum BreakHowType { ThrowOnSetPosition, ThrowOnWrite, ThrowOnSetLength, CancelOnWrite } public BreakHowType BreakHow; public Exception ThrownException { get; private set; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { if (BreakHow == BreakHowType.ThrowOnSetPosition) { ThrownException = new NotSupportedException(); throw ThrownException; } } } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { if (BreakHow == BreakHowType.ThrowOnSetLength) { ThrownException = new IOException(); throw ThrownException; } } public override void Write(byte[] buffer, int offset, int count) { if (BreakHow == BreakHowType.ThrowOnWrite) { ThrownException = new IOException(); throw ThrownException; } else if (BreakHow == BreakHowType.CancelOnWrite) { ThrownException = new OperationCanceledException(); throw ThrownException; } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationErrors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnClassName_ShouldFail() { var markup = @" using System; class MyClass$$ { public void Goo(int x, string y) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnField_ShouldFail() { var markup = @" using System; class MyClass { int t$$ = 2; public void Goo(int x, string y) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters() { var markup = @"class C { void $$M() { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: true); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail() { var markup = @" class C { public static C $$operator +(C a, C b) { return null; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnClassName_ShouldFail() { var markup = @" using System; class MyClass$$ { public void Goo(int x, string y) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnField_ShouldFail() { var markup = @" using System; class MyClass { int t$$ = 2; public void Goo(int x, string y) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters() { var markup = @"class C { void $$M() { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: true); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail() { var markup = @" class C { public static C $$operator +(C a, C b) { return null; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Core/EditorConfigSettings/Data/CodeStyle/CodeStyleSetting.PerLanguageEnumCodeStyleSetting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private class PerLanguageEnumCodeStyleSetting<T> : EnumCodeStyleSettingBase<T> where T : Enum { private readonly PerLanguageOption2<CodeStyleOption2<T>> _option; private readonly AnalyzerConfigOptions _editorConfigOptions; private readonly OptionSet _visualStudioOptions; public PerLanguageEnumCodeStyleSetting(PerLanguageOption2<CodeStyleOption2<T>> option, string description, T[] enumValues, string[] valueDescriptions, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) : base(description, enumValues, valueDescriptions, option.Group.Description, updater) { _option = option; _editorConfigOptions = editorConfigOptions; _visualStudioOptions = visualStudioOptions; Location = new SettingLocation(IsDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); } public override bool IsDefinedInEditorConfig => _editorConfigOptions.TryGetEditorConfigOption<CodeStyleOption2<T>>(_option, out _); public override SettingLocation Location { get; protected set; } protected override void ChangeSeverity(NotificationOption2 severity) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithNotification(severity)); } public override void ChangeValue(int valueIndex) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithValue(_enumValues[valueIndex])); } protected override CodeStyleOption2<T> GetOption() => _editorConfigOptions.TryGetEditorConfigOption(_option, out CodeStyleOption2<T>? value) && value is not null ? value // TODO(jmarolf): Should we expose duplicate options if the user has a different setting in VB vs. C#? // Today this code will choose whatever option is set for C# as the default. : _visualStudioOptions.GetOption<CodeStyleOption2<T>>(new OptionKey2(_option, LanguageNames.CSharp)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private class PerLanguageEnumCodeStyleSetting<T> : EnumCodeStyleSettingBase<T> where T : Enum { private readonly PerLanguageOption2<CodeStyleOption2<T>> _option; private readonly AnalyzerConfigOptions _editorConfigOptions; private readonly OptionSet _visualStudioOptions; public PerLanguageEnumCodeStyleSetting(PerLanguageOption2<CodeStyleOption2<T>> option, string description, T[] enumValues, string[] valueDescriptions, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) : base(description, enumValues, valueDescriptions, option.Group.Description, updater) { _option = option; _editorConfigOptions = editorConfigOptions; _visualStudioOptions = visualStudioOptions; Location = new SettingLocation(IsDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); } public override bool IsDefinedInEditorConfig => _editorConfigOptions.TryGetEditorConfigOption<CodeStyleOption2<T>>(_option, out _); public override SettingLocation Location { get; protected set; } protected override void ChangeSeverity(NotificationOption2 severity) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithNotification(severity)); } public override void ChangeValue(int valueIndex) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithValue(_enumValues[valueIndex])); } protected override CodeStyleOption2<T> GetOption() => _editorConfigOptions.TryGetEditorConfigOption(_option, out CodeStyleOption2<T>? value) && value is not null ? value // TODO(jmarolf): Should we expose duplicate options if the user has a different setting in VB vs. C#? // Today this code will choose whatever option is set for C# as the default. : _visualStudioOptions.GetOption<CodeStyleOption2<T>>(new OptionKey2(_option, LanguageNames.CSharp)); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/CSharpTest/Completion/ArgumentProviders/DefaultArgumentProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.ArgumentProviders { [Trait(Traits.Feature, Traits.Features.Completion)] public class DefaultArgumentProviderTests : AbstractCSharpArgumentProviderTests { internal override Type GetArgumentProviderType() => typeof(DefaultArgumentProvider); [Theory] [InlineData("System.Collections.DictionaryEntry")] public async Task TestDefaultValueIsDefaultLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "default"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("int?")] [InlineData("System.Int32?")] [InlineData("object")] [InlineData("System.Object")] [InlineData("System.Exception")] public async Task TestDefaultValueIsNullLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "null"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("bool", "false")] [InlineData("System.Boolean", "false")] [InlineData("float", "0.0f")] [InlineData("System.Single", "0.0f")] [InlineData("double", "0.0")] [InlineData("System.Double", "0.0")] [InlineData("decimal", "0.0m")] [InlineData("System.Decimal", "0.0m")] [InlineData("char", @"'\\0'")] [InlineData("System.Char", @"'\\0'")] [InlineData("byte", "(byte)0")] [InlineData("System.Byte", "(byte)0")] [InlineData("sbyte", "(sbyte)0")] [InlineData("System.SByte", "(sbyte)0")] [InlineData("short", "(short)0")] [InlineData("System.Int16", "(short)0")] [InlineData("ushort", "(ushort)0")] [InlineData("System.UInt16", "(ushort)0")] [InlineData("int", "0")] [InlineData("System.Int32", "0")] [InlineData("uint", "0U")] [InlineData("System.UInt32", "0U")] [InlineData("long", "0L")] [InlineData("System.Int64", "0L")] [InlineData("ulong", "0UL")] [InlineData("System.UInt64", "0UL")] public async Task TestDefaultValueIsZero(string type, string literalZero) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, literalZero); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.ArgumentProviders { [Trait(Traits.Feature, Traits.Features.Completion)] public class DefaultArgumentProviderTests : AbstractCSharpArgumentProviderTests { internal override Type GetArgumentProviderType() => typeof(DefaultArgumentProvider); [Theory] [InlineData("System.Collections.DictionaryEntry")] public async Task TestDefaultValueIsDefaultLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "default"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("int?")] [InlineData("System.Int32?")] [InlineData("object")] [InlineData("System.Object")] [InlineData("System.Exception")] public async Task TestDefaultValueIsNullLiteral(string type) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, "null"); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } [Theory] [InlineData("bool", "false")] [InlineData("System.Boolean", "false")] [InlineData("float", "0.0f")] [InlineData("System.Single", "0.0f")] [InlineData("double", "0.0")] [InlineData("System.Double", "0.0")] [InlineData("decimal", "0.0m")] [InlineData("System.Decimal", "0.0m")] [InlineData("char", @"'\\0'")] [InlineData("System.Char", @"'\\0'")] [InlineData("byte", "(byte)0")] [InlineData("System.Byte", "(byte)0")] [InlineData("sbyte", "(sbyte)0")] [InlineData("System.SByte", "(sbyte)0")] [InlineData("short", "(short)0")] [InlineData("System.Int16", "(short)0")] [InlineData("ushort", "(ushort)0")] [InlineData("System.UInt16", "(ushort)0")] [InlineData("int", "0")] [InlineData("System.Int32", "0")] [InlineData("uint", "0U")] [InlineData("System.UInt32", "0U")] [InlineData("long", "0L")] [InlineData("System.Int64", "0L")] [InlineData("ulong", "0UL")] [InlineData("System.UInt64", "0UL")] public async Task TestDefaultValueIsZero(string type, string literalZero) { var markup = $@" class C {{ void Method() {{ this.Target($$); }} void Target({type} arg) {{ }} }} "; await VerifyDefaultValueAsync(markup, literalZero); await VerifyDefaultValueAsync(markup, expectedDefaultValue: "prior", previousDefaultValue: "prior"); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/ViewModel/CodeStyleSettingsViewModel.SettingsSnapshotFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.ViewModel { internal partial class CodeStyleSettingsViewModel { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<CodeStyleSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<CodeStyleSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<CodeStyleSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.ViewModel { internal partial class CodeStyleSettingsViewModel { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<CodeStyleSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<CodeStyleSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<CodeStyleSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationDestructorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationDestructorSymbol : CodeGenerationMethodSymbol { public CodeGenerationDestructorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes) : base(containingType, attributes, Accessibility.NotApplicable, default, returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty, returnTypeAttributes: ImmutableArray<AttributeData>.Empty) { } public override MethodKind MethodKind => MethodKind.Destructor; protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationDestructorSymbol(this.ContainingType, this.GetAttributes()); CodeGenerationDestructorInfo.Attach(result, CodeGenerationDestructorInfo.GetTypeName(this), CodeGenerationDestructorInfo.GetStatements(this)); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationDestructorSymbol : CodeGenerationMethodSymbol { public CodeGenerationDestructorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes) : base(containingType, attributes, Accessibility.NotApplicable, default, returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty, returnTypeAttributes: ImmutableArray<AttributeData>.Empty) { } public override MethodKind MethodKind => MethodKind.Destructor; protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationDestructorSymbol(this.ContainingType, this.GetAttributes()); CodeGenerationDestructorInfo.Attach(result, CodeGenerationDestructorInfo.GetTypeName(this), CodeGenerationDestructorInfo.GetStatements(this)); return result; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxKindsServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { [ExportLanguageServiceFactory(typeof(ISyntaxKindsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxKindsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxKindsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSyntaxKindsService.Instance; private sealed class CSharpSyntaxKindsService : CSharpSyntaxKinds, ISyntaxKindsService { public static new readonly CSharpSyntaxKindsService Instance = new(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { [ExportLanguageServiceFactory(typeof(ISyntaxKindsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxKindsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxKindsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSyntaxKindsService.Instance; private sealed class CSharpSyntaxKindsService : CSharpSyntaxKinds, ISyntaxKindsService { public static new readonly CSharpSyntaxKindsService Instance = new(); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IChecksummedPersistentStorageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PersistentStorage; namespace Microsoft.CodeAnalysis.Host { internal interface IChecksummedPersistentStorageService : IPersistentStorageService { new ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken); ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, bool checkBranchId, CancellationToken cancellationToken); ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Workspace workspace, SolutionKey solutionKey, bool checkBranchId, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PersistentStorage; namespace Microsoft.CodeAnalysis.Host { internal interface IChecksummedPersistentStorageService : IPersistentStorageService { new ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken); ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, bool checkBranchId, CancellationToken cancellationToken); ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Workspace workspace, SolutionKey solutionKey, bool checkBranchId, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IndexerAccess.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { private BoundExpression MakeDynamicIndexerAccessReceiver(BoundDynamicIndexerAccess indexerAccess, BoundExpression loweredReceiver) { BoundExpression result; string? indexedPropertyName = indexerAccess.TryGetIndexedPropertyName(); if (indexedPropertyName != null) { // Dev12 forces the receiver to be typed to dynamic to workaround a bug in the runtime binder. // See DynamicRewriter::FixupIndexedProperty: // "If we don't do this, then the calling object is statically typed and we pass the UseCompileTimeType to the runtime binder." // However, with the cast the scenarios don't work either, so we don't mimic Dev12. // loweredReceiver = BoundConversion.Synthesized(loweredReceiver.Syntax, loweredReceiver, Conversion.Identity, false, false, null, DynamicTypeSymbol.Instance); result = _dynamicFactory.MakeDynamicGetMember(loweredReceiver, indexedPropertyName, resultIndexed: true).ToExpression(); } else { result = loweredReceiver; } return result; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var loweredReceiver = VisitExpression(node.Receiver); // There are no target types for dynamic expression. AssertNoImplicitInterpolatedStringHandlerConversions(node.Arguments); var loweredArguments = VisitList(node.Arguments); return MakeDynamicGetIndex(node, loweredReceiver, loweredArguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt); } private BoundExpression MakeDynamicGetIndex( BoundDynamicIndexerAccess node, BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { // If we are calling a method on a NoPIA type, we need to embed all methods/properties // with the matching name of this dynamic invocation. EmbedIfNeedTo(loweredReceiver, node.ApplicableIndexers, node.Syntax); return _dynamicFactory.MakeDynamicGetIndex( MakeDynamicIndexerAccessReceiver(node, loweredReceiver), loweredArguments, argumentNames, refKinds).ToExpression(); } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { Debug.Assert(node.Indexer.IsIndexer || node.Indexer.IsIndexedProperty); Debug.Assert((object?)node.Indexer.GetOwnOrInheritedGetMethod() != null); return VisitIndexerAccess(node, isLeftOfAssignment: false); } private BoundExpression VisitIndexerAccess(BoundIndexerAccess node, bool isLeftOfAssignment) { PropertySymbol indexer = node.Indexer; Debug.Assert(indexer.IsIndexer || indexer.IsIndexedProperty); // Rewrite the receiver. BoundExpression? rewrittenReceiver = VisitExpression(node.ReceiverOpt); Debug.Assert(rewrittenReceiver is { }); return MakeIndexerAccess( node.Syntax, rewrittenReceiver, indexer, node.Arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.Type, node, isLeftOfAssignment); } private BoundExpression MakeIndexerAccess( SyntaxNode syntax, BoundExpression rewrittenReceiver, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, BoundIndexerAccess? oldNodeOpt, bool isLeftOfAssignment) { if (isLeftOfAssignment && indexer.RefKind == RefKind.None) { // This is an indexer set access. We return a BoundIndexerAccess node here. // This node will be rewritten with MakePropertyAssignment when rewriting the enclosing BoundAssignmentOperator. return oldNodeOpt != null ? oldNodeOpt.Update(rewrittenReceiver, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, type) : new BoundIndexerAccess(syntax, rewrittenReceiver, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, type); } else { var getMethod = indexer.GetOwnOrInheritedGetMethod(); Debug.Assert(getMethod is not null); ImmutableArray<BoundExpression> rewrittenArguments = VisitArguments( arguments, indexer, argsToParamsOpt, argumentRefKindsOpt, ref rewrittenReceiver!, out ArrayBuilder<LocalSymbol>? temps); rewrittenArguments = MakeArguments( syntax, rewrittenArguments, indexer, expanded, argsToParamsOpt, ref argumentRefKindsOpt, ref temps, enableCallerInfo: ThreeState.True); BoundExpression call = MakePropertyGetAccess(syntax, rewrittenReceiver, indexer, rewrittenArguments, getMethod); if (temps.Count == 0) { temps.Free(); return call; } else { return new BoundSequence( syntax, temps.ToImmutableAndFree(), ImmutableArray<BoundExpression>.Empty, call, type); } } } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { return VisitIndexOrRangePatternIndexerAccess(node, isLeftOfAssignment: false); } private BoundSequence VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node, bool isLeftOfAssignment) { if (TypeSymbol.Equals( node.Argument.Type, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)) { return VisitIndexPatternIndexerAccess( node.Syntax, node.Receiver, node.LengthOrCountProperty, (PropertySymbol)node.PatternSymbol, node.Argument, isLeftOfAssignment: isLeftOfAssignment); } else { Debug.Assert(TypeSymbol.Equals( node.Argument.Type, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)); return VisitRangePatternIndexerAccess( node.Receiver, node.LengthOrCountProperty, (MethodSymbol)node.PatternSymbol, node.Argument); } } private BoundSequence VisitIndexPatternIndexerAccess( SyntaxNode syntax, BoundExpression receiver, PropertySymbol lengthOrCountProperty, PropertySymbol intIndexer, BoundExpression argument, bool isLeftOfAssignment) { // Lowered code: // ref var receiver = receiverExpr; // int length = receiver.length; // int index = argument.GetOffset(length); // receiver[index]; var F = _factory; Debug.Assert(receiver.Type is { }); var receiverLocal = F.StoreToTemp( VisitExpression(receiver), out var receiverStore, // Store the receiver as a ref local if it's a value type to ensure side effects are propagated receiver.Type.IsReferenceType ? RefKind.None : RefKind.Ref); var lengthLocal = F.StoreToTemp(F.Property(receiverLocal, lengthOrCountProperty), out var lengthStore); var indexLocal = F.StoreToTemp( MakePatternIndexOffsetExpression(argument, lengthLocal, out bool usedLength), out var indexStore); // Hint the array size here because the only case when the length is not needed is if the // user writes code like receiver[(Index)offset], as opposed to just receiver[offset] // and that will probably be very rare. var locals = ArrayBuilder<LocalSymbol>.GetInstance(3); var sideEffects = ArrayBuilder<BoundExpression>.GetInstance(3); locals.Add(receiverLocal.LocalSymbol); sideEffects.Add(receiverStore); if (usedLength) { locals.Add(lengthLocal.LocalSymbol); sideEffects.Add(lengthStore); } locals.Add(indexLocal.LocalSymbol); sideEffects.Add(indexStore); return (BoundSequence)F.Sequence( locals.ToImmutable(), sideEffects.ToImmutable(), MakeIndexerAccess( syntax, receiverLocal, intIndexer, ImmutableArray.Create<BoundExpression>(indexLocal), default, default, expanded: false, argsToParamsOpt: default, defaultArguments: default, intIndexer.Type, oldNodeOpt: null, isLeftOfAssignment)); } /// <summary> /// Used to construct a pattern index offset expression, of the form /// `unloweredExpr.GetOffset(lengthAccess)` /// where unloweredExpr is an expression of type System.Index and the /// lengthAccess retrieves the length of the indexing target. /// </summary> /// <param name="unloweredExpr">The unlowered argument to the indexing expression</param> /// <param name="lengthAccess"> /// An expression accessing the length of the indexing target. This should /// be a non-side-effecting operation. /// </param> /// <param name="usedLength"> /// True if we were able to optimize the <paramref name="unloweredExpr"/> /// to use the <paramref name="lengthAccess"/> operation directly on the receiver, instead of /// using System.Index helpers. /// </param> private BoundExpression MakePatternIndexOffsetExpression( BoundExpression unloweredExpr, BoundExpression lengthAccess, out bool usedLength) { Debug.Assert(TypeSymbol.Equals( unloweredExpr.Type, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)); var F = _factory; if (unloweredExpr is BoundFromEndIndexExpression hatExpression) { // If the System.Index argument is `^index`, we can replace the // `argument.GetOffset(length)` call with `length - index` Debug.Assert(hatExpression.Operand is { Type: { SpecialType: SpecialType.System_Int32 } }); usedLength = true; return F.IntSubtract(lengthAccess, VisitExpression(hatExpression.Operand)); } else if (unloweredExpr is BoundConversion { Operand: { Type: { SpecialType: SpecialType.System_Int32 } } operand }) { // If the System.Index argument is a conversion from int to Index we // can return the int directly usedLength = false; return VisitExpression(operand); } else { usedLength = true; return F.Call( VisitExpression(unloweredExpr), WellKnownMember.System_Index__GetOffset, lengthAccess); } } private BoundSequence VisitRangePatternIndexerAccess( BoundExpression receiver, PropertySymbol lengthOrCountProperty, MethodSymbol sliceMethod, BoundExpression rangeArg) { Debug.Assert(TypeSymbol.Equals( rangeArg.Type, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)); // Lowered code without optimizations: // var receiver = receiverExpr; // int length = receiver.length; // Range range = argumentExpr; // int start = range.Start.GetOffset(length) // int rangeSize = range.End.GetOffset(length) - start // receiver.Slice(start, rangeSize) var F = _factory; var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var sideEffectsBuilder = ArrayBuilder<BoundExpression>.GetInstance(); var receiverLocal = F.StoreToTemp(VisitExpression(receiver), out var receiverStore); var lengthLocal = F.StoreToTemp(F.Property(receiverLocal, lengthOrCountProperty), out var lengthStore); localsBuilder.Add(receiverLocal.LocalSymbol); sideEffectsBuilder.Add(receiverStore); BoundExpression startExpr; BoundExpression rangeSizeExpr; if (rangeArg is BoundRangeExpression rangeExpr) { // If we know that the input is a range expression, we can // optimize by pulling it apart inline, so // // Range range = argumentExpr; // int start = range.Start.GetOffset(length) // int rangeSize = range.End.GetOffset(length) - start // // is, with `start..end`: // // int start = start.GetOffset(length) // int rangeSize = end.GetOffset(length) - start bool usedLength = false; if (rangeExpr.LeftOperandOpt is BoundExpression left) { var startLocal = F.StoreToTemp( MakePatternIndexOffsetExpression(rangeExpr.LeftOperandOpt, lengthLocal, out usedLength), out var startStore); localsBuilder.Add(startLocal.LocalSymbol); sideEffectsBuilder.Add(startStore); startExpr = startLocal; } else { startExpr = F.Literal(0); } BoundExpression endExpr; if (rangeExpr.RightOperandOpt is BoundExpression right) { endExpr = MakePatternIndexOffsetExpression( right, lengthLocal, out bool usedLengthTemp); usedLength |= usedLengthTemp; } else { usedLength = true; endExpr = lengthLocal; } if (usedLength) { // If we used the length, it needs to be calculated after the receiver (the // first bound node in the builder) and before the first use, which could be the // second or third node in the builder localsBuilder.Insert(1, lengthLocal.LocalSymbol); sideEffectsBuilder.Insert(1, lengthStore); } var rangeSizeLocal = F.StoreToTemp( F.IntSubtract(endExpr, startExpr), out var rangeStore); localsBuilder.Add(rangeSizeLocal.LocalSymbol); sideEffectsBuilder.Add(rangeStore); rangeSizeExpr = rangeSizeLocal; } else { var rangeLocal = F.StoreToTemp(VisitExpression(rangeArg), out var rangeStore); localsBuilder.Add(lengthLocal.LocalSymbol); sideEffectsBuilder.Add(lengthStore); localsBuilder.Add(rangeLocal.LocalSymbol); sideEffectsBuilder.Add(rangeStore); var startLocal = F.StoreToTemp( F.Call( F.Call(rangeLocal, F.WellKnownMethod(WellKnownMember.System_Range__get_Start)), F.WellKnownMethod(WellKnownMember.System_Index__GetOffset), lengthLocal), out var startStore); localsBuilder.Add(startLocal.LocalSymbol); sideEffectsBuilder.Add(startStore); startExpr = startLocal; var rangeSizeLocal = F.StoreToTemp( F.IntSubtract( F.Call( F.Call(rangeLocal, F.WellKnownMethod(WellKnownMember.System_Range__get_End)), F.WellKnownMethod(WellKnownMember.System_Index__GetOffset), lengthLocal), startExpr), out var rangeSizeStore); localsBuilder.Add(rangeSizeLocal.LocalSymbol); sideEffectsBuilder.Add(rangeSizeStore); rangeSizeExpr = rangeSizeLocal; } return (BoundSequence)F.Sequence( localsBuilder.ToImmutableAndFree(), sideEffectsBuilder.ToImmutableAndFree(), F.Call(receiverLocal, sliceMethod, startExpr, rangeSizeExpr)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { private BoundExpression MakeDynamicIndexerAccessReceiver(BoundDynamicIndexerAccess indexerAccess, BoundExpression loweredReceiver) { BoundExpression result; string? indexedPropertyName = indexerAccess.TryGetIndexedPropertyName(); if (indexedPropertyName != null) { // Dev12 forces the receiver to be typed to dynamic to workaround a bug in the runtime binder. // See DynamicRewriter::FixupIndexedProperty: // "If we don't do this, then the calling object is statically typed and we pass the UseCompileTimeType to the runtime binder." // However, with the cast the scenarios don't work either, so we don't mimic Dev12. // loweredReceiver = BoundConversion.Synthesized(loweredReceiver.Syntax, loweredReceiver, Conversion.Identity, false, false, null, DynamicTypeSymbol.Instance); result = _dynamicFactory.MakeDynamicGetMember(loweredReceiver, indexedPropertyName, resultIndexed: true).ToExpression(); } else { result = loweredReceiver; } return result; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var loweredReceiver = VisitExpression(node.Receiver); // There are no target types for dynamic expression. AssertNoImplicitInterpolatedStringHandlerConversions(node.Arguments); var loweredArguments = VisitList(node.Arguments); return MakeDynamicGetIndex(node, loweredReceiver, loweredArguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt); } private BoundExpression MakeDynamicGetIndex( BoundDynamicIndexerAccess node, BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { // If we are calling a method on a NoPIA type, we need to embed all methods/properties // with the matching name of this dynamic invocation. EmbedIfNeedTo(loweredReceiver, node.ApplicableIndexers, node.Syntax); return _dynamicFactory.MakeDynamicGetIndex( MakeDynamicIndexerAccessReceiver(node, loweredReceiver), loweredArguments, argumentNames, refKinds).ToExpression(); } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { Debug.Assert(node.Indexer.IsIndexer || node.Indexer.IsIndexedProperty); Debug.Assert((object?)node.Indexer.GetOwnOrInheritedGetMethod() != null); return VisitIndexerAccess(node, isLeftOfAssignment: false); } private BoundExpression VisitIndexerAccess(BoundIndexerAccess node, bool isLeftOfAssignment) { PropertySymbol indexer = node.Indexer; Debug.Assert(indexer.IsIndexer || indexer.IsIndexedProperty); // Rewrite the receiver. BoundExpression? rewrittenReceiver = VisitExpression(node.ReceiverOpt); Debug.Assert(rewrittenReceiver is { }); return MakeIndexerAccess( node.Syntax, rewrittenReceiver, indexer, node.Arguments, node.ArgumentNamesOpt, node.ArgumentRefKindsOpt, node.Expanded, node.ArgsToParamsOpt, node.DefaultArguments, node.Type, node, isLeftOfAssignment); } private BoundExpression MakeIndexerAccess( SyntaxNode syntax, BoundExpression rewrittenReceiver, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, BoundIndexerAccess? oldNodeOpt, bool isLeftOfAssignment) { if (isLeftOfAssignment && indexer.RefKind == RefKind.None) { // This is an indexer set access. We return a BoundIndexerAccess node here. // This node will be rewritten with MakePropertyAssignment when rewriting the enclosing BoundAssignmentOperator. return oldNodeOpt != null ? oldNodeOpt.Update(rewrittenReceiver, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, type) : new BoundIndexerAccess(syntax, rewrittenReceiver, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, type); } else { var getMethod = indexer.GetOwnOrInheritedGetMethod(); Debug.Assert(getMethod is not null); ImmutableArray<BoundExpression> rewrittenArguments = VisitArguments( arguments, indexer, argsToParamsOpt, argumentRefKindsOpt, ref rewrittenReceiver!, out ArrayBuilder<LocalSymbol>? temps); rewrittenArguments = MakeArguments( syntax, rewrittenArguments, indexer, expanded, argsToParamsOpt, ref argumentRefKindsOpt, ref temps, enableCallerInfo: ThreeState.True); BoundExpression call = MakePropertyGetAccess(syntax, rewrittenReceiver, indexer, rewrittenArguments, getMethod); if (temps.Count == 0) { temps.Free(); return call; } else { return new BoundSequence( syntax, temps.ToImmutableAndFree(), ImmutableArray<BoundExpression>.Empty, call, type); } } } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { return VisitIndexOrRangePatternIndexerAccess(node, isLeftOfAssignment: false); } private BoundSequence VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node, bool isLeftOfAssignment) { if (TypeSymbol.Equals( node.Argument.Type, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)) { return VisitIndexPatternIndexerAccess( node.Syntax, node.Receiver, node.LengthOrCountProperty, (PropertySymbol)node.PatternSymbol, node.Argument, isLeftOfAssignment: isLeftOfAssignment); } else { Debug.Assert(TypeSymbol.Equals( node.Argument.Type, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)); return VisitRangePatternIndexerAccess( node.Receiver, node.LengthOrCountProperty, (MethodSymbol)node.PatternSymbol, node.Argument); } } private BoundSequence VisitIndexPatternIndexerAccess( SyntaxNode syntax, BoundExpression receiver, PropertySymbol lengthOrCountProperty, PropertySymbol intIndexer, BoundExpression argument, bool isLeftOfAssignment) { // Lowered code: // ref var receiver = receiverExpr; // int length = receiver.length; // int index = argument.GetOffset(length); // receiver[index]; var F = _factory; Debug.Assert(receiver.Type is { }); var receiverLocal = F.StoreToTemp( VisitExpression(receiver), out var receiverStore, // Store the receiver as a ref local if it's a value type to ensure side effects are propagated receiver.Type.IsReferenceType ? RefKind.None : RefKind.Ref); var lengthLocal = F.StoreToTemp(F.Property(receiverLocal, lengthOrCountProperty), out var lengthStore); var indexLocal = F.StoreToTemp( MakePatternIndexOffsetExpression(argument, lengthLocal, out bool usedLength), out var indexStore); // Hint the array size here because the only case when the length is not needed is if the // user writes code like receiver[(Index)offset], as opposed to just receiver[offset] // and that will probably be very rare. var locals = ArrayBuilder<LocalSymbol>.GetInstance(3); var sideEffects = ArrayBuilder<BoundExpression>.GetInstance(3); locals.Add(receiverLocal.LocalSymbol); sideEffects.Add(receiverStore); if (usedLength) { locals.Add(lengthLocal.LocalSymbol); sideEffects.Add(lengthStore); } locals.Add(indexLocal.LocalSymbol); sideEffects.Add(indexStore); return (BoundSequence)F.Sequence( locals.ToImmutable(), sideEffects.ToImmutable(), MakeIndexerAccess( syntax, receiverLocal, intIndexer, ImmutableArray.Create<BoundExpression>(indexLocal), default, default, expanded: false, argsToParamsOpt: default, defaultArguments: default, intIndexer.Type, oldNodeOpt: null, isLeftOfAssignment)); } /// <summary> /// Used to construct a pattern index offset expression, of the form /// `unloweredExpr.GetOffset(lengthAccess)` /// where unloweredExpr is an expression of type System.Index and the /// lengthAccess retrieves the length of the indexing target. /// </summary> /// <param name="unloweredExpr">The unlowered argument to the indexing expression</param> /// <param name="lengthAccess"> /// An expression accessing the length of the indexing target. This should /// be a non-side-effecting operation. /// </param> /// <param name="usedLength"> /// True if we were able to optimize the <paramref name="unloweredExpr"/> /// to use the <paramref name="lengthAccess"/> operation directly on the receiver, instead of /// using System.Index helpers. /// </param> private BoundExpression MakePatternIndexOffsetExpression( BoundExpression unloweredExpr, BoundExpression lengthAccess, out bool usedLength) { Debug.Assert(TypeSymbol.Equals( unloweredExpr.Type, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)); var F = _factory; if (unloweredExpr is BoundFromEndIndexExpression hatExpression) { // If the System.Index argument is `^index`, we can replace the // `argument.GetOffset(length)` call with `length - index` Debug.Assert(hatExpression.Operand is { Type: { SpecialType: SpecialType.System_Int32 } }); usedLength = true; return F.IntSubtract(lengthAccess, VisitExpression(hatExpression.Operand)); } else if (unloweredExpr is BoundConversion { Operand: { Type: { SpecialType: SpecialType.System_Int32 } } operand }) { // If the System.Index argument is a conversion from int to Index we // can return the int directly usedLength = false; return VisitExpression(operand); } else { usedLength = true; return F.Call( VisitExpression(unloweredExpr), WellKnownMember.System_Index__GetOffset, lengthAccess); } } private BoundSequence VisitRangePatternIndexerAccess( BoundExpression receiver, PropertySymbol lengthOrCountProperty, MethodSymbol sliceMethod, BoundExpression rangeArg) { Debug.Assert(TypeSymbol.Equals( rangeArg.Type, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)); // Lowered code without optimizations: // var receiver = receiverExpr; // int length = receiver.length; // Range range = argumentExpr; // int start = range.Start.GetOffset(length) // int rangeSize = range.End.GetOffset(length) - start // receiver.Slice(start, rangeSize) var F = _factory; var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var sideEffectsBuilder = ArrayBuilder<BoundExpression>.GetInstance(); var receiverLocal = F.StoreToTemp(VisitExpression(receiver), out var receiverStore); var lengthLocal = F.StoreToTemp(F.Property(receiverLocal, lengthOrCountProperty), out var lengthStore); localsBuilder.Add(receiverLocal.LocalSymbol); sideEffectsBuilder.Add(receiverStore); BoundExpression startExpr; BoundExpression rangeSizeExpr; if (rangeArg is BoundRangeExpression rangeExpr) { // If we know that the input is a range expression, we can // optimize by pulling it apart inline, so // // Range range = argumentExpr; // int start = range.Start.GetOffset(length) // int rangeSize = range.End.GetOffset(length) - start // // is, with `start..end`: // // int start = start.GetOffset(length) // int rangeSize = end.GetOffset(length) - start bool usedLength = false; if (rangeExpr.LeftOperandOpt is BoundExpression left) { var startLocal = F.StoreToTemp( MakePatternIndexOffsetExpression(rangeExpr.LeftOperandOpt, lengthLocal, out usedLength), out var startStore); localsBuilder.Add(startLocal.LocalSymbol); sideEffectsBuilder.Add(startStore); startExpr = startLocal; } else { startExpr = F.Literal(0); } BoundExpression endExpr; if (rangeExpr.RightOperandOpt is BoundExpression right) { endExpr = MakePatternIndexOffsetExpression( right, lengthLocal, out bool usedLengthTemp); usedLength |= usedLengthTemp; } else { usedLength = true; endExpr = lengthLocal; } if (usedLength) { // If we used the length, it needs to be calculated after the receiver (the // first bound node in the builder) and before the first use, which could be the // second or third node in the builder localsBuilder.Insert(1, lengthLocal.LocalSymbol); sideEffectsBuilder.Insert(1, lengthStore); } var rangeSizeLocal = F.StoreToTemp( F.IntSubtract(endExpr, startExpr), out var rangeStore); localsBuilder.Add(rangeSizeLocal.LocalSymbol); sideEffectsBuilder.Add(rangeStore); rangeSizeExpr = rangeSizeLocal; } else { var rangeLocal = F.StoreToTemp(VisitExpression(rangeArg), out var rangeStore); localsBuilder.Add(lengthLocal.LocalSymbol); sideEffectsBuilder.Add(lengthStore); localsBuilder.Add(rangeLocal.LocalSymbol); sideEffectsBuilder.Add(rangeStore); var startLocal = F.StoreToTemp( F.Call( F.Call(rangeLocal, F.WellKnownMethod(WellKnownMember.System_Range__get_Start)), F.WellKnownMethod(WellKnownMember.System_Index__GetOffset), lengthLocal), out var startStore); localsBuilder.Add(startLocal.LocalSymbol); sideEffectsBuilder.Add(startStore); startExpr = startLocal; var rangeSizeLocal = F.StoreToTemp( F.IntSubtract( F.Call( F.Call(rangeLocal, F.WellKnownMethod(WellKnownMember.System_Range__get_End)), F.WellKnownMethod(WellKnownMember.System_Index__GetOffset), lengthLocal), startExpr), out var rangeSizeStore); localsBuilder.Add(rangeSizeLocal.LocalSymbol); sideEffectsBuilder.Add(rangeSizeStore); rangeSizeExpr = rangeSizeLocal; } return (BoundSequence)F.Sequence( localsBuilder.ToImmutableAndFree(), sideEffectsBuilder.ToImmutableAndFree(), F.Call(receiverLocal, sliceMethod, startExpr, rangeSizeExpr)); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/Lists/MemberListItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class MemberListItem : SymbolListItem<ISymbol> { private readonly MemberKind _kind; private readonly bool _isInherited; internal MemberListItem(ProjectId projectId, ISymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden, bool isInherited) : base(projectId, symbol, displayText, fullNameText, searchText, isHidden) { _isInherited = isInherited; switch (symbol.Kind) { case SymbolKind.Event: _kind = MemberKind.Event; break; case SymbolKind.Field: var fieldSymbol = (IFieldSymbol)symbol; if (fieldSymbol.ContainingType.TypeKind == TypeKind.Enum) { _kind = MemberKind.EnumMember; } else { _kind = fieldSymbol.IsConst ? MemberKind.Constant : MemberKind.Field; } break; case SymbolKind.Method: var methodSymbol = (IMethodSymbol)symbol; _kind = methodSymbol.MethodKind == MethodKind.Conversion || methodSymbol.MethodKind == MethodKind.UserDefinedOperator ? MemberKind.Operator : MemberKind.Method; break; case SymbolKind.Property: _kind = MemberKind.Property; break; default: Debug.Fail("Unsupported symbol for member: " + symbol.Kind.ToString()); _kind = MemberKind.None; break; } } public bool IsInherited { get { return _isInherited; } } public MemberKind Kind { get { return _kind; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class MemberListItem : SymbolListItem<ISymbol> { private readonly MemberKind _kind; private readonly bool _isInherited; internal MemberListItem(ProjectId projectId, ISymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden, bool isInherited) : base(projectId, symbol, displayText, fullNameText, searchText, isHidden) { _isInherited = isInherited; switch (symbol.Kind) { case SymbolKind.Event: _kind = MemberKind.Event; break; case SymbolKind.Field: var fieldSymbol = (IFieldSymbol)symbol; if (fieldSymbol.ContainingType.TypeKind == TypeKind.Enum) { _kind = MemberKind.EnumMember; } else { _kind = fieldSymbol.IsConst ? MemberKind.Constant : MemberKind.Field; } break; case SymbolKind.Method: var methodSymbol = (IMethodSymbol)symbol; _kind = methodSymbol.MethodKind == MethodKind.Conversion || methodSymbol.MethodKind == MethodKind.UserDefinedOperator ? MemberKind.Operator : MemberKind.Method; break; case SymbolKind.Property: _kind = MemberKind.Property; break; default: Debug.Fail("Unsupported symbol for member: " + symbol.Kind.ToString()); _kind = MemberKind.None; break; } } public bool IsInherited { get { return _isInherited; } } public MemberKind Kind { get { return _kind; } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IParameterReferenceExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IParameterReferenceExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_TupleExpression() { string source = @" class Class1 { public void M(int x, int y) { var tuple = /*<bind>*/(x, x + y)/*</bind>*/; } } "; string expectedOperationTree = @" ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, x + y)') NaturalType: (System.Int32 x, System.Int32) Elements(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'tuple' is assigned but its value is never used // var tuple = /*<bind>*/(x, x + y)/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "tuple").WithArguments("tuple").WithLocation(6, 13) }; VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_TupleDeconstruction() { string source = @" class Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } public void Deconstruct(out int x, out int y) { x = X; y = Y; } } class Class1 { public void M(Point point) { /*<bind>*/var (x, y) = point/*</bind>*/; } } "; string expectedOperationTree = @" IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y)) (Syntax: 'var (x, y) = point') Left: IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x, System.Int32 y)) (Syntax: 'var (x, y)') ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)') NaturalType: (System.Int32 x, System.Int32 y) Elements(2): ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') Right: IParameterReferenceOperation: point (OperationKind.ParameterReference, Type: Point) (Syntax: 'point') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_AnonymousObjectCreation() { string source = @" class Class1 { public void M(int x, string y) { var v = /*<bind>*/new { Amount = x, Message = ""Hello"" + y }/*</bind>*/; } } "; string expectedOperationTree = @" IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 Amount, System.String Message>) (Syntax: 'new { Amoun ... ello"" + y }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Amount = x') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 Amount, System.String Message>.Amount { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Amount') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 Amount, System.String Message>, IsImplicit) (Syntax: 'new { Amoun ... ello"" + y }') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'Message = ""Hello"" + y') Left: IPropertyReferenceOperation: System.String <anonymous type: System.Int32 Amount, System.String Message>.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'Message') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 Amount, System.String Message>, IsImplicit) (Syntax: 'new { Amoun ... ello"" + y }') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '""Hello"" + y') Left: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Hello"") (Syntax: '""Hello""') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AnonymousObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_QueryExpression() { string source = @" using System.Linq; using System.Collections.Generic; struct Customer { public string Name { get; set; } public string Address { get; set; } } class Class1 { public void M(List<Customer> customers) { var result = /*<bind>*/from cust in customers select cust.Name/*</bind>*/; } } "; string expectedOperationTree = @" ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from cust i ... t cust.Name') Expression: IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<Customer, System.String>(this System.Collections.Generic.IEnumerable<Customer> source, System.Func<Customer, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select cust.Name') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from cust in customers') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<Customer>, IsImplicit) (Syntax: 'from cust in customers') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: customers (OperationKind.ParameterReference, Type: System.Collections.Generic.List<Customer>) (Syntax: 'customers') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'cust.Name') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<Customer, System.String>, IsImplicit) (Syntax: 'cust.Name') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'cust.Name') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'cust.Name') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'cust.Name') ReturnedValue: IPropertyReferenceOperation: System.String Customer.Name { get; set; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'cust.Name') Instance Receiver: IParameterReferenceOperation: cust (OperationKind.ParameterReference, Type: Customer) (Syntax: 'cust') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_ObjectAndCollectionInitializer() { string source = @" using System.Collections.Generic; internal class Class { public int X { get; set; } public List<int> Y { get; set; } public Dictionary<int, int> Z { get; set; } public Class C { get; set; } public void M(int x, int y, int z) { var c = /*<bind>*/new Class() { X = x, Y = { x, y, 3 }, Z = { { x, y } }, C = { X = z } }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: Class..ctor()) (OperationKind.ObjectCreation, Type: Class) (Syntax: 'new Class() ... { X = z } }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = x, Y ... { X = z } }') Initializers(4): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = x') Left: IPropertyReferenceOperation: System.Int32 Class.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IMemberInitializerOperation (OperationKind.MemberInitializer, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y = { x, y, 3 }') InitializedMember: IPropertyReferenceOperation: System.Collections.Generic.List<System.Int32> Class.Y { get; set; } (OperationKind.PropertyReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Y') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '{ x, y, 3 }') Initializers(3): IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IMemberInitializerOperation (OperationKind.MemberInitializer, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z = { { x, y } }') InitializedMember: IPropertyReferenceOperation: System.Collections.Generic.Dictionary<System.Int32, System.Int32> Class.Z { get; set; } (OperationKind.PropertyReference, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Z') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: '{ { x, y } }') Initializers(1): IInvocationOperation ( void System.Collections.Generic.Dictionary<System.Int32, System.Int32>.Add(System.Int32 key, System.Int32 value)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{ x, y }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>, IsImplicit) (Syntax: 'Z') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IMemberInitializerOperation (OperationKind.MemberInitializer, Type: Class) (Syntax: 'C = { X = z }') InitializedMember: IPropertyReferenceOperation: Class Class.C { get; set; } (OperationKind.PropertyReference, Type: Class) (Syntax: 'C') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'C') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = z }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = z') Left: IPropertyReferenceOperation: System.Int32 Class.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X') Right: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DelegateCreationExpressionWithLambdaArgument() { string source = @" using System; class Class { // Used parameter methods public void UsedParameterMethod1(Action a) { Action a2 = /*<bind>*/new Action(() => { a(); })/*</bind>*/; } } "; string expectedOperationTree = @" IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action( ... })') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a();') Expression: IInvocationOperation (virtual void System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'a()') Instance Receiver: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a') Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ ... }') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DelegateCreationExpressionWithMethodArgument() { string source = @" using System; class Class { public delegate void Delegate(int x, int y); public void Method(Delegate d) { var a = /*<bind>*/new Delegate(Method2)/*</bind>*/; } public void Method2(int x, int y) { } } "; string expectedOperationTree = @" IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Class.Delegate) (Syntax: 'new Delegate(Method2)') Target: IMethodReferenceOperation: void Class.Method2(System.Int32 x, System.Int32 y) (OperationKind.MethodReference, Type: null) (Syntax: 'Method2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Method2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DelegateCreationExpressionWithInvalidArgument() { string source = @" using System; class Class { public delegate void Delegate(int x, int y); public void Method(int x) { var a = /*<bind>*/new Delegate(x)/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: Class.Delegate, IsInvalid) (Syntax: 'new Delegate(x)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0149: Method name expected // var a = /*<bind>*/new Delegate(x)/*</bind>*/; Diagnostic(ErrorCode.ERR_MethodNameExpected, "x").WithLocation(10, 40) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicCollectionInitializer() { string source = @" using System.Collections.Generic; internal class Class { public dynamic X { get; set; } public void M(int x, int y) { var c = new Class() /*<bind>*/{ X = { { x, y } } }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = { { x, y } } }') Initializers(1): IMemberInitializerOperation (OperationKind.MemberInitializer, Type: dynamic) (Syntax: 'X = { { x, y } }') InitializedMember: IPropertyReferenceOperation: dynamic Class.X { get; set; } (OperationKind.PropertyReference, Type: dynamic) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: dynamic) (Syntax: '{ { x, y } }') Initializers(1): IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Void) (Syntax: '{ x, y }') Expression: IDynamicMemberReferenceOperation (Member Name: ""Add"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null, IsImplicit) (Syntax: 'X') Type Arguments(0) Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: dynamic, IsImplicit) (Syntax: 'X') Arguments(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_NameOfExpression() { string source = @" class Class1 { public string M(int x) { return /*<bind>*/nameof(x)/*</bind>*/; } } "; string expectedOperationTree = @" INameOfOperation (OperationKind.NameOf, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_PointerIndirectionExpression() { string source = @" class Class1 { public unsafe int M(int *x) { return /*<bind>*/*x/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '*x') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32*) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // public unsafe int M(int *x) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(4, 23) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_FixedLocalInitializer() { string source = @" using System.Collections.Generic; internal class Class { public unsafe void M(int[] array) { fixed (int* /*<bind>*/p = array/*</bind>*/) { *p = 1; } } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = array') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= array') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'array') Children(1): IParameterReferenceOperation: array (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'array') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // public unsafe void M(int[] array) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_RefTypeOperator() { string source = @" class Class1 { public System.Type M(System.TypedReference x) { return /*<bind>*/__reftype(x)/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__reftype(x)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.TypedReference) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<RefTypeExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_MakeRefOperator() { string source = @" class Class1 { public void M(System.Type x) { var y = /*<bind>*/__makeref(x)/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__makeref(x)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Type) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<MakeRefExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_RefValueOperator() { string source = @" class Class1 { public void M(System.TypedReference x) { var y = /*<bind>*/__refvalue(x, int)/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__refvalue(x, int)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.TypedReference) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<RefValueExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicIndexerAccess() { string source = @" class Class1 { public void M(dynamic d, int x) { var /*<bind>*/y = d[x]/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: dynamic y) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y = d[x]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= d[x]') IDynamicIndexerAccessOperation (OperationKind.DynamicIndexerAccess, Type: dynamic) (Syntax: 'd[x]') Expression: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicMemberAccess() { string source = @" class Class1 { public void M(dynamic x, int y) { var z = /*<bind>*/x.M(y)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'x.M(y)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'x.M') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') Arguments(1): IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicInvocation() { string source = @" class Class1 { public void M(dynamic x, int y) { var z = /*<bind>*/x(y)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'x(y)') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') Arguments(1): IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicObjectCreation() { string source = @" internal class Class { public Class(Class x) { } public Class(string x) { } public void M(dynamic x) { var c = /*<bind>*/new Class(x)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: Class) (Syntax: 'new Class(x)') Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_StackAllocArrayCreation() { string source = @" using System.Collections.Generic; internal class Class { public unsafe void M(int x) { int* block = /*<bind>*/stackalloc int[x]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: 'stackalloc int[x]') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // public unsafe void M(int x) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_InterpolatedStringExpression() { string source = @" using System; internal class Class { public void M(string x, int y) { Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,20}') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y:D3}') Expression: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_ThrowExpression() { string source = @" using System; internal class Class { public void M(string x) { var y = x ?? /*<bind>*/throw new ArgumentNullException(nameof(x))/*</bind>*/; } } "; string expectedOperationTree = @" IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw new A ... (nameof(x))') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, IsImplicit) (Syntax: 'new Argumen ... (nameof(x))') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: System.ArgumentNullException..ctor(System.String paramName)) (OperationKind.ObjectCreation, Type: System.ArgumentNullException) (Syntax: 'new Argumen ... (nameof(x))') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: paramName) (OperationKind.Argument, Type: null) (Syntax: 'nameof(x)') INameOfOperation (OperationKind.NameOf, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ThrowExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_PatternSwitchStatement() { string source = @" internal class Class { public void M(int x) { switch (x) { /*<bind>*/case var y when (x >= 10): break;/*</bind>*/ } } } "; string expectedOperationTree = @" ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case var y ... break;') Locals: Local_1: System.Int32 y Clauses: IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case var y ... (x >= 10):') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: True) Guard: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x >= 10') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Body: IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchSectionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DefaultPatternSwitchStatement() { string source = @" internal class Class { public void M(int x) { switch (x) { case var y when (x >= 10): break; /*<bind>*/default:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IDefaultCaseClauseOperation (Label Id: 0) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<DefaultSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_UserDefinedLogicalConditionalOperator() { string source = @" class A<T> { public static bool operator true(A<T> o) { return true; } public static bool operator false(A<T> o) { return false; } } class B : A<object> { public static B operator &(B x, B y) { return x; } } class C : B { public static C operator |(C x, C y) { return x; } } class P { static void M(C x, C y) { if (/*<bind>*/x && y/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: B B.op_BitwiseAnd(B x, B y)) (OperationKind.Binary, Type: B) (Syntax: 'x && y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ParameterReference_NoPiaObjectCreation() { var sources0 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(C))] public interface I { int P { get; set; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public class C { public C(object o) { } } "; var sources1 = @" struct S { public I F(object x) { return /*<bind>*/new I(x)/*</bind>*/; } } "; var compilation0 = CreateCompilation(sources0); compilation0.VerifyDiagnostics(); var compilation1 = CreateEmptyCompilation( sources1, references: new[] { MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes: true) }); string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: I, IsInvalid) (Syntax: 'new I(x)') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // (6,24): error CS1729: 'I' does not contain a constructor that takes 1 arguments // return /*<bind>*/new I(x)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, "I").WithArguments("I", "1").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation1, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_ArgListOperator() { string source = @" using System; class C { static void Method(int x, bool y) { M(1, /*<bind>*/__arglist(x, y)/*</bind>*/); } static void M(int x, __arglist) { } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19790, "https://github.com/dotnet/roslyn/issues/19790")] public void ParameterReference_IsPatternExpression() { string source = @" class Class1 { public void Method1(object x) { if (/*<bind>*/x is int y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is int y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19902, "https://github.com/dotnet/roslyn/issues/19902")] public void ParameterReference_LocalFunctionStatement() { string source = @" using System; using System.Collections.Generic; class Class { static IEnumerable<T> MyIterator<T>(IEnumerable<T> source, Func<T, bool> predicate) { /*<bind>*/IEnumerable<T> Iterator() { foreach (var element in source) if (predicate(element)) yield return element; }/*</bind>*/ return Iterator(); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Collections.Generic.IEnumerable<T> Iterator()) (OperationKind.LocalFunction, Type: null) (Syntax: 'IEnumerable ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'foreach (va ... rn element;') Locals: Local_1: T element LoopControlVariable: IVariableDeclaratorOperation (Symbol: T element) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<T>, IsImplicit) (Syntax: 'source') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: source (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable<T>) (Syntax: 'source') Body: IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (predica ... rn element;') Condition: IInvocationOperation (virtual System.Boolean System.Func<T, System.Boolean>.Invoke(T arg)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'predicate(element)') Instance Receiver: IParameterReferenceOperation: predicate (OperationKind.ParameterReference, Type: System.Func<T, System.Boolean>) (Syntax: 'predicate') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: 'element') ILocalReferenceOperation: element (OperationKind.LocalReference, Type: T) (Syntax: 'element') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return element;') ReturnedValue: ILocalReferenceOperation: element (OperationKind.LocalReference, Type: T) (Syntax: 'element') WhenFalse: null NextVariables(0) IReturnOperation (OperationKind.YieldBreak, Type: null, IsImplicit) (Syntax: '{ ... }') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IParameterReferenceExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_TupleExpression() { string source = @" class Class1 { public void M(int x, int y) { var tuple = /*<bind>*/(x, x + y)/*</bind>*/; } } "; string expectedOperationTree = @" ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, x + y)') NaturalType: (System.Int32 x, System.Int32) Elements(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = new[] { // file.cs(6,13): warning CS0219: The variable 'tuple' is assigned but its value is never used // var tuple = /*<bind>*/(x, x + y)/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "tuple").WithArguments("tuple").WithLocation(6, 13) }; VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_TupleDeconstruction() { string source = @" class Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } public void Deconstruct(out int x, out int y) { x = X; y = Y; } } class Class1 { public void M(Point point) { /*<bind>*/var (x, y) = point/*</bind>*/; } } "; string expectedOperationTree = @" IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y)) (Syntax: 'var (x, y) = point') Left: IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x, System.Int32 y)) (Syntax: 'var (x, y)') ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)') NaturalType: (System.Int32 x, System.Int32 y) Elements(2): ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') Right: IParameterReferenceOperation: point (OperationKind.ParameterReference, Type: Point) (Syntax: 'point') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_AnonymousObjectCreation() { string source = @" class Class1 { public void M(int x, string y) { var v = /*<bind>*/new { Amount = x, Message = ""Hello"" + y }/*</bind>*/; } } "; string expectedOperationTree = @" IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 Amount, System.String Message>) (Syntax: 'new { Amoun ... ello"" + y }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Amount = x') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 Amount, System.String Message>.Amount { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Amount') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 Amount, System.String Message>, IsImplicit) (Syntax: 'new { Amoun ... ello"" + y }') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'Message = ""Hello"" + y') Left: IPropertyReferenceOperation: System.String <anonymous type: System.Int32 Amount, System.String Message>.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'Message') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 Amount, System.String Message>, IsImplicit) (Syntax: 'new { Amoun ... ello"" + y }') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: '""Hello"" + y') Left: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Hello"") (Syntax: '""Hello""') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AnonymousObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_QueryExpression() { string source = @" using System.Linq; using System.Collections.Generic; struct Customer { public string Name { get; set; } public string Address { get; set; } } class Class1 { public void M(List<Customer> customers) { var result = /*<bind>*/from cust in customers select cust.Name/*</bind>*/; } } "; string expectedOperationTree = @" ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from cust i ... t cust.Name') Expression: IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<Customer, System.String>(this System.Collections.Generic.IEnumerable<Customer> source, System.Func<Customer, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select cust.Name') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from cust in customers') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<Customer>, IsImplicit) (Syntax: 'from cust in customers') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: customers (OperationKind.ParameterReference, Type: System.Collections.Generic.List<Customer>) (Syntax: 'customers') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'cust.Name') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<Customer, System.String>, IsImplicit) (Syntax: 'cust.Name') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'cust.Name') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'cust.Name') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'cust.Name') ReturnedValue: IPropertyReferenceOperation: System.String Customer.Name { get; set; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'cust.Name') Instance Receiver: IParameterReferenceOperation: cust (OperationKind.ParameterReference, Type: Customer) (Syntax: 'cust') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_ObjectAndCollectionInitializer() { string source = @" using System.Collections.Generic; internal class Class { public int X { get; set; } public List<int> Y { get; set; } public Dictionary<int, int> Z { get; set; } public Class C { get; set; } public void M(int x, int y, int z) { var c = /*<bind>*/new Class() { X = x, Y = { x, y, 3 }, Z = { { x, y } }, C = { X = z } }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectCreationOperation (Constructor: Class..ctor()) (OperationKind.ObjectCreation, Type: Class) (Syntax: 'new Class() ... { X = z } }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = x, Y ... { X = z } }') Initializers(4): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = x') Left: IPropertyReferenceOperation: System.Int32 Class.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IMemberInitializerOperation (OperationKind.MemberInitializer, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y = { x, y, 3 }') InitializedMember: IPropertyReferenceOperation: System.Collections.Generic.List<System.Int32> Class.Y { get; set; } (OperationKind.PropertyReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Y') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List<System.Int32>) (Syntax: '{ x, y, 3 }') Initializers(3): IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( void System.Collections.Generic.List<System.Int32>.Add(System.Int32 item)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List<System.Int32>, IsImplicit) (Syntax: 'Y') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IMemberInitializerOperation (OperationKind.MemberInitializer, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z = { { x, y } }') InitializedMember: IPropertyReferenceOperation: System.Collections.Generic.Dictionary<System.Int32, System.Int32> Class.Z { get; set; } (OperationKind.PropertyReference, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: 'Z') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Z') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>) (Syntax: '{ { x, y } }') Initializers(1): IInvocationOperation ( void System.Collections.Generic.Dictionary<System.Int32, System.Int32>.Add(System.Int32 key, System.Int32 value)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{ x, y }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary<System.Int32, System.Int32>, IsImplicit) (Syntax: 'Z') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IMemberInitializerOperation (OperationKind.MemberInitializer, Type: Class) (Syntax: 'C = { X = z }') InitializedMember: IPropertyReferenceOperation: Class Class.C { get; set; } (OperationKind.PropertyReference, Type: Class) (Syntax: 'C') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'C') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = z }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = z') Left: IPropertyReferenceOperation: System.Int32 Class.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X') Right: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DelegateCreationExpressionWithLambdaArgument() { string source = @" using System; class Class { // Used parameter methods public void UsedParameterMethod1(Action a) { Action a2 = /*<bind>*/new Action(() => { a(); })/*</bind>*/; } } "; string expectedOperationTree = @" IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action( ... })') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a();') Expression: IInvocationOperation (virtual void System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'a()') Instance Receiver: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a') Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ ... }') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DelegateCreationExpressionWithMethodArgument() { string source = @" using System; class Class { public delegate void Delegate(int x, int y); public void Method(Delegate d) { var a = /*<bind>*/new Delegate(Method2)/*</bind>*/; } public void Method2(int x, int y) { } } "; string expectedOperationTree = @" IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Class.Delegate) (Syntax: 'new Delegate(Method2)') Target: IMethodReferenceOperation: void Class.Method2(System.Int32 x, System.Int32 y) (OperationKind.MethodReference, Type: null) (Syntax: 'Method2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'Method2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DelegateCreationExpressionWithInvalidArgument() { string source = @" using System; class Class { public delegate void Delegate(int x, int y); public void Method(int x) { var a = /*<bind>*/new Delegate(x)/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: Class.Delegate, IsInvalid) (Syntax: 'new Delegate(x)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0149: Method name expected // var a = /*<bind>*/new Delegate(x)/*</bind>*/; Diagnostic(ErrorCode.ERR_MethodNameExpected, "x").WithLocation(10, 40) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicCollectionInitializer() { string source = @" using System.Collections.Generic; internal class Class { public dynamic X { get; set; } public void M(int x, int y) { var c = new Class() /*<bind>*/{ X = { { x, y } } }/*</bind>*/; } } "; string expectedOperationTree = @" IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Class) (Syntax: '{ X = { { x, y } } }') Initializers(1): IMemberInitializerOperation (OperationKind.MemberInitializer, Type: dynamic) (Syntax: 'X = { { x, y } }') InitializedMember: IPropertyReferenceOperation: dynamic Class.X { get; set; } (OperationKind.PropertyReference, Type: dynamic) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Class, IsImplicit) (Syntax: 'X') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: dynamic) (Syntax: '{ { x, y } }') Initializers(1): IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Void) (Syntax: '{ x, y }') Expression: IDynamicMemberReferenceOperation (Member Name: ""Add"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null, IsImplicit) (Syntax: 'X') Type Arguments(0) Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: dynamic, IsImplicit) (Syntax: 'X') Arguments(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_NameOfExpression() { string source = @" class Class1 { public string M(int x) { return /*<bind>*/nameof(x)/*</bind>*/; } } "; string expectedOperationTree = @" INameOfOperation (OperationKind.NameOf, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_PointerIndirectionExpression() { string source = @" class Class1 { public unsafe int M(int *x) { return /*<bind>*/*x/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '*x') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32*) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // public unsafe int M(int *x) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(4, 23) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_FixedLocalInitializer() { string source = @" using System.Collections.Generic; internal class Class { public unsafe void M(int[] array) { fixed (int* /*<bind>*/p = array/*</bind>*/) { *p = 1; } } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Int32* p) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p = array') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= array') IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'array') Children(1): IParameterReferenceOperation: array (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'array') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // public unsafe void M(int[] array) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_RefTypeOperator() { string source = @" class Class1 { public System.Type M(System.TypedReference x) { return /*<bind>*/__reftype(x)/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__reftype(x)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.TypedReference) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<RefTypeExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_MakeRefOperator() { string source = @" class Class1 { public void M(System.Type x) { var y = /*<bind>*/__makeref(x)/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__makeref(x)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Type) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<MakeRefExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_RefValueOperator() { string source = @" class Class1 { public void M(System.TypedReference x) { var y = /*<bind>*/__refvalue(x, int)/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__refvalue(x, int)') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.TypedReference) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<RefValueExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicIndexerAccess() { string source = @" class Class1 { public void M(dynamic d, int x) { var /*<bind>*/y = d[x]/*</bind>*/; } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: dynamic y) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y = d[x]') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= d[x]') IDynamicIndexerAccessOperation (OperationKind.DynamicIndexerAccess, Type: dynamic) (Syntax: 'd[x]') Expression: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicMemberAccess() { string source = @" class Class1 { public void M(dynamic x, int y) { var z = /*<bind>*/x.M(y)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'x.M(y)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'x.M') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') Arguments(1): IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicInvocation() { string source = @" class Class1 { public void M(dynamic x, int y) { var z = /*<bind>*/x(y)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'x(y)') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') Arguments(1): IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DynamicObjectCreation() { string source = @" internal class Class { public Class(Class x) { } public Class(string x) { } public void M(dynamic x) { var c = /*<bind>*/new Class(x)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: Class) (Syntax: 'new Class(x)') Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_StackAllocArrayCreation() { string source = @" using System.Collections.Generic; internal class Class { public unsafe void M(int x) { int* block = /*<bind>*/stackalloc int[x]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: 'stackalloc int[x]') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0227: Unsafe code may only appear if compiling with /unsafe // public unsafe void M(int x) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "M").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_InterpolatedStringExpression() { string source = @" using System; internal class Class { public void M(string x, int y) { Console.WriteLine(/*<bind>*/$""String {x,20} and {y:D3} and constant {1}""/*</bind>*/); } } "; string expectedOperationTree = @" IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""String {x ... nstant {1}""') Parts(6): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'String ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""String "", IsImplicit) (Syntax: 'String ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{x,20}') Expression: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Alignment: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and "", IsImplicit) (Syntax: ' and ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{y:D3}') Expression: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Alignment: null FormatString: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""D3"") (Syntax: ':D3') IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ' and constant ') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "" and constant "", IsImplicit) (Syntax: ' and constant ') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{1}') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Alignment: null FormatString: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InterpolatedStringExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_ThrowExpression() { string source = @" using System; internal class Class { public void M(string x) { var y = x ?? /*<bind>*/throw new ArgumentNullException(nameof(x))/*</bind>*/; } } "; string expectedOperationTree = @" IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw new A ... (nameof(x))') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, IsImplicit) (Syntax: 'new Argumen ... (nameof(x))') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: System.ArgumentNullException..ctor(System.String paramName)) (OperationKind.ObjectCreation, Type: System.ArgumentNullException) (Syntax: 'new Argumen ... (nameof(x))') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: paramName) (OperationKind.Argument, Type: null) (Syntax: 'nameof(x)') INameOfOperation (OperationKind.NameOf, Type: System.String, Constant: ""x"") (Syntax: 'nameof(x)') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ThrowExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_PatternSwitchStatement() { string source = @" internal class Class { public void M(int x) { switch (x) { /*<bind>*/case var y when (x >= 10): break;/*</bind>*/ } } } "; string expectedOperationTree = @" ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case var y ... break;') Locals: Local_1: System.Int32 y Clauses: IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case var y ... (x >= 10):') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: True) Guard: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x >= 10') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Body: IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchSectionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_DefaultPatternSwitchStatement() { string source = @" internal class Class { public void M(int x) { switch (x) { case var y when (x >= 10): break; /*<bind>*/default:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IDefaultCaseClauseOperation (Label Id: 0) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<DefaultSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_UserDefinedLogicalConditionalOperator() { string source = @" class A<T> { public static bool operator true(A<T> o) { return true; } public static bool operator false(A<T> o) { return false; } } class B : A<object> { public static B operator &(B x, B y) { return x; } } class C : B { public static C operator |(C x, C y) { return x; } } class P { static void M(C x, C y) { if (/*<bind>*/x && y/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: B B.op_BitwiseAnd(B x, B y)) (OperationKind.Binary, Type: B) (Syntax: 'x && y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ParameterReference_NoPiaObjectCreation() { var sources0 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(C))] public interface I { int P { get; set; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public class C { public C(object o) { } } "; var sources1 = @" struct S { public I F(object x) { return /*<bind>*/new I(x)/*</bind>*/; } } "; var compilation0 = CreateCompilation(sources0); compilation0.VerifyDiagnostics(); var compilation1 = CreateEmptyCompilation( sources1, references: new[] { MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes: true) }); string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: I, IsInvalid) (Syntax: 'new I(x)') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // (6,24): error CS1729: 'I' does not contain a constructor that takes 1 arguments // return /*<bind>*/new I(x)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadCtorArgCount, "I").WithArguments("I", "1").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(compilation1, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void ParameterReference_ArgListOperator() { string source = @" using System; class C { static void Method(int x, bool y) { M(1, /*<bind>*/__arglist(x, y)/*</bind>*/); } static void M(int x, __arglist) { } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19790, "https://github.com/dotnet/roslyn/issues/19790")] public void ParameterReference_IsPatternExpression() { string source = @" class Class1 { public void Method1(object x) { if (/*<bind>*/x is int y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is int y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19902, "https://github.com/dotnet/roslyn/issues/19902")] public void ParameterReference_LocalFunctionStatement() { string source = @" using System; using System.Collections.Generic; class Class { static IEnumerable<T> MyIterator<T>(IEnumerable<T> source, Func<T, bool> predicate) { /*<bind>*/IEnumerable<T> Iterator() { foreach (var element in source) if (predicate(element)) yield return element; }/*</bind>*/ return Iterator(); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Collections.Generic.IEnumerable<T> Iterator()) (OperationKind.LocalFunction, Type: null) (Syntax: 'IEnumerable ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'foreach (va ... rn element;') Locals: Local_1: T element LoopControlVariable: IVariableDeclaratorOperation (Symbol: T element) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<T>, IsImplicit) (Syntax: 'source') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: source (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable<T>) (Syntax: 'source') Body: IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (predica ... rn element;') Condition: IInvocationOperation (virtual System.Boolean System.Func<T, System.Boolean>.Invoke(T arg)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'predicate(element)') Instance Receiver: IParameterReferenceOperation: predicate (OperationKind.ParameterReference, Type: System.Func<T, System.Boolean>) (Syntax: 'predicate') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: 'element') ILocalReferenceOperation: element (OperationKind.LocalReference, Type: T) (Syntax: 'element') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return element;') ReturnedValue: ILocalReferenceOperation: element (OperationKind.LocalReference, Type: T) (Syntax: 'element') WhenFalse: null NextVariables(0) IReturnOperation (OperationKind.YieldBreak, Type: null, IsImplicit) (Syntax: '{ ... }') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Tools/PrepareTests/MinimizeUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; internal static class MinimizeUtil { internal record FilePathInfo(string RelativeDirectory, string Directory, string RelativePath, string FullPath); internal static void Run(string sourceDirectory, string destinationDirectory, bool isUnix) { const string duplicateDirectoryName = ".duplicate"; var duplicateDirectory = Path.Combine(destinationDirectory, duplicateDirectoryName); Directory.CreateDirectory(duplicateDirectory); // https://github.com/dotnet/roslyn/issues/49486 // we should avoid copying the files under Resources. Directory.CreateDirectory(Path.Combine(destinationDirectory, "src/Workspaces/MSBuildTest/Resources")); var individualFiles = new[] { "global.json", "NuGet.config", "src/Workspaces/MSBuildTest/Resources/.editorconfig", "src/Workspaces/MSBuildTest/Resources/global.json", "src/Workspaces/MSBuildTest/Resources/Directory.Build.props", "src/Workspaces/MSBuildTest/Resources/Directory.Build.targets", "src/Workspaces/MSBuildTest/Resources/Directory.Build.rsp", "src/Workspaces/MSBuildTest/Resources/NuGet.Config", }; foreach (var individualFile in individualFiles) { var outputPath = Path.Combine(destinationDirectory, individualFile); var outputDirectory = Path.GetDirectoryName(outputPath)!; CreateHardLink(outputPath, Path.Combine(sourceDirectory, individualFile)); } // Map of all PE files MVID to the path information var idToFilePathMap = initialWalk(); resolveDuplicates(); writeHydrateFile(); // The goal of initial walk is to // 1. Record any PE files as they are eligable for de-dup // 2. Hard link all other files into destination directory Dictionary<Guid, List<FilePathInfo>> initialWalk() { IEnumerable<string> directories = new[] { Path.Combine(sourceDirectory, "eng") }; var artifactsDir = Path.Combine(sourceDirectory, "artifacts/bin"); directories = directories.Concat(Directory.EnumerateDirectories(artifactsDir, "*.UnitTests")); directories = directories.Concat(Directory.EnumerateDirectories(artifactsDir, "RunTests")); var idToFilePathMap = directories.AsParallel() .SelectMany(unitDirPath => walkDirectory(unitDirPath, sourceDirectory, destinationDirectory)) .GroupBy(pair => pair.mvid) .ToDictionary( group => group.Key, group => group.Select(pair => pair.pathInfo).ToList()); return idToFilePathMap; } static IEnumerable<(Guid mvid, FilePathInfo pathInfo)> walkDirectory(string unitDirPath, string sourceDirectory, string destinationDirectory) { string? lastOutputDirectory = null; foreach (var sourceFilePath in Directory.EnumerateFiles(unitDirPath, "*", SearchOption.AllDirectories)) { var currentDirName = Path.GetDirectoryName(sourceFilePath)!; var currentRelativeDirectory = Path.GetRelativePath(sourceDirectory, currentDirName); var currentOutputDirectory = Path.Combine(destinationDirectory, currentRelativeDirectory); if (currentOutputDirectory != lastOutputDirectory) { Directory.CreateDirectory(currentOutputDirectory); lastOutputDirectory = currentOutputDirectory; } var fileName = Path.GetFileName(sourceFilePath); if (fileName.EndsWith(".dll", StringComparison.Ordinal) && TryGetMvid(sourceFilePath, out var mvid)) { var filePathInfo = new FilePathInfo( RelativeDirectory: currentRelativeDirectory, Directory: currentDirName, RelativePath: Path.Combine(currentRelativeDirectory, fileName), FullPath: sourceFilePath); yield return (mvid, filePathInfo); } else { var destFilePath = Path.Combine(currentOutputDirectory, fileName); CreateHardLink(destFilePath, sourceFilePath); } } } // Now that we have a complete list of PE files, determine which are duplicates void resolveDuplicates() { foreach (var pair in idToFilePathMap) { if (pair.Value.Count > 1) { CreateHardLink(getPeFilePath(pair.Key), pair.Value[0].FullPath); } else { var item = pair.Value[0]; var destFilePath = Path.Combine(destinationDirectory, item.RelativePath); CreateHardLink(destFilePath, item.FullPath); } } } static string getPeFileName(Guid mvid) => mvid.ToString(); string getPeFilePath(Guid mvid) => Path.Combine(duplicateDirectory, getPeFileName(mvid)); void writeHydrateFile() { var fileList = new List<string>(); var grouping = idToFilePathMap .Where(x => x.Value.Count > 1) .SelectMany(pair => pair.Value.Select(fp => (Id: pair.Key, FilePath: fp))) .GroupBy(fp => getGroupDirectory(fp.FilePath.RelativeDirectory)); // The "rehydrate-all" script assumes we are running all tests on a single machine instead of on Helix. var rehydrateAllBuilder = new StringBuilder(); if (isUnix) { writeUnixHeaderContent(rehydrateAllBuilder); rehydrateAllBuilder.AppendLine("export HELIX_CORRELATION_PAYLOAD=$scriptroot/.duplicate"); } else { rehydrateAllBuilder.AppendLine(@"set HELIX_CORRELATION_PAYLOAD=%~dp0\.duplicate"); } var builder = new StringBuilder(); foreach (var group in grouping) { string filename; builder.Clear(); if (isUnix) { filename = "rehydrate.sh"; writeUnixRehydrateContent(builder, group); rehydrateAllBuilder.AppendLine(@"bash """ + Path.Combine("$scriptroot", group.Key, "rehydrate.sh") + @""""); } else { filename = "rehydrate.cmd"; writeWindowsRehydrateContent(builder, group); rehydrateAllBuilder.AppendLine("call " + Path.Combine("%~dp0", group.Key, "rehydrate.cmd")); } File.WriteAllText(Path.Combine(destinationDirectory, group.Key, filename), builder.ToString()); } string rehydrateAllFilename = isUnix ? "rehydrate-all.sh" : "rehydrate-all.cmd"; File.WriteAllText(Path.Combine(destinationDirectory, rehydrateAllFilename), rehydrateAllBuilder.ToString()); static void writeWindowsRehydrateContent(StringBuilder builder, IGrouping<string, (Guid Id, FilePathInfo FilePath)> group) { builder.AppendLine("@echo off"); var count = 0; foreach (var tuple in group) { var source = getPeFileName(tuple.Id); var destFileName = Path.GetRelativePath(group.Key, tuple.FilePath.RelativePath); if (Path.GetDirectoryName(destFileName) is { Length: not 0 } directory) { builder.AppendLine($@"mkdir %~dp0\{directory} 2> nul"); } builder.AppendLine($@" mklink /h %~dp0\{destFileName} %HELIX_CORRELATION_PAYLOAD%\{source} > nul if %errorlevel% neq 0 ( echo Cmd failed: mklink /h %~dp0\{destFileName} %HELIX_CORRELATION_PAYLOAD%\{source} exit /b 1 )"); count++; if (count % 1_000 == 0) { builder.AppendLine($"echo {count:n0} hydrated"); } } builder.AppendLine("@echo on"); // so the rest of the commands show up in helix logs } static void writeUnixHeaderContent(StringBuilder builder) { builder.AppendLine(@"#!/bin/bash source=""${BASH_SOURCE[0]}"" # resolve $source until the file is no longer a symlink while [[ -h ""$source"" ]]; do scriptroot=""$( cd -P ""$( dirname ""$source"" )"" && pwd )"" source=""$(readlink ""$source"")"" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source=""$scriptroot/$source"" done scriptroot=""$( cd -P ""$( dirname ""$source"" )"" && pwd )"" "); } static void writeUnixRehydrateContent(StringBuilder builder, IGrouping<string, (Guid Id, FilePathInfo FilePath)> group) { writeUnixHeaderContent(builder); var count = 0; foreach (var tuple in group) { var source = getPeFileName(tuple.Id); var destFilePath = Path.GetRelativePath(group.Key, tuple.FilePath.RelativePath); if (Path.GetDirectoryName(destFilePath) is { Length: not 0 } directory) { builder.AppendLine($@"mkdir -p ""$scriptroot/{directory}"""); } builder.AppendLine($@"ln ""$HELIX_CORRELATION_PAYLOAD/{source}"" ""$scriptroot/{destFilePath}"" || exit $?"); count++; if (count % 1_000 == 0) { builder.AppendLine($"echo '{count:n0} hydrated'"); } } // Working around an AzDo file permissions bug. // We want this to happen at the end so we can be agnostic about whether ilasm was already in the directory, or was linked in from the .duplicate directory. builder.AppendLine(); builder.AppendLine(@"find $scriptroot -name ilasm -exec chmod 755 {} +"); } static string getGroupDirectory(string relativePath) { // artifacts/TestProject/Debug/net472/whatever/etc should become: // artifacts/TestProject/Debug/net472 var groupDirectory = relativePath; while (Path.GetFileName(Path.GetDirectoryName(groupDirectory)) is not (null or "Debug" or "Release")) groupDirectory = Path.GetDirectoryName(groupDirectory); if (groupDirectory is null) { // So far, this scenario doesn't seem to happen. // If it *did* happen, we'd want to know, but it isn't necessarily a problem. Console.WriteLine("Directory not grouped under configuration/TFM: " + relativePath); return relativePath; } return groupDirectory; } } } private static void CreateHardLink(string fileName, string existingFileName) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var success = CreateHardLink(fileName, existingFileName, IntPtr.Zero); if (!success) { // for debugging: https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes throw new IOException($"Failed to create hard link from {existingFileName} to {fileName} with exception 0x{Marshal.GetLastWin32Error():X}"); } } else { var result = link(existingFileName, fileName); if (result != 0) { throw new IOException($"Failed to create hard link from {existingFileName} to {fileName} with error code {Marshal.GetLastWin32Error()}"); } } // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createhardlinkw [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); // https://man7.org/linux/man-pages/man2/link.2.html [DllImport("libc", SetLastError = true)] static extern int link(string oldpath, string newpath); } private static bool TryGetMvid(string filePath, out Guid mvid) { try { using var stream = File.OpenRead(filePath); var reader = new PEReader(stream); if (!reader.HasMetadata) { mvid = default; return false; } var metadataReader = reader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; mvid = metadataReader.GetGuid(mvidHandle); return true; } catch { mvid = default; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; internal static class MinimizeUtil { internal record FilePathInfo(string RelativeDirectory, string Directory, string RelativePath, string FullPath); internal static void Run(string sourceDirectory, string destinationDirectory, bool isUnix) { const string duplicateDirectoryName = ".duplicate"; var duplicateDirectory = Path.Combine(destinationDirectory, duplicateDirectoryName); Directory.CreateDirectory(duplicateDirectory); // https://github.com/dotnet/roslyn/issues/49486 // we should avoid copying the files under Resources. Directory.CreateDirectory(Path.Combine(destinationDirectory, "src/Workspaces/MSBuildTest/Resources")); var individualFiles = new[] { "global.json", "NuGet.config", "src/Workspaces/MSBuildTest/Resources/.editorconfig", "src/Workspaces/MSBuildTest/Resources/global.json", "src/Workspaces/MSBuildTest/Resources/Directory.Build.props", "src/Workspaces/MSBuildTest/Resources/Directory.Build.targets", "src/Workspaces/MSBuildTest/Resources/Directory.Build.rsp", "src/Workspaces/MSBuildTest/Resources/NuGet.Config", }; foreach (var individualFile in individualFiles) { var outputPath = Path.Combine(destinationDirectory, individualFile); var outputDirectory = Path.GetDirectoryName(outputPath)!; CreateHardLink(outputPath, Path.Combine(sourceDirectory, individualFile)); } // Map of all PE files MVID to the path information var idToFilePathMap = initialWalk(); resolveDuplicates(); writeHydrateFile(); // The goal of initial walk is to // 1. Record any PE files as they are eligable for de-dup // 2. Hard link all other files into destination directory Dictionary<Guid, List<FilePathInfo>> initialWalk() { IEnumerable<string> directories = new[] { Path.Combine(sourceDirectory, "eng") }; var artifactsDir = Path.Combine(sourceDirectory, "artifacts/bin"); directories = directories.Concat(Directory.EnumerateDirectories(artifactsDir, "*.UnitTests")); directories = directories.Concat(Directory.EnumerateDirectories(artifactsDir, "RunTests")); var idToFilePathMap = directories.AsParallel() .SelectMany(unitDirPath => walkDirectory(unitDirPath, sourceDirectory, destinationDirectory)) .GroupBy(pair => pair.mvid) .ToDictionary( group => group.Key, group => group.Select(pair => pair.pathInfo).ToList()); return idToFilePathMap; } static IEnumerable<(Guid mvid, FilePathInfo pathInfo)> walkDirectory(string unitDirPath, string sourceDirectory, string destinationDirectory) { string? lastOutputDirectory = null; foreach (var sourceFilePath in Directory.EnumerateFiles(unitDirPath, "*", SearchOption.AllDirectories)) { var currentDirName = Path.GetDirectoryName(sourceFilePath)!; var currentRelativeDirectory = Path.GetRelativePath(sourceDirectory, currentDirName); var currentOutputDirectory = Path.Combine(destinationDirectory, currentRelativeDirectory); if (currentOutputDirectory != lastOutputDirectory) { Directory.CreateDirectory(currentOutputDirectory); lastOutputDirectory = currentOutputDirectory; } var fileName = Path.GetFileName(sourceFilePath); if (fileName.EndsWith(".dll", StringComparison.Ordinal) && TryGetMvid(sourceFilePath, out var mvid)) { var filePathInfo = new FilePathInfo( RelativeDirectory: currentRelativeDirectory, Directory: currentDirName, RelativePath: Path.Combine(currentRelativeDirectory, fileName), FullPath: sourceFilePath); yield return (mvid, filePathInfo); } else { var destFilePath = Path.Combine(currentOutputDirectory, fileName); CreateHardLink(destFilePath, sourceFilePath); } } } // Now that we have a complete list of PE files, determine which are duplicates void resolveDuplicates() { foreach (var pair in idToFilePathMap) { if (pair.Value.Count > 1) { CreateHardLink(getPeFilePath(pair.Key), pair.Value[0].FullPath); } else { var item = pair.Value[0]; var destFilePath = Path.Combine(destinationDirectory, item.RelativePath); CreateHardLink(destFilePath, item.FullPath); } } } static string getPeFileName(Guid mvid) => mvid.ToString(); string getPeFilePath(Guid mvid) => Path.Combine(duplicateDirectory, getPeFileName(mvid)); void writeHydrateFile() { var fileList = new List<string>(); var grouping = idToFilePathMap .Where(x => x.Value.Count > 1) .SelectMany(pair => pair.Value.Select(fp => (Id: pair.Key, FilePath: fp))) .GroupBy(fp => getGroupDirectory(fp.FilePath.RelativeDirectory)); // The "rehydrate-all" script assumes we are running all tests on a single machine instead of on Helix. var rehydrateAllBuilder = new StringBuilder(); if (isUnix) { writeUnixHeaderContent(rehydrateAllBuilder); rehydrateAllBuilder.AppendLine("export HELIX_CORRELATION_PAYLOAD=$scriptroot/.duplicate"); } else { rehydrateAllBuilder.AppendLine(@"set HELIX_CORRELATION_PAYLOAD=%~dp0\.duplicate"); } var builder = new StringBuilder(); foreach (var group in grouping) { string filename; builder.Clear(); if (isUnix) { filename = "rehydrate.sh"; writeUnixRehydrateContent(builder, group); rehydrateAllBuilder.AppendLine(@"bash """ + Path.Combine("$scriptroot", group.Key, "rehydrate.sh") + @""""); } else { filename = "rehydrate.cmd"; writeWindowsRehydrateContent(builder, group); rehydrateAllBuilder.AppendLine("call " + Path.Combine("%~dp0", group.Key, "rehydrate.cmd")); } File.WriteAllText(Path.Combine(destinationDirectory, group.Key, filename), builder.ToString()); } string rehydrateAllFilename = isUnix ? "rehydrate-all.sh" : "rehydrate-all.cmd"; File.WriteAllText(Path.Combine(destinationDirectory, rehydrateAllFilename), rehydrateAllBuilder.ToString()); static void writeWindowsRehydrateContent(StringBuilder builder, IGrouping<string, (Guid Id, FilePathInfo FilePath)> group) { builder.AppendLine("@echo off"); var count = 0; foreach (var tuple in group) { var source = getPeFileName(tuple.Id); var destFileName = Path.GetRelativePath(group.Key, tuple.FilePath.RelativePath); if (Path.GetDirectoryName(destFileName) is { Length: not 0 } directory) { builder.AppendLine($@"mkdir %~dp0\{directory} 2> nul"); } builder.AppendLine($@" mklink /h %~dp0\{destFileName} %HELIX_CORRELATION_PAYLOAD%\{source} > nul if %errorlevel% neq 0 ( echo Cmd failed: mklink /h %~dp0\{destFileName} %HELIX_CORRELATION_PAYLOAD%\{source} exit /b 1 )"); count++; if (count % 1_000 == 0) { builder.AppendLine($"echo {count:n0} hydrated"); } } builder.AppendLine("@echo on"); // so the rest of the commands show up in helix logs } static void writeUnixHeaderContent(StringBuilder builder) { builder.AppendLine(@"#!/bin/bash source=""${BASH_SOURCE[0]}"" # resolve $source until the file is no longer a symlink while [[ -h ""$source"" ]]; do scriptroot=""$( cd -P ""$( dirname ""$source"" )"" && pwd )"" source=""$(readlink ""$source"")"" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source=""$scriptroot/$source"" done scriptroot=""$( cd -P ""$( dirname ""$source"" )"" && pwd )"" "); } static void writeUnixRehydrateContent(StringBuilder builder, IGrouping<string, (Guid Id, FilePathInfo FilePath)> group) { writeUnixHeaderContent(builder); var count = 0; foreach (var tuple in group) { var source = getPeFileName(tuple.Id); var destFilePath = Path.GetRelativePath(group.Key, tuple.FilePath.RelativePath); if (Path.GetDirectoryName(destFilePath) is { Length: not 0 } directory) { builder.AppendLine($@"mkdir -p ""$scriptroot/{directory}"""); } builder.AppendLine($@"ln ""$HELIX_CORRELATION_PAYLOAD/{source}"" ""$scriptroot/{destFilePath}"" || exit $?"); count++; if (count % 1_000 == 0) { builder.AppendLine($"echo '{count:n0} hydrated'"); } } // Working around an AzDo file permissions bug. // We want this to happen at the end so we can be agnostic about whether ilasm was already in the directory, or was linked in from the .duplicate directory. builder.AppendLine(); builder.AppendLine(@"find $scriptroot -name ilasm -exec chmod 755 {} +"); } static string getGroupDirectory(string relativePath) { // artifacts/TestProject/Debug/net472/whatever/etc should become: // artifacts/TestProject/Debug/net472 var groupDirectory = relativePath; while (Path.GetFileName(Path.GetDirectoryName(groupDirectory)) is not (null or "Debug" or "Release")) groupDirectory = Path.GetDirectoryName(groupDirectory); if (groupDirectory is null) { // So far, this scenario doesn't seem to happen. // If it *did* happen, we'd want to know, but it isn't necessarily a problem. Console.WriteLine("Directory not grouped under configuration/TFM: " + relativePath); return relativePath; } return groupDirectory; } } } private static void CreateHardLink(string fileName, string existingFileName) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var success = CreateHardLink(fileName, existingFileName, IntPtr.Zero); if (!success) { // for debugging: https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes throw new IOException($"Failed to create hard link from {existingFileName} to {fileName} with exception 0x{Marshal.GetLastWin32Error():X}"); } } else { var result = link(existingFileName, fileName); if (result != 0) { throw new IOException($"Failed to create hard link from {existingFileName} to {fileName} with error code {Marshal.GetLastWin32Error()}"); } } // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createhardlinkw [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); // https://man7.org/linux/man-pages/man2/link.2.html [DllImport("libc", SetLastError = true)] static extern int link(string oldpath, string newpath); } private static bool TryGetMvid(string filePath, out Guid mvid) { try { using var stream = File.OpenRead(filePath); var reader = new PEReader(stream); if (!reader.HasMetadata) { mvid = default; return false; } var metadataReader = reader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; mvid = metadataReader.GetGuid(mvidHandle); return true; } catch { mvid = default; return false; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/Portable/Symbols/IAliasSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a using alias (Imports alias in Visual Basic). /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IAliasSymbol : ISymbol { /// <summary> /// Gets the <see cref="INamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> INamespaceOrTypeSymbol Target { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a using alias (Imports alias in Visual Basic). /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IAliasSymbol : ISymbol { /// <summary> /// Gets the <see cref="INamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> INamespaceOrTypeSymbol Target { get; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/Implementation/Utilities/AbstractNotifyPropertyChanged.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal class AbstractNotifyPropertyChanged : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <returns>True if the property was updated</returns> protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = "") { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; NotifyPropertyChanged(propertyName); return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal class AbstractNotifyPropertyChanged : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <returns>True if the property was updated</returns> protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = "") { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; NotifyPropertyChanged(propertyName); return true; } return false; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/Implementation/IHierarchyItemToProjectIdMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { /// <summary> /// Maps from hierarchy items to project IDs. /// </summary> internal interface IHierarchyItemToProjectIdMap : IWorkspaceService { /// <summary> /// Given an <see cref="IVsHierarchyItem"/> representing a project and an optional target framework moniker, /// returns the <see cref="ProjectId"/> of the equivalent Roslyn <see cref="Project"/>. /// </summary> /// <param name="hierarchyItem">An <see cref="IVsHierarchyItem"/> for the project root.</param> /// <param name="targetFrameworkMoniker">An optional string representing a TargetFrameworkMoniker. /// This is only useful in multi-targeting scenarios where there may be multiple Roslyn projects /// (one per target framework) for a single project on disk.</param> /// <param name="projectId">The <see cref="ProjectId"/> of the found project, if any.</param> /// <returns>True if the desired project was found; false otherwise.</returns> bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { /// <summary> /// Maps from hierarchy items to project IDs. /// </summary> internal interface IHierarchyItemToProjectIdMap : IWorkspaceService { /// <summary> /// Given an <see cref="IVsHierarchyItem"/> representing a project and an optional target framework moniker, /// returns the <see cref="ProjectId"/> of the equivalent Roslyn <see cref="Project"/>. /// </summary> /// <param name="hierarchyItem">An <see cref="IVsHierarchyItem"/> for the project root.</param> /// <param name="targetFrameworkMoniker">An optional string representing a TargetFrameworkMoniker. /// This is only useful in multi-targeting scenarios where there may be multiple Roslyn projects /// (one per target framework) for a single project on disk.</param> /// <param name="projectId">The <see cref="ProjectId"/> of the found project, if any.</param> /// <returns>True if the desired project was found; false otherwise.</returns> bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/IntegrationTest/TestUtilities/Input/ShiftState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input { [Flags] public enum ShiftState : byte { Shift = 1, Ctrl = 1 << 1, Alt = 1 << 2, Hankaku = 1 << 3, Reserved1 = 1 << 4, Reserved2 = 1 << 5 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input { [Flags] public enum ShiftState : byte { Shift = 1, Ctrl = 1 << 1, Alt = 1 << 2, Hankaku = 1 << 3, Reserved1 = 1 << 4, Reserved2 = 1 << 5 } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class Matcher { /// <summary> /// Matcher equivalent to (m*) /// </summary> public static Matcher<T> Repeat<T>(Matcher<T> matcher) => Matcher<T>.Repeat(matcher); /// <summary> /// Matcher equivalent to (m+) /// </summary> public static Matcher<T> OneOrMore<T>(Matcher<T> matcher) => Matcher<T>.OneOrMore(matcher); /// <summary> /// Matcher equivalent to (m_1|m_2|...|m_n) /// </summary> public static Matcher<T> Choice<T>(params Matcher<T>[] matchers) => Matcher<T>.Choice(matchers); /// <summary> /// Matcher equivalent to (m_1 ... m_n) /// </summary> public static Matcher<T> Sequence<T>(params Matcher<T>[] matchers) => Matcher<T>.Sequence(matchers); /// <summary> /// Matcher that matches an element if the provide predicate returns true. /// </summary> public static Matcher<T> Single<T>(Func<T, bool> predicate, string description) => Matcher<T>.Single(predicate, description); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class Matcher { /// <summary> /// Matcher equivalent to (m*) /// </summary> public static Matcher<T> Repeat<T>(Matcher<T> matcher) => Matcher<T>.Repeat(matcher); /// <summary> /// Matcher equivalent to (m+) /// </summary> public static Matcher<T> OneOrMore<T>(Matcher<T> matcher) => Matcher<T>.OneOrMore(matcher); /// <summary> /// Matcher equivalent to (m_1|m_2|...|m_n) /// </summary> public static Matcher<T> Choice<T>(params Matcher<T>[] matchers) => Matcher<T>.Choice(matchers); /// <summary> /// Matcher equivalent to (m_1 ... m_n) /// </summary> public static Matcher<T> Sequence<T>(params Matcher<T>[] matchers) => Matcher<T>.Sequence(matchers); /// <summary> /// Matcher that matches an element if the provide predicate returns true. /// </summary> public static Matcher<T> Single<T>(Func<T, bool> predicate, string description) => Matcher<T>.Single(predicate, description); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/Portable/Syntax/AnnotationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis { public static class AnnotationExtensions { /// <summary> /// Creates a new node identical to this node with the specified annotations attached. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be added to the new node.</param> public static TNode WithAdditionalAnnotations<TNode>(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode { return (TNode)node.WithAdditionalAnnotationsInternal(annotations); } /// <summary> /// Creates a new node identical to this node with the specified annotations attached. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be added to the new node.</param> public static TNode WithAdditionalAnnotations<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : SyntaxNode { return (TNode)node.WithAdditionalAnnotationsInternal(annotations); } /// <summary> /// Creates a new node identical to this node with the specified annotations removed. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be removed from the new node.</param> public static TNode WithoutAnnotations<TNode>(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode { return (TNode)node.GetNodeWithoutAnnotations(annotations); } /// <summary> /// Creates a new node identical to this node with the specified annotations removed. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be removed from the new node.</param> public static TNode WithoutAnnotations<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : SyntaxNode { return (TNode)node.GetNodeWithoutAnnotations(annotations); } /// <summary> /// Creates a new node identical to this node with the annotations of the specified kind removed. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotationKind">The kind of annotation to remove.</param> public static TNode WithoutAnnotations<TNode>(this TNode node, string annotationKind) where TNode : SyntaxNode { if (node.HasAnnotations(annotationKind)) { return node.WithoutAnnotations<TNode>(node.GetAnnotations(annotationKind).ToArray()); } else { return node; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis { public static class AnnotationExtensions { /// <summary> /// Creates a new node identical to this node with the specified annotations attached. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be added to the new node.</param> public static TNode WithAdditionalAnnotations<TNode>(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode { return (TNode)node.WithAdditionalAnnotationsInternal(annotations); } /// <summary> /// Creates a new node identical to this node with the specified annotations attached. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be added to the new node.</param> public static TNode WithAdditionalAnnotations<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : SyntaxNode { return (TNode)node.WithAdditionalAnnotationsInternal(annotations); } /// <summary> /// Creates a new node identical to this node with the specified annotations removed. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be removed from the new node.</param> public static TNode WithoutAnnotations<TNode>(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode { return (TNode)node.GetNodeWithoutAnnotations(annotations); } /// <summary> /// Creates a new node identical to this node with the specified annotations removed. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotations">Annotations to be removed from the new node.</param> public static TNode WithoutAnnotations<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : SyntaxNode { return (TNode)node.GetNodeWithoutAnnotations(annotations); } /// <summary> /// Creates a new node identical to this node with the annotations of the specified kind removed. /// </summary> /// <param name="node">Original node.</param> /// <param name="annotationKind">The kind of annotation to remove.</param> public static TNode WithoutAnnotations<TNode>(this TNode node, string annotationKind) where TNode : SyntaxNode { if (node.HasAnnotations(annotationKind)) { return node.WithoutAnnotations<TNode>(node.GetAnnotations(annotationKind).ToArray()); } else { return node; } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Test/Semantic/Semantics/AnonymousFunctionTests.cs
 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [WorkItem(275, "https://github.com/dotnet/csharplang/issues/275")] [CompilerTrait(CompilerFeature.AnonymousFunctions)] public class AnonymousFunctionTests : CSharpTestBase { public static CSharpCompilation VerifyInPreview(string source, params DiagnosticDescription[] expected) => CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(expected); internal CompilationVerifier VerifyInPreview(CSharpTestSource source, string expectedOutput, Action<ModuleSymbol>? symbolValidator = null, params DiagnosticDescription[] expected) => CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(expected); internal void VerifyInPreview(string source, string expectedOutput, string metadataName, string expectedIL) { verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(); verifier.VerifyIL(metadataName, expectedIL); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void DisallowInNonPreview() { var source = @" using System; public class C { public static int a; public void F() { Func<int> f = static () => a; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,23): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(10, 23)); } [Fact] public void StaticLambdaCanReferenceStaticField() { var source = @" using System; public class C { public static int a; public static void Main() { Func<int> f = static () => a; a = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld ""int C.a"" IL_0005: ret } "); } [Fact] public void StaticLambdaCanReferenceStaticProperty() { var source = @" using System; public class C { static int A { get; set; } public static void Main() { Func<int> f = static () => A; A = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__4_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.A.get"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanReferenceConstField() { var source = @" using System; public class C { public const int a = 42; public static void Main() { Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReferenceConstLocal() { var source = @" using System; public class C { public static void Main() { const int a = 42; Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReturnConstLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { const int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret }"); } [Fact] public void StaticLambdaCannotCaptureInstanceField() { var source = @" using System; public class C { public int a; public void F() { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "a").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureInstanceProperty() { var source = @" using System; public class C { int A { get; } public void F() { Func<int> f = static () => A; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => A; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "A").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureParameter() { var source = @" using System; public class C { public void F(int a) { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (8,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(8, 36)); } [Fact] public void StaticLambdaCannotCaptureOuterLocal() { var source = @" using System; public class C { public void F() { int a; Func<int> f = static () => a; } }"; VerifyInPreview(source, // (9,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(9, 36), // (9,36): error CS0165: Use of unassigned local variable 'a' // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(9, 36)); } [Fact] public void StaticLambdaCanReturnInnerLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0, //a int V_1) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: br.s IL_0008 IL_0008: ldloc.1 IL_0009: ret }"); } [Fact] public void StaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { this.F(); return 0; }; } }"; VerifyInPreview(source, // (10,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(10, 13)); } [Fact] public void StaticLambdaCannotReferenceBase() { var source = @" using System; public class B { public virtual void F() { } } public class C : B { public override void F() { Func<int> f = static () => { base.F(); return 0; }; } }"; VerifyInPreview(source, // (15,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // base.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "base").WithLocation(15, 13)); } [Fact] public void StaticLambdaCannotReferenceInstanceLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { F(); return 0; }; void F() {} } }"; VerifyInPreview(source, // (10,13): error CS8427: A static anonymous function cannot contain a reference to 'F'. // F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "F()").WithArguments("F").WithLocation(10, 13)); } [Fact] public void StaticLambdaCanReferenceStaticLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => local(); Console.WriteLine(f()); static int local() => 42; } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.<Main>g__local|0_1()"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; Func<int> g = () => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 39 (0x27) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<int> V_1, //g int V_2) IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000f: ldloc.0 IL_0010: ldftn ""int C.<>c__DisplayClass0_0.<Main>b__1()"" IL_0016: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: callvirt ""int System.Func<int>.Invoke()"" IL_0022: stloc.2 IL_0023: br.s IL_0025 IL_0025: ldloc.2 IL_0026: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { static int f() { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; var verifier = VerifyInPreview( source, expectedOutput: "42", symbolValidator); const string metadataName = "C.<Main>g__f|0_0"; if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL(metadataName, @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); Assert.True(method.IsStatic); } } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { static int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20)); } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanCallStaticMethod() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => M(); Console.Write(f()); } static int M() => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.M()"" IL_0005: ret } "); } [Fact] public void QueryInStaticLambdaCannotAccessThis() { var source = @" using System; using System.Linq; public class C { public static string[] args; public void F() { Func<int> f = static () => { var q = from a in args select M(a); return 0; }; } int M(string a) => 0; }"; VerifyInPreview(source, // (14,28): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // select M(a); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "M").WithLocation(14, 28)); } [Fact] public void QueryInStaticLambdaCanReferenceStatic() { var source = @" using System; using System.Linq; using System.Collections.Generic; public class C { public static string[] args; public static void Main() { args = new[] { """" }; Func<IEnumerable<int>> f = static () => { var q = from a in args select M(a); return q; }; foreach (var x in f()) { Console.Write(x); } } static int M(string a) => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 49 (0x31) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<int> V_0, //q System.Collections.Generic.IEnumerable<int> V_1) IL_0000: nop IL_0001: ldsfld ""string[] C.args"" IL_0006: ldsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""C.<>c C.<>c.<>9"" IL_0014: ldftn ""int C.<>c.<Main>b__1_1(string)"" IL_001a: newobj ""System.Func<string, int>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<string, int>(System.Collections.Generic.IEnumerable<string>, System.Func<string, int>)"" IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: stloc.1 IL_002d: br.s IL_002f IL_002f: ldloc.1 IL_0030: ret } "); } [Fact] public void InstanceLambdaInStaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { Func<int> g = () => { this.F(); return 0; }; return g(); }; } }"; VerifyInPreview(source, // (12,17): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(12, 17)); } [Fact] public void TestStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = static delegate(int i) { }; Action<int> b = static a => { }; Action<int> c = static (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.True(anonymousMethod.IsStatic); Assert.True(simpleLambda.IsStatic); Assert.True(parenthesizedLambda.IsStatic); } [Fact] public void TestNonStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = delegate(int i) { }; Action<int> b = a => { }; Action<int> c = (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.False(anonymousMethod.IsStatic); Assert.False(simpleLambda.IsStatic); Assert.False(parenthesizedLambda.IsStatic); } [Fact] public void TestStaticLambdaCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static () => ""hello""); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticLambdaIndexerArgument() { var source = @" using System; public class C { public object this[Func<object> fn] { get { Console.WriteLine(fn()); return null; } } public static void Main() { _ = new C()[static () => ""hello""]; } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__2_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticDelegateCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static delegate() { return ""hello""; }); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaNameof() { var source = @" using System; public class C { public int w; public static int x; public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void Main() { int y = 0; F(static (int z) => { return nameof(w) + nameof(x) + nameof(y) + nameof(z); }); } }"; VerifyInPreview(source, expectedOutput: "wxyz", metadataName: "C.<>c.<Main>b__3_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""wxyz"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaTypeParams() { var source = @" using System; public class C<T> { public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void M<U>() { F(static (int x) => { return default(T).ToString() + default(U).ToString(); }); } } public class Program { public static void Main() { C<int>.M<bool>(); } }"; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator, expectedOutput: "0False") .VerifyDiagnostics(); verifier.VerifyIL("C<T>.<>c__1<U>.<M>b__1_0", @" { // Code size 51 (0x33) .maxstack 3 .locals init (T V_0, U V_1, string V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: dup IL_0004: initobj ""T"" IL_000a: constrained. ""T"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_1 IL_0017: dup IL_0018: initobj ""U"" IL_001e: constrained. ""U"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""string string.Concat(string, string)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c__1.<M>b__1_0"); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void StaticLambda_Nint() { var source = @" using System; local(static x => x + 1); void local(Func<nint, nint> fn) { Console.WriteLine(fn(0)); }"; VerifyInPreview(source, expectedOutput: "1", metadataName: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + ".<>c.<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">b__0_0", expectedIL: @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldc.i4.1 IL_0002: conv.i IL_0003: add IL_0004: ret }"); } [Fact] public void StaticLambda_ExpressionTree() { var source = @" using System; using System.Linq.Expressions; class C { static void Main() { local(static x => x + 1); static void local(Expression<Func<int, int>> fn) { Console.WriteLine(fn.Compile()(0)); } } }"; var verifier = VerifyInPreview(source, expectedOutput: "1"); verifier.VerifyIL("C.Main", @" { // Code size 72 (0x48) .maxstack 5 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: nop IL_0001: ldtoken ""int"" IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000b: ldstr ""x"" IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldtoken ""int"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_002c: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)"" IL_0031: ldc.i4.1 IL_0032: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0037: dup IL_0038: ldc.i4.0 IL_0039: ldloc.0 IL_003a: stelem.ref IL_003b: call ""System.Linq.Expressions.Expression<System.Func<int, int>> System.Linq.Expressions.Expression.Lambda<System.Func<int, int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0040: call ""void C.<Main>g__local|0_1(System.Linq.Expressions.Expression<System.Func<int, int>>)"" IL_0045: nop IL_0046: nop IL_0047: ret }"); } [Fact] public void StaticLambda_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS1525: Invalid expression term 'static' // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "static").WithArguments("static").WithLocation(6, 32), // (6,32): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "static").WithLocation(6, 32), // (6,32): error CS0106: The modifier 'static' is not valid for this item // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 32), // (6,40): error CS8124: Tuple must contain at least two elements. // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(6, 40), // (6,42): error CS1001: Identifier expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=>").WithLocation(6, 42), // (6,42): error CS1003: Syntax error, ',' expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 42), // (6,45): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 45) ); } [Fact] public void StaticLambda_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert lambda expression to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static () => { }").WithArguments("lambda expression", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS0211: Cannot take the address of the given expression // delegate*<void> ptr = &static delegate() { }; Diagnostic(ErrorCode.ERR_InvalidAddrOp, "static delegate() { }").WithLocation(6, 32) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert anonymous method to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static delegate() { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static delegate() { }").WithArguments("anonymous method", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void ConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b ? () => Write(1) : a; a(); a = b ? static () => Write(2) : a; a(); a = b ? () => { Write(3); } : a; a(); a = b ? static () => { Write(4); } : a; a(); a = b ? a : () => { }; a = b ? a : static () => { }; a = b ? delegate() { Write(5); } : a; a(); a = b ? static delegate() { Write(6); } : a; a(); a = b ? a : delegate() { }; a = b ? a : static delegate() { }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void RefConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, ref System.Action a) { a = ref b ? ref () => Write(1) : ref a; a(); a = ref b ? ref static () => Write(2) : ref a; a(); a = ref b ? ref () => { Write(3); } : ref a; a(); a = ref b ? ref static () => { Write(4); } : ref a; a(); a = ref b ? ref a : ref () => { }; a = ref b ? ref a : ref static () => { }; a = ref b ? ref delegate() { Write(5); } : ref a; a(); a = ref b ? ref static delegate() { Write(6); } : ref a; a(); a = ref b ? ref a : ref delegate() { }; a = b ? ref a : ref static delegate() { }; } } "; VerifyInPreview(source, // (8,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => Write(1) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => Write(1)").WithLocation(8, 25), // (11,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => Write(2) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => Write(2)").WithLocation(11, 25), // (14,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => { Write(3); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { Write(3); }").WithLocation(14, 25), // (17,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => { Write(4); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { Write(4); }").WithLocation(17, 25), // (20,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { }").WithLocation(20, 33), // (21,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref static () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { }").WithLocation(21, 33), // (23,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref delegate() { Write(5); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { Write(5); }").WithLocation(23, 25), // (26,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static delegate() { Write(6); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { Write(6); }").WithLocation(26, 25), // (29,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { }").WithLocation(29, 33), // (30,29): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = b ? ref a : ref static delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { }").WithLocation(30, 29) ); } [Fact] public void SwitchExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b switch { true => () => Write(1), false => a }; a(); a = b switch { true => static () => Write(2), false => a }; a(); a = b switch { true => () => { Write(3); }, false => a }; a(); a = b switch { true => static () => { Write(4); }, false => a }; a(); a = b switch { true => a , false => () => { Write(0); } }; a = b switch { true => a , false => static () => { Write(0); } }; a = b switch { true => delegate() { Write(5); }, false => a }; a(); a = b switch { true => static delegate() { Write(6); }, false => a }; a(); a = b switch { true => a , false => delegate() { Write(0); } }; a = b switch { true => a , false => static delegate() { Write(0); } }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void DiscardParams() { var source = @" using System; class C { static void Main() { Action<int, int, string> fn = static (_, _, z) => Console.Write(z); fn(1, 2, ""hello""); fn = static delegate(int _, int _, string z) { Console.Write(z); }; fn(3, 4, "" world""); } } "; CompileAndVerify(source, expectedOutput: "hello world", parseOptions: TestOptions.Regular9); } [Fact] public void PrivateMemberAccessibility() { var source = @" using System; class C { private static void M1(int i) { Console.Write(i); } class Inner { static void Main() { Action a = static () => M1(1); a(); a = static delegate() { M1(2); }; a(); } } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { CompileAndVerify(source, expectedOutput: "12", parseOptions: TestOptions.Regular9); } } } }
 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [WorkItem(275, "https://github.com/dotnet/csharplang/issues/275")] [CompilerTrait(CompilerFeature.AnonymousFunctions)] public class AnonymousFunctionTests : CSharpTestBase { public static CSharpCompilation VerifyInPreview(string source, params DiagnosticDescription[] expected) => CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(expected); internal CompilationVerifier VerifyInPreview(CSharpTestSource source, string expectedOutput, Action<ModuleSymbol>? symbolValidator = null, params DiagnosticDescription[] expected) => CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(expected); internal void VerifyInPreview(string source, string expectedOutput, string metadataName, string expectedIL) { verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(); verifier.VerifyIL(metadataName, expectedIL); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void DisallowInNonPreview() { var source = @" using System; public class C { public static int a; public void F() { Func<int> f = static () => a; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,23): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(10, 23)); } [Fact] public void StaticLambdaCanReferenceStaticField() { var source = @" using System; public class C { public static int a; public static void Main() { Func<int> f = static () => a; a = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld ""int C.a"" IL_0005: ret } "); } [Fact] public void StaticLambdaCanReferenceStaticProperty() { var source = @" using System; public class C { static int A { get; set; } public static void Main() { Func<int> f = static () => A; A = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__4_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.A.get"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanReferenceConstField() { var source = @" using System; public class C { public const int a = 42; public static void Main() { Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReferenceConstLocal() { var source = @" using System; public class C { public static void Main() { const int a = 42; Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReturnConstLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { const int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret }"); } [Fact] public void StaticLambdaCannotCaptureInstanceField() { var source = @" using System; public class C { public int a; public void F() { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "a").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureInstanceProperty() { var source = @" using System; public class C { int A { get; } public void F() { Func<int> f = static () => A; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => A; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "A").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureParameter() { var source = @" using System; public class C { public void F(int a) { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (8,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(8, 36)); } [Fact] public void StaticLambdaCannotCaptureOuterLocal() { var source = @" using System; public class C { public void F() { int a; Func<int> f = static () => a; } }"; VerifyInPreview(source, // (9,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(9, 36), // (9,36): error CS0165: Use of unassigned local variable 'a' // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(9, 36)); } [Fact] public void StaticLambdaCanReturnInnerLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0, //a int V_1) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: br.s IL_0008 IL_0008: ldloc.1 IL_0009: ret }"); } [Fact] public void StaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { this.F(); return 0; }; } }"; VerifyInPreview(source, // (10,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(10, 13)); } [Fact] public void StaticLambdaCannotReferenceBase() { var source = @" using System; public class B { public virtual void F() { } } public class C : B { public override void F() { Func<int> f = static () => { base.F(); return 0; }; } }"; VerifyInPreview(source, // (15,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // base.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "base").WithLocation(15, 13)); } [Fact] public void StaticLambdaCannotReferenceInstanceLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { F(); return 0; }; void F() {} } }"; VerifyInPreview(source, // (10,13): error CS8427: A static anonymous function cannot contain a reference to 'F'. // F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "F()").WithArguments("F").WithLocation(10, 13)); } [Fact] public void StaticLambdaCanReferenceStaticLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => local(); Console.WriteLine(f()); static int local() => 42; } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.<Main>g__local|0_1()"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; Func<int> g = () => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 39 (0x27) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<int> V_1, //g int V_2) IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000f: ldloc.0 IL_0010: ldftn ""int C.<>c__DisplayClass0_0.<Main>b__1()"" IL_0016: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: callvirt ""int System.Func<int>.Invoke()"" IL_0022: stloc.2 IL_0023: br.s IL_0025 IL_0025: ldloc.2 IL_0026: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { static int f() { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; var verifier = VerifyInPreview( source, expectedOutput: "42", symbolValidator); const string metadataName = "C.<Main>g__f|0_0"; if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL(metadataName, @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); Assert.True(method.IsStatic); } } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { static int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20)); } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanCallStaticMethod() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => M(); Console.Write(f()); } static int M() => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.M()"" IL_0005: ret } "); } [Fact] public void QueryInStaticLambdaCannotAccessThis() { var source = @" using System; using System.Linq; public class C { public static string[] args; public void F() { Func<int> f = static () => { var q = from a in args select M(a); return 0; }; } int M(string a) => 0; }"; VerifyInPreview(source, // (14,28): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // select M(a); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "M").WithLocation(14, 28)); } [Fact] public void QueryInStaticLambdaCanReferenceStatic() { var source = @" using System; using System.Linq; using System.Collections.Generic; public class C { public static string[] args; public static void Main() { args = new[] { """" }; Func<IEnumerable<int>> f = static () => { var q = from a in args select M(a); return q; }; foreach (var x in f()) { Console.Write(x); } } static int M(string a) => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 49 (0x31) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<int> V_0, //q System.Collections.Generic.IEnumerable<int> V_1) IL_0000: nop IL_0001: ldsfld ""string[] C.args"" IL_0006: ldsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""C.<>c C.<>c.<>9"" IL_0014: ldftn ""int C.<>c.<Main>b__1_1(string)"" IL_001a: newobj ""System.Func<string, int>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<string, int>(System.Collections.Generic.IEnumerable<string>, System.Func<string, int>)"" IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: stloc.1 IL_002d: br.s IL_002f IL_002f: ldloc.1 IL_0030: ret } "); } [Fact] public void InstanceLambdaInStaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { Func<int> g = () => { this.F(); return 0; }; return g(); }; } }"; VerifyInPreview(source, // (12,17): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(12, 17)); } [Fact] public void TestStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = static delegate(int i) { }; Action<int> b = static a => { }; Action<int> c = static (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.True(anonymousMethod.IsStatic); Assert.True(simpleLambda.IsStatic); Assert.True(parenthesizedLambda.IsStatic); } [Fact] public void TestNonStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = delegate(int i) { }; Action<int> b = a => { }; Action<int> c = (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.False(anonymousMethod.IsStatic); Assert.False(simpleLambda.IsStatic); Assert.False(parenthesizedLambda.IsStatic); } [Fact] public void TestStaticLambdaCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static () => ""hello""); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticLambdaIndexerArgument() { var source = @" using System; public class C { public object this[Func<object> fn] { get { Console.WriteLine(fn()); return null; } } public static void Main() { _ = new C()[static () => ""hello""]; } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__2_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticDelegateCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static delegate() { return ""hello""; }); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaNameof() { var source = @" using System; public class C { public int w; public static int x; public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void Main() { int y = 0; F(static (int z) => { return nameof(w) + nameof(x) + nameof(y) + nameof(z); }); } }"; VerifyInPreview(source, expectedOutput: "wxyz", metadataName: "C.<>c.<Main>b__3_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""wxyz"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaTypeParams() { var source = @" using System; public class C<T> { public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void M<U>() { F(static (int x) => { return default(T).ToString() + default(U).ToString(); }); } } public class Program { public static void Main() { C<int>.M<bool>(); } }"; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator, expectedOutput: "0False") .VerifyDiagnostics(); verifier.VerifyIL("C<T>.<>c__1<U>.<M>b__1_0", @" { // Code size 51 (0x33) .maxstack 3 .locals init (T V_0, U V_1, string V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: dup IL_0004: initobj ""T"" IL_000a: constrained. ""T"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_1 IL_0017: dup IL_0018: initobj ""U"" IL_001e: constrained. ""U"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""string string.Concat(string, string)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c__1.<M>b__1_0"); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void StaticLambda_Nint() { var source = @" using System; local(static x => x + 1); void local(Func<nint, nint> fn) { Console.WriteLine(fn(0)); }"; VerifyInPreview(source, expectedOutput: "1", metadataName: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + ".<>c.<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">b__0_0", expectedIL: @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldc.i4.1 IL_0002: conv.i IL_0003: add IL_0004: ret }"); } [Fact] public void StaticLambda_ExpressionTree() { var source = @" using System; using System.Linq.Expressions; class C { static void Main() { local(static x => x + 1); static void local(Expression<Func<int, int>> fn) { Console.WriteLine(fn.Compile()(0)); } } }"; var verifier = VerifyInPreview(source, expectedOutput: "1"); verifier.VerifyIL("C.Main", @" { // Code size 72 (0x48) .maxstack 5 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: nop IL_0001: ldtoken ""int"" IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000b: ldstr ""x"" IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldtoken ""int"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_002c: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)"" IL_0031: ldc.i4.1 IL_0032: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0037: dup IL_0038: ldc.i4.0 IL_0039: ldloc.0 IL_003a: stelem.ref IL_003b: call ""System.Linq.Expressions.Expression<System.Func<int, int>> System.Linq.Expressions.Expression.Lambda<System.Func<int, int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0040: call ""void C.<Main>g__local|0_1(System.Linq.Expressions.Expression<System.Func<int, int>>)"" IL_0045: nop IL_0046: nop IL_0047: ret }"); } [Fact] public void StaticLambda_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS1525: Invalid expression term 'static' // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "static").WithArguments("static").WithLocation(6, 32), // (6,32): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "static").WithLocation(6, 32), // (6,32): error CS0106: The modifier 'static' is not valid for this item // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 32), // (6,40): error CS8124: Tuple must contain at least two elements. // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(6, 40), // (6,42): error CS1001: Identifier expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=>").WithLocation(6, 42), // (6,42): error CS1003: Syntax error, ',' expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 42), // (6,45): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 45) ); } [Fact] public void StaticLambda_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert lambda expression to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static () => { }").WithArguments("lambda expression", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS0211: Cannot take the address of the given expression // delegate*<void> ptr = &static delegate() { }; Diagnostic(ErrorCode.ERR_InvalidAddrOp, "static delegate() { }").WithLocation(6, 32) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert anonymous method to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static delegate() { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static delegate() { }").WithArguments("anonymous method", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void ConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b ? () => Write(1) : a; a(); a = b ? static () => Write(2) : a; a(); a = b ? () => { Write(3); } : a; a(); a = b ? static () => { Write(4); } : a; a(); a = b ? a : () => { }; a = b ? a : static () => { }; a = b ? delegate() { Write(5); } : a; a(); a = b ? static delegate() { Write(6); } : a; a(); a = b ? a : delegate() { }; a = b ? a : static delegate() { }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void RefConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, ref System.Action a) { a = ref b ? ref () => Write(1) : ref a; a(); a = ref b ? ref static () => Write(2) : ref a; a(); a = ref b ? ref () => { Write(3); } : ref a; a(); a = ref b ? ref static () => { Write(4); } : ref a; a(); a = ref b ? ref a : ref () => { }; a = ref b ? ref a : ref static () => { }; a = ref b ? ref delegate() { Write(5); } : ref a; a(); a = ref b ? ref static delegate() { Write(6); } : ref a; a(); a = ref b ? ref a : ref delegate() { }; a = b ? ref a : ref static delegate() { }; } } "; VerifyInPreview(source, // (8,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => Write(1) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => Write(1)").WithLocation(8, 25), // (11,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => Write(2) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => Write(2)").WithLocation(11, 25), // (14,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => { Write(3); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { Write(3); }").WithLocation(14, 25), // (17,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => { Write(4); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { Write(4); }").WithLocation(17, 25), // (20,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { }").WithLocation(20, 33), // (21,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref static () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { }").WithLocation(21, 33), // (23,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref delegate() { Write(5); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { Write(5); }").WithLocation(23, 25), // (26,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static delegate() { Write(6); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { Write(6); }").WithLocation(26, 25), // (29,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { }").WithLocation(29, 33), // (30,29): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = b ? ref a : ref static delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { }").WithLocation(30, 29) ); } [Fact] public void SwitchExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b switch { true => () => Write(1), false => a }; a(); a = b switch { true => static () => Write(2), false => a }; a(); a = b switch { true => () => { Write(3); }, false => a }; a(); a = b switch { true => static () => { Write(4); }, false => a }; a(); a = b switch { true => a , false => () => { Write(0); } }; a = b switch { true => a , false => static () => { Write(0); } }; a = b switch { true => delegate() { Write(5); }, false => a }; a(); a = b switch { true => static delegate() { Write(6); }, false => a }; a(); a = b switch { true => a , false => delegate() { Write(0); } }; a = b switch { true => a , false => static delegate() { Write(0); } }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void DiscardParams() { var source = @" using System; class C { static void Main() { Action<int, int, string> fn = static (_, _, z) => Console.Write(z); fn(1, 2, ""hello""); fn = static delegate(int _, int _, string z) { Console.Write(z); }; fn(3, 4, "" world""); } } "; CompileAndVerify(source, expectedOutput: "hello world", parseOptions: TestOptions.Regular9); } [Fact] public void PrivateMemberAccessibility() { var source = @" using System; class C { private static void M1(int i) { Console.Write(i); } class Inner { static void Main() { Action a = static () => M1(1); a(); a = static delegate() { M1(2); }; a(); } } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { CompileAndVerify(source, expectedOutput: "12", parseOptions: TestOptions.Regular9); } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Core/Shared/Extensions/TextChangeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class TextChangeExtensions { public static TextChangeRange ToTextChangeRange(this ITextChange textChange) => new(textChange.OldSpan.ToTextSpan(), textChange.NewLength); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class TextChangeExtensions { public static TextChangeRange ToTextChangeRange(this ITextChange textChange) => new(textChange.OldSpan.ToTextSpan(), textChange.NewLength); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxFirstTokenReplacer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal class SyntaxFirstTokenReplacer : CSharpSyntaxRewriter { private readonly SyntaxToken _oldToken; private readonly SyntaxToken _newToken; private readonly int _diagnosticOffsetDelta; private bool _foundOldToken; private SyntaxFirstTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken, int diagnosticOffsetDelta) { _oldToken = oldToken; _newToken = newToken; _diagnosticOffsetDelta = diagnosticOffsetDelta; _foundOldToken = false; } internal static TRoot Replace<TRoot>(TRoot root, SyntaxToken oldToken, SyntaxToken newToken, int diagnosticOffsetDelta) where TRoot : CSharpSyntaxNode { var replacer = new SyntaxFirstTokenReplacer(oldToken, newToken, diagnosticOffsetDelta); var newRoot = (TRoot)replacer.Visit(root); Debug.Assert(replacer._foundOldToken); return newRoot; } public override CSharpSyntaxNode Visit(CSharpSyntaxNode node) { if (node != null) { if (!_foundOldToken) { var token = node as SyntaxToken; if (token != null) { Debug.Assert(token == _oldToken); _foundOldToken = true; return _newToken; // NB: diagnostic offsets have already been updated (by SyntaxParser.AddSkippedSyntax) } return UpdateDiagnosticOffset(base.Visit(node), _diagnosticOffsetDelta); } } return node; } private static TSyntax UpdateDiagnosticOffset<TSyntax>(TSyntax node, int diagnosticOffsetDelta) where TSyntax : CSharpSyntaxNode { DiagnosticInfo[] oldDiagnostics = node.GetDiagnostics(); if (oldDiagnostics == null || oldDiagnostics.Length == 0) { return node; } var numDiagnostics = oldDiagnostics.Length; DiagnosticInfo[] newDiagnostics = new DiagnosticInfo[numDiagnostics]; for (int i = 0; i < numDiagnostics; i++) { DiagnosticInfo oldDiagnostic = oldDiagnostics[i]; SyntaxDiagnosticInfo oldSyntaxDiagnostic = oldDiagnostic as SyntaxDiagnosticInfo; newDiagnostics[i] = oldSyntaxDiagnostic == null ? oldDiagnostic : new SyntaxDiagnosticInfo( oldSyntaxDiagnostic.Offset + diagnosticOffsetDelta, oldSyntaxDiagnostic.Width, (ErrorCode)oldSyntaxDiagnostic.Code, oldSyntaxDiagnostic.Arguments); } return node.WithDiagnosticsGreen(newDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal class SyntaxFirstTokenReplacer : CSharpSyntaxRewriter { private readonly SyntaxToken _oldToken; private readonly SyntaxToken _newToken; private readonly int _diagnosticOffsetDelta; private bool _foundOldToken; private SyntaxFirstTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken, int diagnosticOffsetDelta) { _oldToken = oldToken; _newToken = newToken; _diagnosticOffsetDelta = diagnosticOffsetDelta; _foundOldToken = false; } internal static TRoot Replace<TRoot>(TRoot root, SyntaxToken oldToken, SyntaxToken newToken, int diagnosticOffsetDelta) where TRoot : CSharpSyntaxNode { var replacer = new SyntaxFirstTokenReplacer(oldToken, newToken, diagnosticOffsetDelta); var newRoot = (TRoot)replacer.Visit(root); Debug.Assert(replacer._foundOldToken); return newRoot; } public override CSharpSyntaxNode Visit(CSharpSyntaxNode node) { if (node != null) { if (!_foundOldToken) { var token = node as SyntaxToken; if (token != null) { Debug.Assert(token == _oldToken); _foundOldToken = true; return _newToken; // NB: diagnostic offsets have already been updated (by SyntaxParser.AddSkippedSyntax) } return UpdateDiagnosticOffset(base.Visit(node), _diagnosticOffsetDelta); } } return node; } private static TSyntax UpdateDiagnosticOffset<TSyntax>(TSyntax node, int diagnosticOffsetDelta) where TSyntax : CSharpSyntaxNode { DiagnosticInfo[] oldDiagnostics = node.GetDiagnostics(); if (oldDiagnostics == null || oldDiagnostics.Length == 0) { return node; } var numDiagnostics = oldDiagnostics.Length; DiagnosticInfo[] newDiagnostics = new DiagnosticInfo[numDiagnostics]; for (int i = 0; i < numDiagnostics; i++) { DiagnosticInfo oldDiagnostic = oldDiagnostics[i]; SyntaxDiagnosticInfo oldSyntaxDiagnostic = oldDiagnostic as SyntaxDiagnosticInfo; newDiagnostics[i] = oldSyntaxDiagnostic == null ? oldDiagnostic : new SyntaxDiagnosticInfo( oldSyntaxDiagnostic.Offset + diagnosticOffsetDelta, oldSyntaxDiagnostic.Width, (ErrorCode)oldSyntaxDiagnostic.Code, oldSyntaxDiagnostic.Arguments); } return node.WithDiagnosticsGreen(newDiagnostics); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Core/Implementation/InlineRename/InlineRenameService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(IInlineRenameService))] [Export(typeof(InlineRenameService))] internal class InlineRenameService : IInlineRenameService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ITextBufferAssociatedViewService _textBufferAssociatedViewService; private readonly IAsynchronousOperationListener _asyncListener; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IFeatureServiceFactory _featureServiceFactory; private InlineRenameSession? _activeRenameSession; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineRenameService( IThreadingContext threadingContext, IUIThreadOperationExecutor uiThreadOperationExecutor, ITextBufferAssociatedViewService textBufferAssociatedViewService, ITextBufferFactoryService textBufferFactoryService, IFeatureServiceFactory featureServiceFactory, [ImportMany] IEnumerable<IRefactorNotifyService> refactorNotifyServices, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uiThreadOperationExecutor = uiThreadOperationExecutor; _textBufferAssociatedViewService = textBufferAssociatedViewService; _textBufferFactoryService = textBufferFactoryService; _featureServiceFactory = featureServiceFactory; _refactorNotifyServices = refactorNotifyServices; _asyncListener = listenerProvider.GetListener(FeatureAttribute.Rename); } public InlineRenameSessionInfo StartInlineSession( Document document, TextSpan textSpan, CancellationToken cancellationToken) { if (_activeRenameSession != null) { throw new InvalidOperationException(EditorFeaturesResources.An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one); } var editorRenameService = document.GetRequiredLanguageService<IEditorInlineRenameService>(); var renameInfo = editorRenameService.GetRenameInfoAsync(document, textSpan.Start, cancellationToken).WaitAndGetResult(cancellationToken); var readOnlyOrCannotNavigateToSpanSessionInfo = IsReadOnlyOrCannotNavigateToSpan(renameInfo, document, cancellationToken); if (readOnlyOrCannotNavigateToSpanSessionInfo != null) { return readOnlyOrCannotNavigateToSpanSessionInfo; } if (!renameInfo.CanRename) { return new InlineRenameSessionInfo(renameInfo.LocalizedErrorMessage); } var snapshot = document.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot(); Contract.ThrowIfNull(snapshot, "The document used for starting the inline rename session should still be open and associated with a snapshot."); ActiveSession = new InlineRenameSession( _threadingContext, this, document.Project.Solution.Workspace, renameInfo.TriggerSpan.ToSnapshotSpan(snapshot), renameInfo, _uiThreadOperationExecutor, _textBufferAssociatedViewService, _textBufferFactoryService, _featureServiceFactory, _refactorNotifyServices, _asyncListener); return new InlineRenameSessionInfo(ActiveSession); static InlineRenameSessionInfo? IsReadOnlyOrCannotNavigateToSpan(IInlineRenameInfo renameInfo, Document document, CancellationToken cancellationToken) { if (renameInfo is IInlineRenameInfo inlineRenameInfo && inlineRenameInfo.DefinitionLocations != default) { var workspace = document.Project.Solution.Workspace; var navigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>(); foreach (var documentSpan in inlineRenameInfo.DefinitionLocations) { var sourceText = documentSpan.Document.GetTextSynchronously(cancellationToken); var textSnapshot = sourceText.FindCorrespondingEditorTextSnapshot(); if (textSnapshot != null) { var buffer = textSnapshot.TextBuffer; var originalSpan = documentSpan.SourceSpan.ToSnapshotSpan(textSnapshot).TranslateTo(buffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); if (buffer.IsReadOnly(originalSpan)) { return new InlineRenameSessionInfo(EditorFeaturesResources.You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file); } } if (!navigationService.CanNavigateToSpan(workspace, document.Id, documentSpan.SourceSpan, cancellationToken)) { return new InlineRenameSessionInfo(EditorFeaturesResources.You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to); } } } return null; } } IInlineRenameSession? IInlineRenameService.ActiveSession => _activeRenameSession; internal InlineRenameSession? ActiveSession { get { return _activeRenameSession; } set { var previousSession = _activeRenameSession; _activeRenameSession = value; ActiveSessionChanged?.Invoke(this, new ActiveSessionChangedEventArgs(previousSession!)); } } /// <summary> /// Raised when the ActiveSession property has changed. /// </summary> internal event EventHandler<ActiveSessionChangedEventArgs>? ActiveSessionChanged; internal class ActiveSessionChangedEventArgs : EventArgs { public ActiveSessionChangedEventArgs(InlineRenameSession previousSession) => this.PreviousSession = previousSession; public InlineRenameSession PreviousSession { get; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(IInlineRenameService))] [Export(typeof(InlineRenameService))] internal class InlineRenameService : IInlineRenameService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ITextBufferAssociatedViewService _textBufferAssociatedViewService; private readonly IAsynchronousOperationListener _asyncListener; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IFeatureServiceFactory _featureServiceFactory; private InlineRenameSession? _activeRenameSession; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineRenameService( IThreadingContext threadingContext, IUIThreadOperationExecutor uiThreadOperationExecutor, ITextBufferAssociatedViewService textBufferAssociatedViewService, ITextBufferFactoryService textBufferFactoryService, IFeatureServiceFactory featureServiceFactory, [ImportMany] IEnumerable<IRefactorNotifyService> refactorNotifyServices, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uiThreadOperationExecutor = uiThreadOperationExecutor; _textBufferAssociatedViewService = textBufferAssociatedViewService; _textBufferFactoryService = textBufferFactoryService; _featureServiceFactory = featureServiceFactory; _refactorNotifyServices = refactorNotifyServices; _asyncListener = listenerProvider.GetListener(FeatureAttribute.Rename); } public InlineRenameSessionInfo StartInlineSession( Document document, TextSpan textSpan, CancellationToken cancellationToken) { if (_activeRenameSession != null) { throw new InvalidOperationException(EditorFeaturesResources.An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one); } var editorRenameService = document.GetRequiredLanguageService<IEditorInlineRenameService>(); var renameInfo = editorRenameService.GetRenameInfoAsync(document, textSpan.Start, cancellationToken).WaitAndGetResult(cancellationToken); var readOnlyOrCannotNavigateToSpanSessionInfo = IsReadOnlyOrCannotNavigateToSpan(renameInfo, document, cancellationToken); if (readOnlyOrCannotNavigateToSpanSessionInfo != null) { return readOnlyOrCannotNavigateToSpanSessionInfo; } if (!renameInfo.CanRename) { return new InlineRenameSessionInfo(renameInfo.LocalizedErrorMessage); } var snapshot = document.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot(); Contract.ThrowIfNull(snapshot, "The document used for starting the inline rename session should still be open and associated with a snapshot."); ActiveSession = new InlineRenameSession( _threadingContext, this, document.Project.Solution.Workspace, renameInfo.TriggerSpan.ToSnapshotSpan(snapshot), renameInfo, _uiThreadOperationExecutor, _textBufferAssociatedViewService, _textBufferFactoryService, _featureServiceFactory, _refactorNotifyServices, _asyncListener); return new InlineRenameSessionInfo(ActiveSession); static InlineRenameSessionInfo? IsReadOnlyOrCannotNavigateToSpan(IInlineRenameInfo renameInfo, Document document, CancellationToken cancellationToken) { if (renameInfo is IInlineRenameInfo inlineRenameInfo && inlineRenameInfo.DefinitionLocations != default) { var workspace = document.Project.Solution.Workspace; var navigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>(); foreach (var documentSpan in inlineRenameInfo.DefinitionLocations) { var sourceText = documentSpan.Document.GetTextSynchronously(cancellationToken); var textSnapshot = sourceText.FindCorrespondingEditorTextSnapshot(); if (textSnapshot != null) { var buffer = textSnapshot.TextBuffer; var originalSpan = documentSpan.SourceSpan.ToSnapshotSpan(textSnapshot).TranslateTo(buffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); if (buffer.IsReadOnly(originalSpan)) { return new InlineRenameSessionInfo(EditorFeaturesResources.You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file); } } if (!navigationService.CanNavigateToSpan(workspace, document.Id, documentSpan.SourceSpan, cancellationToken)) { return new InlineRenameSessionInfo(EditorFeaturesResources.You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to); } } } return null; } } IInlineRenameSession? IInlineRenameService.ActiveSession => _activeRenameSession; internal InlineRenameSession? ActiveSession { get { return _activeRenameSession; } set { var previousSession = _activeRenameSession; _activeRenameSession = value; ActiveSessionChanged?.Invoke(this, new ActiveSessionChangedEventArgs(previousSession!)); } } /// <summary> /// Raised when the ActiveSession property has changed. /// </summary> internal event EventHandler<ActiveSessionChangedEventArgs>? ActiveSessionChanged; internal class ActiveSessionChangedEventArgs : EventArgs { public ActiveSessionChangedEventArgs(InlineRenameSession previousSession) => this.PreviousSession = previousSession; public InlineRenameSession PreviousSession { get; } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Tools/IdeCoreBenchmarks/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; namespace IdeCoreBenchmarks { internal class Program { private class IgnoreReleaseOnly : ManualConfig { public IgnoreReleaseOnly() { AddValidator(JitOptimizationsValidator.DontFailOnError); AddLogger(DefaultConfig.Instance.GetLoggers().ToArray()); AddExporter(DefaultConfig.Instance.GetExporters().ToArray()); AddColumnProvider(DefaultConfig.Instance.GetColumnProviders().ToArray()); AddDiagnoser(MemoryDiagnoser.Default); } } public const string RoslynRootPathEnvVariableName = "ROSLYN_SOURCE_ROOT_PATH"; public static string GetRoslynRootLocation([CallerFilePath] string sourceFilePath = "") { //This file is located at [Roslyn]\src\Tools\IdeCoreBenchmarks\Program.cs return Path.Combine(Path.GetDirectoryName(sourceFilePath), @"..\..\.."); } private static void Main(string[] args) { Environment.SetEnvironmentVariable(RoslynRootPathEnvVariableName, GetRoslynRootLocation()); new BenchmarkSwitcher(typeof(Program).Assembly).Run(args); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; namespace IdeCoreBenchmarks { internal class Program { private class IgnoreReleaseOnly : ManualConfig { public IgnoreReleaseOnly() { AddValidator(JitOptimizationsValidator.DontFailOnError); AddLogger(DefaultConfig.Instance.GetLoggers().ToArray()); AddExporter(DefaultConfig.Instance.GetExporters().ToArray()); AddColumnProvider(DefaultConfig.Instance.GetColumnProviders().ToArray()); AddDiagnoser(MemoryDiagnoser.Default); } } public const string RoslynRootPathEnvVariableName = "ROSLYN_SOURCE_ROOT_PATH"; public static string GetRoslynRootLocation([CallerFilePath] string sourceFilePath = "") { //This file is located at [Roslyn]\src\Tools\IdeCoreBenchmarks\Program.cs return Path.Combine(Path.GetDirectoryName(sourceFilePath), @"..\..\.."); } private static void Main(string[] args) { Environment.SetEnvironmentVariable(RoslynRootPathEnvVariableName, GetRoslynRootLocation()); new BenchmarkSwitcher(typeof(Program).Assembly).Run(args); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/AbstractItemEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Documents; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { private abstract class AbstractItemEntry : Entry { protected readonly StreamingFindUsagesPresenter Presenter; public AbstractItemEntry(RoslynDefinitionBucket definitionBucket, StreamingFindUsagesPresenter presenter) : base(definitionBucket) { Presenter = presenter; } public override bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content) { if (columnName == StandardTableColumnDefinitions2.LineText) { var inlines = CreateLineTextInlines(); var textBlock = inlines.ToTextBlock(Presenter.ClassificationFormatMap, wrap: false); content = textBlock; return true; } content = null; return false; } protected abstract IList<Inline> CreateLineTextInlines(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Documents; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { private abstract class AbstractItemEntry : Entry { protected readonly StreamingFindUsagesPresenter Presenter; public AbstractItemEntry(RoslynDefinitionBucket definitionBucket, StreamingFindUsagesPresenter presenter) : base(definitionBucket) { Presenter = presenter; } public override bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content) { if (columnName == StandardTableColumnDefinitions2.LineText) { var inlines = CreateLineTextInlines(); var textBlock = inlines.ToTextBlock(Presenter.ClassificationFormatMap, wrap: false); content = textBlock; return true; } content = null; return false; } protected abstract IList<Inline> CreateLineTextInlines(); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/CSharp/Impl/LanguageService/CSharpDebuggerIntelliSenseContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { internal class CSharpDebuggerIntelliSenseContext : AbstractDebuggerIntelliSenseContext { public CSharpDebuggerIntelliSenseContext( IWpfTextView view, IVsTextView vsTextView, IVsTextLines debuggerBuffer, ITextBuffer contextBuffer, TextSpan[] currentStatementSpan, IComponentModel componentModel, IServiceProvider serviceProvider) : base(view, vsTextView, debuggerBuffer, contextBuffer, currentStatementSpan, componentModel, serviceProvider, componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType)) { } // Test constructor internal CSharpDebuggerIntelliSenseContext( IWpfTextView view, ITextBuffer contextBuffer, TextSpan[] currentStatementSpan, IComponentModel componentModel, bool immediateWindow) : base(view, contextBuffer, currentStatementSpan, componentModel, componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType), immediateWindow) { } protected override int GetAdjustedContextPoint(int contextPoint, Document document) { // Determine the position in the buffer at which to end the tracking span representing // the part of the imaginary buffer before the text in the view. var tree = document.GetSyntaxTreeSynchronously(CancellationToken.None); var token = tree.FindTokenOnLeftOfPosition(contextPoint, CancellationToken.None); // Special case to handle class designer because it asks for debugger IntelliSense using // spans between members. if (contextPoint > token.Span.End && token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Block) && token.Parent.Parent is MemberDeclarationSyntax) { return contextPoint; } if (token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Block)) { return token.SpanStart; } return token.FullSpan.End; } protected override ITrackingSpan GetPreviousStatementBufferAndSpan(int contextPoint, Document document) { var previousTrackingSpan = ContextBuffer.CurrentSnapshot.CreateTrackingSpan(Span.FromBounds(0, contextPoint), SpanTrackingMode.EdgeNegative); // terminate the previous expression/statement var buffer = ProjectionBufferFactoryService.CreateProjectionBuffer( projectionEditResolver: null, sourceSpans: new object[] { previousTrackingSpan, this.StatementTerminator }, options: ProjectionBufferOptions.None, contentType: this.ContentType); return buffer.CurrentSnapshot.CreateTrackingSpan(0, buffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeNegative); } public override bool CompletionStartsOnQuestionMark { get { return false; } } protected override string StatementTerminator { get { return ";"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { internal class CSharpDebuggerIntelliSenseContext : AbstractDebuggerIntelliSenseContext { public CSharpDebuggerIntelliSenseContext( IWpfTextView view, IVsTextView vsTextView, IVsTextLines debuggerBuffer, ITextBuffer contextBuffer, TextSpan[] currentStatementSpan, IComponentModel componentModel, IServiceProvider serviceProvider) : base(view, vsTextView, debuggerBuffer, contextBuffer, currentStatementSpan, componentModel, serviceProvider, componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType)) { } // Test constructor internal CSharpDebuggerIntelliSenseContext( IWpfTextView view, ITextBuffer contextBuffer, TextSpan[] currentStatementSpan, IComponentModel componentModel, bool immediateWindow) : base(view, contextBuffer, currentStatementSpan, componentModel, componentModel.GetService<IContentTypeRegistryService>().GetContentType(ContentTypeNames.CSharpContentType), immediateWindow) { } protected override int GetAdjustedContextPoint(int contextPoint, Document document) { // Determine the position in the buffer at which to end the tracking span representing // the part of the imaginary buffer before the text in the view. var tree = document.GetSyntaxTreeSynchronously(CancellationToken.None); var token = tree.FindTokenOnLeftOfPosition(contextPoint, CancellationToken.None); // Special case to handle class designer because it asks for debugger IntelliSense using // spans between members. if (contextPoint > token.Span.End && token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Block) && token.Parent.Parent is MemberDeclarationSyntax) { return contextPoint; } if (token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Block)) { return token.SpanStart; } return token.FullSpan.End; } protected override ITrackingSpan GetPreviousStatementBufferAndSpan(int contextPoint, Document document) { var previousTrackingSpan = ContextBuffer.CurrentSnapshot.CreateTrackingSpan(Span.FromBounds(0, contextPoint), SpanTrackingMode.EdgeNegative); // terminate the previous expression/statement var buffer = ProjectionBufferFactoryService.CreateProjectionBuffer( projectionEditResolver: null, sourceSpans: new object[] { previousTrackingSpan, this.StatementTerminator }, options: ProjectionBufferOptions.None, contentType: this.ContentType); return buffer.CurrentSnapshot.CreateTrackingSpan(0, buffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeNegative); } public override bool CompletionStartsOnQuestionMark { get { return false; } } protected override string StatementTerminator { get { return ";"; } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Test/Emit/Emit/ResourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Globalization; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class ResourceTests : CSharpTestBase { [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void DefaultVersionResource() { string source = @" public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerNoAttrs", options: TestOptions.ReleaseExe); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; string mftData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint mftSize; IntPtr mftRsrc = Win32Res.GetResource(lib, "#1", "#24", out mftSize); mftData = Win32Res.ManifestResourceToXml(mftRsrc, mftSize); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""612""> <VS_FIXEDFILEINFO FileVersionMS=""00000000"" FileVersionLS=""00000000"" ProductVersionMS=""00000000"" ProductVersionLS=""00000000"" /> <KeyValuePair Key=""FileDescription"" Value="" "" /> <KeyValuePair Key=""FileVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value="" "" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""ProductVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""Assembly Version"" Value=""0.0.0.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"; Assert.Equal(expected, mftData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal(" ", fileVer.LegalCopyright); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourcesInCoff() { //this is to test that resources coming from a COFF can be added to a binary. string source = @" class C { } "; var c1 = CreateCompilation(source, assemblyName: "Win32WithCoff", options: TestOptions.ReleaseDll); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { var memStream = new MemoryStream(TestResources.General.nativeCOFFResources); c1.Emit(output, win32Resources: memStream); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the resources //we expect are present. Also need to check that the actual contents of at least one of the resources //is good. That tests our processing of the relocations. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint stringTableSize; IntPtr stringTable = Win32Res.GetResource(lib, "#1", "#6", out stringTableSize); Assert.NotEqual(default, stringTable); uint elevenSize; IntPtr elevenRsrc = Win32Res.GetResource(lib, "#1", "#11", out elevenSize); Assert.NotEqual(default, elevenRsrc); uint wevtSize; IntPtr wevtRsrc = Win32Res.GetResource(lib, "#1", "WEVT_TEMPLATE", out wevtSize); Assert.NotEqual(default, wevtRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""1104""> <VS_FIXEDFILEINFO FileVersionMS=""000b0000"" FileVersionLS=""eacc0000"" ProductVersionMS=""000b0000"" ProductVersionLS=""eacc0000"" /> <KeyValuePair Key=""CompanyName"" Value=""Microsoft Corporation"" /> <KeyValuePair Key=""FileDescription"" Value=""Team Foundation Server Object Model"" /> <KeyValuePair Key=""FileVersion"" Value=""11.0.60108.0 built by: TOOLSET_ROSLYN(GNAMBOO-DEV-GNAMBOO)"" /> <KeyValuePair Key=""InternalName"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""LegalCopyright"" Value=""© Microsoft Corporation. All rights reserved."" /> <KeyValuePair Key=""OriginalFilename"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""ProductName"" Value=""Microsoft® Visual Studio® 2012"" /> <KeyValuePair Key=""ProductVersion"" Value=""11.0.60108.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal("Microsoft Corporation", fileVer.CompanyName); } [Fact] public void FaultyResourceDataProvider() { var c1 = CreateCompilation(""); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => { throw new Exception("bad stuff"); }, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'bad stuff' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", "bad stuff") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => null, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'Resource data provider should return non-null stream' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream) ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier_EmbeddedResource() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("A", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS7041_DuplicateManifestResourceFileName() { var c1 = CSharpCompilation.Create("goo", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void NoDuplicateManifestResourceFileNameDiagnosticForEmbeddedResources() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("B", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify(); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("B", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify(); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501"), WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] [Fact] public void CS1508_CS7041_DuplicateManifestResourceDiagnostics() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A"), // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true), new ResourceDescription("B", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo"), // error CS1508: Resource identifier 'B' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("B") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "goo.dll", dataProvider, true), }); //make sure there's no problem when the name of the primary module conflicts with a file name of an added resource. result.Diagnostics.Verify(); var netModule1 = TestReferences.SymbolsTests.netModule.netModule1; c1 = CreateCompilation("", references: new[] { netModule1 }); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "netmodule1.netmodule", dataProvider, true), }); // Native compiler gives CS0013 (FTL_MetadataEmitFailure) at Emit stage result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'netmodule1.netmodule' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("netModule1.netmodule") ); } [ConditionalFact(typeof(DesktopOnly))] public void AddManagedResource() { string source = @"public class C { static public void Main() {} }"; // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CreateCompilation(source); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var assembly = Assembly.ReflectionOnlyLoad(output.ToArray()); string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(resourceFileName, rInfo.FileName); c1 = null; } [ConditionalFact(typeof(WindowsDesktopOnly))] public void AddResourceToModule() { bool metadataOnly = false; Func<Compilation, Stream, ResourceDescription[], CodeAnalysis.Emit.EmitResult> emit; emit = (c, s, r) => c.Emit(s, manifestResources: r, options: new EmitOptions(metadataOnly: metadataOnly)); var sourceTree = SyntaxFactory.ParseSyntaxTree(""); // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false), new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); var c_mod1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod1 = new MemoryStream(); result = emit(c_mod1, output_mod1, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.True(result.Success); var mod1 = ModuleMetadata.CreateFromImage(output_mod1.ToImmutable()); var ref_mod1 = mod1.GetReference(); Assert.Equal(ManifestResourceAttributes.Public, mod1.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c2 = CreateCompilation(sourceTree, new[] { ref_mod1 }, TestOptions.ReleaseDll); var output2 = new MemoryStream(); var result2 = c2.Emit(output2); Assert.True(result2.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output2.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(1, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(System.Reflection.ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); } var c_mod2 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod2 = new MemoryStream(); result = emit(c_mod2, output_mod2, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), true) }); Assert.True(result.Success); var ref_mod2 = ModuleMetadata.CreateFromImage(output_mod2.ToImmutable()).GetReference(); { var c3 = CreateCompilation(sourceTree, new[] { ref_mod2 }, TestOptions.ReleaseDll); var output3 = new MemoryStream(); var result3 = c3.Emit(output3); Assert.True(result3.Success); var assembly = Assembly.ReflectionOnlyLoad(output3.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod2.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod2.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } var c_mod3 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod3 = new MemoryStream(); result = emit(c_mod3, output_mod3, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var mod3 = ModuleMetadata.CreateFromImage(output_mod3.ToImmutable()); var ref_mod3 = mod3.GetReference(); Assert.Equal(ManifestResourceAttributes.Private, mod3.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c4 = CreateCompilation(sourceTree, new[] { ref_mod3 }, TestOptions.ReleaseDll); var output4 = new MemoryStream(); var result4 = c4.Emit(output4, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), false) }); Assert.True(result4.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output4.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c5 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod3 }, TestOptions.ReleaseDll); var output5 = new MemoryStream(); var result5 = emit(c5, output5, null); Assert.True(result5.Success); var assembly = Assembly.ReflectionOnlyLoad(output5.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } else if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseDll); var output6 = new MemoryStream(); var result6 = emit(c6, output6, null); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME") ); } result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME"), // error CS1508: Resource identifier 'another.DoTtEd.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("another.DoTtEd.NAME") ); } c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseModule); result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result6.Success); } } [Fact] public void AddManagedLinkedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, "nonExistent", () => { throw new NotSupportedException("error in data provider"); }, false) }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [Fact] public void AddManagedEmbeddedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, () => null, true), }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourceWithAttrSettings() { string source = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyFileVersion(""5.6.7.8"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] [assembly: System.Reflection.AssemblyDescription(""A classic of magical realist literature"")] [assembly: System.Reflection.AssemblyCompany(""MossBrain"")] [assembly: System.Reflection.AssemblyProduct(""Sound Cannon"")] [assembly: System.Reflection.AssemblyCopyright(""circle C"")] [assembly: System.Reflection.AssemblyTrademark(""circle R"")] [assembly: System.Reflection.AssemblyInformationalVersion(""1.2.3garbage"")] public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerAttrs", options: TestOptions.ReleaseExe); var exeFile = Temp.CreateFile(); using (FileStream output = exeFile.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; string versionData; //Open as data IntPtr lib = IntPtr.Zero; try { lib = LoadLibraryEx(exeFile.Path, IntPtr.Zero, 0x00000002); Assert.True(lib != IntPtr.Zero, String.Format("LoadLibrary failed with HResult: {0:X}", +Marshal.GetLastWin32Error())); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""964""> <VS_FIXEDFILEINFO FileVersionMS=""00050006"" FileVersionLS=""00070008"" ProductVersionMS=""00010002"" ProductVersionLS=""00030000"" /> <KeyValuePair Key=""Comments"" Value=""A classic of magical realist literature"" /> <KeyValuePair Key=""CompanyName"" Value=""MossBrain"" /> <KeyValuePair Key=""FileDescription"" Value=""One Hundred Years of Solitude"" /> <KeyValuePair Key=""FileVersion"" Value=""5.6.7.8"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value=""circle C"" /> <KeyValuePair Key=""LegalTrademarks"" Value=""circle R"" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""ProductName"" Value=""Sound Cannon"" /> <KeyValuePair Key=""ProductVersion"" Value=""1.2.3garbage"" /> <KeyValuePair Key=""Assembly Version"" Value=""1.2.3.4"" /> </VersionResource>"; Assert.Equal(expected, versionData); } [Fact] public void ResourceProviderStreamGivesBadLength() { var backingStream = new MemoryStream(new byte[] { 1, 2, 3, 4 }); var stream = new TestStream( canRead: true, canSeek: true, readFunc: backingStream.Read, length: 6, // Lie about the length (> backingStream.Length) getPosition: () => backingStream.Position); var c1 = CreateCompilation(""); using (new EnsureEnglishUICulture()) { var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("res", () => stream, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'res' -- 'Resource stream ended at 4 bytes, expected 6 bytes.' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("res", "Resource stream ended at 4 bytes, expected 6 bytes.").WithLocation(1, 1)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Globalization; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class ResourceTests : CSharpTestBase { [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void DefaultVersionResource() { string source = @" public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerNoAttrs", options: TestOptions.ReleaseExe); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; string mftData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint mftSize; IntPtr mftRsrc = Win32Res.GetResource(lib, "#1", "#24", out mftSize); mftData = Win32Res.ManifestResourceToXml(mftRsrc, mftSize); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""612""> <VS_FIXEDFILEINFO FileVersionMS=""00000000"" FileVersionLS=""00000000"" ProductVersionMS=""00000000"" ProductVersionLS=""00000000"" /> <KeyValuePair Key=""FileDescription"" Value="" "" /> <KeyValuePair Key=""FileVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value="" "" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerNoAttrs.exe"" /> <KeyValuePair Key=""ProductVersion"" Value=""0.0.0.0"" /> <KeyValuePair Key=""Assembly Version"" Value=""0.0.0.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"; Assert.Equal(expected, mftData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal(" ", fileVer.LegalCopyright); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourcesInCoff() { //this is to test that resources coming from a COFF can be added to a binary. string source = @" class C { } "; var c1 = CreateCompilation(source, assemblyName: "Win32WithCoff", options: TestOptions.ReleaseDll); var exe = Temp.CreateFile(); using (FileStream output = exe.Open()) { var memStream = new MemoryStream(TestResources.General.nativeCOFFResources); c1.Emit(output, win32Resources: memStream); } c1 = null; //Open as data IntPtr lib = IntPtr.Zero; string versionData; try { lib = LoadLibraryEx(exe.Path, IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //the manifest and version primitives are tested elsewhere. This is to test that the resources //we expect are present. Also need to check that the actual contents of at least one of the resources //is good. That tests our processing of the relocations. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); uint stringTableSize; IntPtr stringTable = Win32Res.GetResource(lib, "#1", "#6", out stringTableSize); Assert.NotEqual(default, stringTable); uint elevenSize; IntPtr elevenRsrc = Win32Res.GetResource(lib, "#1", "#11", out elevenSize); Assert.NotEqual(default, elevenRsrc); uint wevtSize; IntPtr wevtRsrc = Win32Res.GetResource(lib, "#1", "WEVT_TEMPLATE", out wevtSize); Assert.NotEqual(default, wevtRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""1104""> <VS_FIXEDFILEINFO FileVersionMS=""000b0000"" FileVersionLS=""eacc0000"" ProductVersionMS=""000b0000"" ProductVersionLS=""eacc0000"" /> <KeyValuePair Key=""CompanyName"" Value=""Microsoft Corporation"" /> <KeyValuePair Key=""FileDescription"" Value=""Team Foundation Server Object Model"" /> <KeyValuePair Key=""FileVersion"" Value=""11.0.60108.0 built by: TOOLSET_ROSLYN(GNAMBOO-DEV-GNAMBOO)"" /> <KeyValuePair Key=""InternalName"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""LegalCopyright"" Value=""© Microsoft Corporation. All rights reserved."" /> <KeyValuePair Key=""OriginalFilename"" Value=""Microsoft.TeamFoundation.Framework.Server.dll"" /> <KeyValuePair Key=""ProductName"" Value=""Microsoft® Visual Studio® 2012"" /> <KeyValuePair Key=""ProductVersion"" Value=""11.0.60108.0"" /> </VersionResource>"; Assert.Equal(expected, versionData); //look at the same data through the FileVersion API. //If the codepage and resource language information is not //written correctly into the internal resource directory of //the PE, then GetVersionInfo will fail to find the FileVersionInfo. //Once upon a time in Roslyn, the codepage and lang info was not written correctly. var fileVer = FileVersionInfo.GetVersionInfo(exe.Path); Assert.Equal("Microsoft Corporation", fileVer.CompanyName); } [Fact] public void FaultyResourceDataProvider() { var c1 = CreateCompilation(""); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => { throw new Exception("bad stuff"); }, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'bad stuff' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", "bad stuff") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("r2", "file", () => null, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'file' -- 'Resource data provider should return non-null stream' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("file", CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream) ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS1508_DuplicateManifestResourceIdentifier_EmbeddedResource() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("A", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void CS7041_DuplicateManifestResourceFileName() { var c1 = CSharpCompilation.Create("goo", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501")] [Fact] public void NoDuplicateManifestResourceFileNameDiagnosticForEmbeddedResources() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", dataProvider, true), new ResourceDescription("B", null, dataProvider, true, isEmbedded: true, checkArgs: true) }); result.Diagnostics.Verify(); // file name ignored for embedded manifest resources result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true, isEmbedded: true, checkArgs: true), new ResourceDescription("B", "x.goo", dataProvider, true, isEmbedded: false, checkArgs: true) }); result.Diagnostics.Verify(); } [WorkItem(543501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543501"), WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] [Fact] public void CS1508_CS7041_DuplicateManifestResourceDiagnostics() { var c1 = CreateCompilation(""); Func<Stream> dataProvider = () => new MemoryStream(new byte[] { }); var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("A", "x.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS1508: Resource identifier 'A' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("A"), // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "x.goo", dataProvider, true), new ResourceDescription("B", "x.goo", dataProvider, true), new ResourceDescription("B", "y.goo", dataProvider, true) }); result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'x.goo' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("x.goo"), // error CS1508: Resource identifier 'B' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("B") ); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "goo.dll", dataProvider, true), }); //make sure there's no problem when the name of the primary module conflicts with a file name of an added resource. result.Diagnostics.Verify(); var netModule1 = TestReferences.SymbolsTests.netModule.netModule1; c1 = CreateCompilation("", references: new[] { netModule1 }); result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("A", "netmodule1.netmodule", dataProvider, true), }); // Native compiler gives CS0013 (FTL_MetadataEmitFailure) at Emit stage result.Diagnostics.Verify( // error CS7041: Each linked resource and module must have a unique filename. Filename 'netmodule1.netmodule' is specified more than once in this assembly Diagnostic(ErrorCode.ERR_ResourceFileNameNotUnique).WithArguments("netModule1.netmodule") ); } [ConditionalFact(typeof(DesktopOnly))] public void AddManagedResource() { string source = @"public class C { static public void Main() {} }"; // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CreateCompilation(source); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var assembly = Assembly.ReflectionOnlyLoad(output.ToArray()); string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(resourceFileName, rInfo.FileName); c1 = null; } [ConditionalFact(typeof(WindowsDesktopOnly))] public void AddResourceToModule() { bool metadataOnly = false; Func<Compilation, Stream, ResourceDescription[], CodeAnalysis.Emit.EmitResult> emit; emit = (c, s, r) => c.Emit(s, manifestResources: r, options: new EmitOptions(metadataOnly: metadataOnly)); var sourceTree = SyntaxFactory.ParseSyntaxTree(""); // Do not name the compilation, a unique guid is used as a name by default. It prevents conflicts with other assemblies loaded via Assembly.ReflectionOnlyLoad. var c1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var resourceFileName = "RoslynResourceFile.goo"; var output = new MemoryStream(); const string r1Name = "some.dotted.NAME"; const string r2Name = "another.DoTtEd.NAME"; var arrayOfEmbeddedData = new byte[] { 1, 2, 3, 4, 5 }; var resourceFileData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false), new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); result = emit(c1, output, new ResourceDescription[] { new ResourceDescription(r2Name, resourceFileName, () => new MemoryStream(resourceFileData), false) }); Assert.False(result.Success); Assert.NotEmpty(result.Diagnostics.Where(x => x.Code == (int)ErrorCode.ERR_CantRefResource)); var c_mod1 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod1 = new MemoryStream(); result = emit(c_mod1, output_mod1, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true) }); Assert.True(result.Success); var mod1 = ModuleMetadata.CreateFromImage(output_mod1.ToImmutable()); var ref_mod1 = mod1.GetReference(); Assert.Equal(ManifestResourceAttributes.Public, mod1.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c2 = CreateCompilation(sourceTree, new[] { ref_mod1 }, TestOptions.ReleaseDll); var output2 = new MemoryStream(); var result2 = c2.Emit(output2); Assert.True(result2.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output2.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(1, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(System.Reflection.ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); } var c_mod2 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod2 = new MemoryStream(); result = emit(c_mod2, output_mod2, new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), true), new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), true) }); Assert.True(result.Success); var ref_mod2 = ModuleMetadata.CreateFromImage(output_mod2.ToImmutable()).GetReference(); { var c3 = CreateCompilation(sourceTree, new[] { ref_mod2 }, TestOptions.ReleaseDll); var output3 = new MemoryStream(); var result3 = c3.Emit(output3); Assert.True(result3.Success); var assembly = Assembly.ReflectionOnlyLoad(output3.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod2.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod2.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod2.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } var c_mod3 = CSharpCompilation.Create( Guid.NewGuid().ToString(), new[] { sourceTree }, new[] { MscorlibRef }, TestOptions.ReleaseModule); var output_mod3 = new MemoryStream(); result = emit(c_mod3, output_mod3, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result.Success); var mod3 = ModuleMetadata.CreateFromImage(output_mod3.ToImmutable()); var ref_mod3 = mod3.GetReference(); Assert.Equal(ManifestResourceAttributes.Private, mod3.Module.GetEmbeddedResourcesOrThrow()[0].Attributes); { var c4 = CreateCompilation(sourceTree, new[] { ref_mod3 }, TestOptions.ReleaseDll); var output4 = new MemoryStream(); var result4 = c4.Emit(output4, manifestResources: new ResourceDescription[] { new ResourceDescription(r1Name, () => new MemoryStream(arrayOfEmbeddedData), false) }); Assert.True(result4.Success); var assembly = System.Reflection.Assembly.ReflectionOnlyLoad(output4.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, rInfo.ResourceLocation); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c5 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod3 }, TestOptions.ReleaseDll); var output5 = new MemoryStream(); var result5 = emit(c5, output5, null); Assert.True(result5.Success); var assembly = Assembly.ReflectionOnlyLoad(output5.ToArray()); assembly.ModuleResolve += (object sender, ResolveEventArgs e) => { if (e.Name.Equals(c_mod1.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod1.ToArray()); } else if (e.Name.Equals(c_mod3.SourceModule.Name)) { return assembly.LoadModule(e.Name, output_mod3.ToArray()); } return null; }; string[] resourceNames = assembly.GetManifestResourceNames(); Assert.Equal(2, resourceNames.Length); var rInfo = assembly.GetManifestResourceInfo(r1Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod1.SourceModule.Name, rInfo.FileName); var rData = assembly.GetManifestResourceStream(r1Name); var rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(arrayOfEmbeddedData, rBytes); rInfo = assembly.GetManifestResourceInfo(r2Name); Assert.Equal(ResourceLocation.Embedded, rInfo.ResourceLocation); Assert.Equal(c_mod3.SourceModule.Name, rInfo.FileName); rData = assembly.GetManifestResourceStream(r2Name); rBytes = new byte[rData.Length]; rData.Read(rBytes, 0, (int)rData.Length); Assert.Equal(resourceFileData, rBytes); } { var c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseDll); var output6 = new MemoryStream(); var result6 = emit(c6, output6, null); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME") ); } result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); if (metadataOnly) { Assert.True(result6.Success); } else { Assert.False(result6.Success); result6.Diagnostics.Verify( // error CS1508: Resource identifier 'some.dotted.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("some.dotted.NAME"), // error CS1508: Resource identifier 'another.DoTtEd.NAME' has already been used in this assembly Diagnostic(ErrorCode.ERR_ResourceNotUnique).WithArguments("another.DoTtEd.NAME") ); } c6 = CreateCompilation(sourceTree, new[] { ref_mod1, ref_mod2 }, TestOptions.ReleaseModule); result6 = emit(c6, output6, new ResourceDescription[] { new ResourceDescription(r2Name, () => new MemoryStream(resourceFileData), false) }); Assert.True(result6.Success); } } [Fact] public void AddManagedLinkedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, "nonExistent", () => { throw new NotSupportedException("error in data provider"); }, false) }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [Fact] public void AddManagedEmbeddedResourceFail() { string source = @" public class Maine { static public void Main() { } } "; var c1 = CreateCompilation(source); var output = new MemoryStream(); const string r2Name = "another.DoTtEd.NAME"; var result = c1.Emit(output, manifestResources: new ResourceDescription[] { new ResourceDescription(r2Name, () => null, true), }); Assert.False(result.Success); Assert.Equal((int)ErrorCode.ERR_CantReadResource, result.Diagnostics.ToArray()[0].Code); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void ResourceWithAttrSettings() { string source = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyFileVersion(""5.6.7.8"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] [assembly: System.Reflection.AssemblyDescription(""A classic of magical realist literature"")] [assembly: System.Reflection.AssemblyCompany(""MossBrain"")] [assembly: System.Reflection.AssemblyProduct(""Sound Cannon"")] [assembly: System.Reflection.AssemblyCopyright(""circle C"")] [assembly: System.Reflection.AssemblyTrademark(""circle R"")] [assembly: System.Reflection.AssemblyInformationalVersion(""1.2.3garbage"")] public class Maine { public static void Main() { } } "; var c1 = CreateCompilation(source, assemblyName: "Win32VerAttrs", options: TestOptions.ReleaseExe); var exeFile = Temp.CreateFile(); using (FileStream output = exeFile.Open()) { c1.Emit(output, win32Resources: c1.CreateDefaultWin32Resources(true, false, null, null)); } c1 = null; string versionData; //Open as data IntPtr lib = IntPtr.Zero; try { lib = LoadLibraryEx(exeFile.Path, IntPtr.Zero, 0x00000002); Assert.True(lib != IntPtr.Zero, String.Format("LoadLibrary failed with HResult: {0:X}", +Marshal.GetLastWin32Error())); //the manifest and version primitives are tested elsewhere. This is to test that the default //values are passed to the primitives that assemble the resources. uint size; IntPtr versionRsrc = Win32Res.GetResource(lib, "#1", "#16", out size); versionData = Win32Res.VersionResourceToXml(versionRsrc); } finally { if (lib != IntPtr.Zero) { FreeLibrary(lib); } } string expected = @"<?xml version=""1.0"" encoding=""utf-16""?> <VersionResource Size=""964""> <VS_FIXEDFILEINFO FileVersionMS=""00050006"" FileVersionLS=""00070008"" ProductVersionMS=""00010002"" ProductVersionLS=""00030000"" /> <KeyValuePair Key=""Comments"" Value=""A classic of magical realist literature"" /> <KeyValuePair Key=""CompanyName"" Value=""MossBrain"" /> <KeyValuePair Key=""FileDescription"" Value=""One Hundred Years of Solitude"" /> <KeyValuePair Key=""FileVersion"" Value=""5.6.7.8"" /> <KeyValuePair Key=""InternalName"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""LegalCopyright"" Value=""circle C"" /> <KeyValuePair Key=""LegalTrademarks"" Value=""circle R"" /> <KeyValuePair Key=""OriginalFilename"" Value=""Win32VerAttrs.exe"" /> <KeyValuePair Key=""ProductName"" Value=""Sound Cannon"" /> <KeyValuePair Key=""ProductVersion"" Value=""1.2.3garbage"" /> <KeyValuePair Key=""Assembly Version"" Value=""1.2.3.4"" /> </VersionResource>"; Assert.Equal(expected, versionData); } [Fact] public void ResourceProviderStreamGivesBadLength() { var backingStream = new MemoryStream(new byte[] { 1, 2, 3, 4 }); var stream = new TestStream( canRead: true, canSeek: true, readFunc: backingStream.Read, length: 6, // Lie about the length (> backingStream.Length) getPosition: () => backingStream.Position); var c1 = CreateCompilation(""); using (new EnsureEnglishUICulture()) { var result = c1.Emit(new MemoryStream(), manifestResources: new[] { new ResourceDescription("res", () => stream, false) }); result.Diagnostics.Verify( // error CS1566: Error reading resource 'res' -- 'Resource stream ended at 4 bytes, expected 6 bytes.' Diagnostic(ErrorCode.ERR_CantReadResource).WithArguments("res", "Resource stream ended at 4 bytes, expected 6 bytes.").WithLocation(1, 1)); } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/Core/Portable/LinkedFileDiffMerging/UnmergedDocumentChanges.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal sealed class UnmergedDocumentChanges { public IEnumerable<TextChange> UnmergedChanges { get; } public string ProjectName { get; } public DocumentId DocumentId { get; } public UnmergedDocumentChanges(IEnumerable<TextChange> unmergedChanges, string projectName, DocumentId documentId) { UnmergedChanges = unmergedChanges; ProjectName = projectName; DocumentId = documentId; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal sealed class UnmergedDocumentChanges { public IEnumerable<TextChange> UnmergedChanges { get; } public string ProjectName { get; } public DocumentId DocumentId { get; } public UnmergedDocumentChanges(IEnumerable<TextChange> unmergedChanges, string projectName, DocumentId documentId) { UnmergedChanges = unmergedChanges; ProjectName = projectName; DocumentId = documentId; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/RebuildTest/CompilationOptionsReaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Rebuild; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.Extensions.Logging; using Xunit; using Microsoft.Cci; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Rebuild.UnitTests { public class CompilationOptionsReaderTests : CSharpTestBase { private CompilationOptionsReader GetOptionsReader(Compilation compilation) { compilation.VerifyDiagnostics(); var peBytes = compilation.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded)); var originalReader = new PEReader(peBytes); var originalPdbReader = originalReader.GetEmbeddedPdbMetadataReader(); AssertEx.NotNull(originalPdbReader); var factory = LoggerFactory.Create(configure => { }); var logger = factory.CreateLogger("RoundTripVerification"); return new CompilationOptionsReader(logger, originalPdbReader, originalReader); } [Fact] public void PublicKeyNetModule() { var compilation = CreateCompilation( options: TestOptions.DebugModule, source: @" class C { } "); var reader = GetOptionsReader(compilation); Assert.Null(reader.GetPublicKey()); } [Theory] [CombinatorialData] public void OutputKind(OutputKind kind) { var compilation = CreateCompilation( options: new CSharpCompilationOptions(outputKind: kind), source: @" class Program { public static void Main() { } }"); var reader = GetOptionsReader(compilation); Assert.Equal(kind, reader.GetMetadataCompilationOptions().OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Rebuild; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.Extensions.Logging; using Xunit; using Microsoft.Cci; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Rebuild.UnitTests { public class CompilationOptionsReaderTests : CSharpTestBase { private CompilationOptionsReader GetOptionsReader(Compilation compilation) { compilation.VerifyDiagnostics(); var peBytes = compilation.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded)); var originalReader = new PEReader(peBytes); var originalPdbReader = originalReader.GetEmbeddedPdbMetadataReader(); AssertEx.NotNull(originalPdbReader); var factory = LoggerFactory.Create(configure => { }); var logger = factory.CreateLogger("RoundTripVerification"); return new CompilationOptionsReader(logger, originalPdbReader, originalReader); } [Fact] public void PublicKeyNetModule() { var compilation = CreateCompilation( options: TestOptions.DebugModule, source: @" class C { } "); var reader = GetOptionsReader(compilation); Assert.Null(reader.GetPublicKey()); } [Theory] [CombinatorialData] public void OutputKind(OutputKind kind) { var compilation = CreateCompilation( options: new CSharpCompilationOptions(outputKind: kind), source: @" class Program { public static void Main() { } }"); var reader = GetOptionsReader(compilation); Assert.Equal(kind, reader.GetMetadataCompilationOptions().OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind)); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.AttributeInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == null; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == null; } } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DynamicKeywordRecommenderTests : RecommenderTests { private readonly DynamicKeywordRecommender _recommender = new DynamicKeywordRecommender(); public DynamicKeywordRecommenderTests() { this.keywordText = "dynamic"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFixedStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(545303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545303")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreProcessor() { await VerifyAbsenceAsync( @"class Program { #region $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DynamicKeywordRecommenderTests : RecommenderTests { private readonly DynamicKeywordRecommender _recommender = new DynamicKeywordRecommender(); public DynamicKeywordRecommenderTests() { this.keywordText = "dynamic"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFixedStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(545303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545303")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreProcessor() { await VerifyAbsenceAsync( @"class Program { #region $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/VisualBasic/Portable/GenerateDefaultConstructors/VisualBasicGenerateDefaultConstructorsCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.GenerateDefaultConstructors Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateDefaultConstructors <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateDefaultConstructors), [Shared]> Friend Class VisualBasicGenerateDefaultConstructorsCodeFixProvider Inherits AbstractGenerateDefaultConstructorCodeFixProvider Private Const BC30387 As String = NameOf(BC30387) ' Class 'C' must declare a 'Sub New' because its base class 'B' does not have an accessible 'Sub New' that can be called with no arguments. Private Const BC40056 As String = NameOf(BC40056) ' Namespace or type specified in the Imports 'TestProj' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As Immutable.ImmutableArray(Of String) = ImmutableArray.Create(BC30387, BC40056) End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.GenerateDefaultConstructors Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateDefaultConstructors <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateDefaultConstructors), [Shared]> Friend Class VisualBasicGenerateDefaultConstructorsCodeFixProvider Inherits AbstractGenerateDefaultConstructorCodeFixProvider Private Const BC30387 As String = NameOf(BC30387) ' Class 'C' must declare a 'Sub New' because its base class 'B' does not have an accessible 'Sub New' that can be called with no arguments. Private Const BC40056 As String = NameOf(BC40056) ' Namespace or type specified in the Imports 'TestProj' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As Immutable.ImmutableArray(Of String) = ImmutableArray.Create(BC30387, BC40056) End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpErrorListDesktop.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListDesktop : CSharpErrorListCommon { public CSharpErrorListDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorList() { base.ErrorList(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListDesktop : CSharpErrorListCommon { public CSharpErrorListDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorList() { base.ErrorList(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/InheritsGraphQuery.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class InheritsGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (var depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is INamedTypeSymbol namedType) { if (namedType.BaseType != null) { var baseTypeNode = await graphBuilder.AddNodeAsync( namedType.BaseType, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } else if (namedType.TypeKind == TypeKind.Interface && !namedType.OriginalDefinition.AllInterfaces.IsEmpty) { foreach (var baseNode in namedType.OriginalDefinition.AllInterfaces.Distinct()) { var baseTypeNode = await graphBuilder.AddNodeAsync( baseNode, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } } } } nodesToProcess = newNodes; } return graphBuilder; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class InheritsGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (var depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is INamedTypeSymbol namedType) { if (namedType.BaseType != null) { var baseTypeNode = await graphBuilder.AddNodeAsync( namedType.BaseType, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } else if (namedType.TypeKind == TypeKind.Interface && !namedType.OriginalDefinition.AllInterfaces.IsEmpty) { foreach (var baseNode in namedType.OriginalDefinition.AllInterfaces.Distinct()) { var baseTypeNode = await graphBuilder.AddNodeAsync( baseNode, relatedNode: node, cancellationToken).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode, cancellationToken); } } } } nodesToProcess = newNodes; } return graphBuilder; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/Core/Implementation/IntelliSense/QuickInfo/IntellisenseQuickInfoBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using CodeAnalysisQuickInfoItem = Microsoft.CodeAnalysis.QuickInfo.QuickInfoItem; using IntellisenseQuickInfoItem = Microsoft.VisualStudio.Language.Intellisense.QuickInfoItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo { internal static class IntellisenseQuickInfoBuilder { private static async Task<ContainerElement> BuildInteractiveContentAsync(CodeAnalysisQuickInfoItem quickInfoItem, IntellisenseQuickInfoBuilderContext? context, CancellationToken cancellationToken) { // Build the first line of QuickInfo item, the images and the Description section should be on the first line with Wrapped style var glyphs = quickInfoItem.Tags.GetGlyphs(); var symbolGlyph = glyphs.FirstOrDefault(g => g != Glyph.CompletionWarning); var warningGlyph = glyphs.FirstOrDefault(g => g == Glyph.CompletionWarning); var firstLineElements = new List<object>(); if (symbolGlyph != Glyph.None) { firstLineElements.Add(new ImageElement(symbolGlyph.GetImageId())); } if (warningGlyph != Glyph.None) { firstLineElements.Add(new ImageElement(warningGlyph.GetImageId())); } var elements = new List<object>(); var descSection = quickInfoItem.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.Description); if (descSection != null) { var isFirstElement = true; foreach (var element in Helpers.BuildInteractiveTextElements(descSection.TaggedParts, context)) { if (isFirstElement) { isFirstElement = false; firstLineElements.Add(element); } else { // If the description section contains multiple paragraphs, the second and additional paragraphs // are not wrapped in firstLineElements (they are normal paragraphs). elements.Add(element); } } } elements.Insert(0, new ContainerElement(ContainerElementStyle.Wrapped, firstLineElements)); var documentationCommentSection = quickInfoItem.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.DocumentationComments); if (documentationCommentSection != null) { var isFirstElement = true; foreach (var element in Helpers.BuildInteractiveTextElements(documentationCommentSection.TaggedParts, context)) { if (isFirstElement) { isFirstElement = false; // Stack the first paragraph of the documentation comments with the last line of the description // to avoid vertical padding between the two. var lastElement = elements[elements.Count - 1]; elements[elements.Count - 1] = new ContainerElement( ContainerElementStyle.Stacked, lastElement, element); } else { elements.Add(element); } } } // Add the remaining sections as Stacked style elements.AddRange( quickInfoItem.Sections.Where(s => s.Kind != QuickInfoSectionKinds.Description && s.Kind != QuickInfoSectionKinds.DocumentationComments) .SelectMany(s => Helpers.BuildInteractiveTextElements(s.TaggedParts, context))); // build text for RelatedSpan if (quickInfoItem.RelatedSpans.Any() && context?.Document is Document document) { var classifiedSpanList = new List<ClassifiedSpan>(); foreach (var span in quickInfoItem.RelatedSpans) { var classifiedSpans = await ClassifierHelper.GetClassifiedSpansAsync(document, span, cancellationToken).ConfigureAwait(false); classifiedSpanList.AddRange(classifiedSpans); } var tabSize = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.TabSize, document.Project.Language); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var spans = IndentationHelper.GetSpansWithAlignedIndentation(text, classifiedSpanList.ToImmutableArray(), tabSize); var textRuns = spans.Select(s => new ClassifiedTextRun(s.ClassificationType, text.GetSubText(s.TextSpan).ToString(), ClassifiedTextRunStyle.UseClassificationFont)); if (textRuns.Any()) { elements.Add(new ClassifiedTextElement(textRuns)); } } return new ContainerElement( ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } internal static async Task<IntellisenseQuickInfoItem> BuildItemAsync( ITrackingSpan trackingSpan, CodeAnalysisQuickInfoItem quickInfoItem, Document document, IThreadingContext threadingContext, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, CancellationToken cancellationToken) { var context = new IntellisenseQuickInfoBuilderContext(document, threadingContext, streamingPresenter); var content = await BuildInteractiveContentAsync(quickInfoItem, context, cancellationToken).ConfigureAwait(false); return new IntellisenseQuickInfoItem(trackingSpan, content); } /// <summary> /// Builds the classified hover content without navigation actions and requiring /// an instance of <see cref="IStreamingFindUsagesPresenter"/> /// TODO - This can be removed once LSP supports colorization in markupcontent /// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/918138 /// </summary> internal static Task<ContainerElement> BuildContentWithoutNavigationActionsAsync( CodeAnalysisQuickInfoItem quickInfoItem, IntellisenseQuickInfoBuilderContext? context, CancellationToken cancellationToken) { return BuildInteractiveContentAsync(quickInfoItem, context, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using CodeAnalysisQuickInfoItem = Microsoft.CodeAnalysis.QuickInfo.QuickInfoItem; using IntellisenseQuickInfoItem = Microsoft.VisualStudio.Language.Intellisense.QuickInfoItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo { internal static class IntellisenseQuickInfoBuilder { private static async Task<ContainerElement> BuildInteractiveContentAsync(CodeAnalysisQuickInfoItem quickInfoItem, IntellisenseQuickInfoBuilderContext? context, CancellationToken cancellationToken) { // Build the first line of QuickInfo item, the images and the Description section should be on the first line with Wrapped style var glyphs = quickInfoItem.Tags.GetGlyphs(); var symbolGlyph = glyphs.FirstOrDefault(g => g != Glyph.CompletionWarning); var warningGlyph = glyphs.FirstOrDefault(g => g == Glyph.CompletionWarning); var firstLineElements = new List<object>(); if (symbolGlyph != Glyph.None) { firstLineElements.Add(new ImageElement(symbolGlyph.GetImageId())); } if (warningGlyph != Glyph.None) { firstLineElements.Add(new ImageElement(warningGlyph.GetImageId())); } var elements = new List<object>(); var descSection = quickInfoItem.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.Description); if (descSection != null) { var isFirstElement = true; foreach (var element in Helpers.BuildInteractiveTextElements(descSection.TaggedParts, context)) { if (isFirstElement) { isFirstElement = false; firstLineElements.Add(element); } else { // If the description section contains multiple paragraphs, the second and additional paragraphs // are not wrapped in firstLineElements (they are normal paragraphs). elements.Add(element); } } } elements.Insert(0, new ContainerElement(ContainerElementStyle.Wrapped, firstLineElements)); var documentationCommentSection = quickInfoItem.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.DocumentationComments); if (documentationCommentSection != null) { var isFirstElement = true; foreach (var element in Helpers.BuildInteractiveTextElements(documentationCommentSection.TaggedParts, context)) { if (isFirstElement) { isFirstElement = false; // Stack the first paragraph of the documentation comments with the last line of the description // to avoid vertical padding between the two. var lastElement = elements[elements.Count - 1]; elements[elements.Count - 1] = new ContainerElement( ContainerElementStyle.Stacked, lastElement, element); } else { elements.Add(element); } } } // Add the remaining sections as Stacked style elements.AddRange( quickInfoItem.Sections.Where(s => s.Kind != QuickInfoSectionKinds.Description && s.Kind != QuickInfoSectionKinds.DocumentationComments) .SelectMany(s => Helpers.BuildInteractiveTextElements(s.TaggedParts, context))); // build text for RelatedSpan if (quickInfoItem.RelatedSpans.Any() && context?.Document is Document document) { var classifiedSpanList = new List<ClassifiedSpan>(); foreach (var span in quickInfoItem.RelatedSpans) { var classifiedSpans = await ClassifierHelper.GetClassifiedSpansAsync(document, span, cancellationToken).ConfigureAwait(false); classifiedSpanList.AddRange(classifiedSpans); } var tabSize = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.TabSize, document.Project.Language); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var spans = IndentationHelper.GetSpansWithAlignedIndentation(text, classifiedSpanList.ToImmutableArray(), tabSize); var textRuns = spans.Select(s => new ClassifiedTextRun(s.ClassificationType, text.GetSubText(s.TextSpan).ToString(), ClassifiedTextRunStyle.UseClassificationFont)); if (textRuns.Any()) { elements.Add(new ClassifiedTextElement(textRuns)); } } return new ContainerElement( ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } internal static async Task<IntellisenseQuickInfoItem> BuildItemAsync( ITrackingSpan trackingSpan, CodeAnalysisQuickInfoItem quickInfoItem, Document document, IThreadingContext threadingContext, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, CancellationToken cancellationToken) { var context = new IntellisenseQuickInfoBuilderContext(document, threadingContext, streamingPresenter); var content = await BuildInteractiveContentAsync(quickInfoItem, context, cancellationToken).ConfigureAwait(false); return new IntellisenseQuickInfoItem(trackingSpan, content); } /// <summary> /// Builds the classified hover content without navigation actions and requiring /// an instance of <see cref="IStreamingFindUsagesPresenter"/> /// TODO - This can be removed once LSP supports colorization in markupcontent /// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/918138 /// </summary> internal static Task<ContainerElement> BuildContentWithoutNavigationActionsAsync( CodeAnalysisQuickInfoItem quickInfoItem, IntellisenseQuickInfoBuilderContext? context, CancellationToken cancellationToken) { return BuildInteractiveContentAsync(quickInfoItem, context, cancellationToken); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./eng/common/cross/arm/sources.list.jessie
# Debian (sid) # UNSTABLE deb http://ftp.debian.org/debian/ sid main contrib non-free deb-src http://ftp.debian.org/debian/ sid main contrib non-free
# Debian (sid) # UNSTABLE deb http://ftp.debian.org/debian/ sid main contrib non-free deb-src http://ftp.debian.org/debian/ sid main contrib non-free
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/VisualBasic/Portable/Completion/CompletionProviders/NamedParameterCompletionProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.ErrorReporting Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(NamedParameterCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(EnumCompletionProvider))> <[Shared]> Partial Friend Class NamedParameterCompletionProvider Inherits LSPCompletionProvider Friend Const s_colonEquals As String = ":=" <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return CompletionUtilities.IsDefaultTriggerCharacter(text, characterPosition, options) End Function Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.CommonTriggerChars Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task Try Dim document = context.Document Dim position = context.Position Dim cancellationToken = context.CancellationToken Dim syntaxTree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False) If syntaxTree.IsInNonUserCode(position, cancellationToken) OrElse syntaxTree.IsInSkippedText(position, cancellationToken) Then Return End If Dim token = syntaxTree.GetTargetToken(position, cancellationToken) If Not token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) Then Return End If Dim argumentList = TryCast(token.Parent, ArgumentListSyntax) If argumentList Is Nothing Then Return End If If token.Kind = SyntaxKind.CommaToken Then ' Consider refining this logic to mandate completion with an argument name, if preceded by an out-of-position name ' See https://github.com/dotnet/roslyn/issues/20657 Dim languageVersion = DirectCast(document.Project.ParseOptions, VisualBasicParseOptions).LanguageVersion If languageVersion < LanguageVersion.VisualBasic15_5 AndAlso token.IsMandatoryNamedParameterPosition() Then context.IsExclusive = True End If End If Dim semanticModel = Await document.ReuseExistingSpeculativeModelAsync(argumentList, cancellationToken).ConfigureAwait(False) Dim parameterLists = GetParameterLists(semanticModel, position, argumentList.Parent, cancellationToken) If parameterLists Is Nothing Then Return End If Dim existingNamedParameters = GetExistingNamedParameters(argumentList, position) parameterLists = parameterLists.Where(Function(p) IsValid(p, existingNamedParameters)) Dim unspecifiedParameters = parameterLists.SelectMany(Function(pl) pl). Where(Function(p) Not existingNamedParameters.Contains(p.Name)) Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False) For Each parameter In unspecifiedParameters context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText:=parameter.Name, displayTextSuffix:=s_colonEquals, insertionText:=parameter.Name.ToIdentifierToken().ToString() & s_colonEquals, symbols:=ImmutableArray.Create(parameter), contextPosition:=position, rules:=s_itemRules)) Next Catch e As Exception When FatalError.ReportAndCatchUnlessCanceled(e) ' nop End Try End Function ' Typing : or = should not filter the list, but they should commit the list. Private Shared ReadOnly s_itemRules As CompletionItemRules = CompletionItemRules.Default. WithFilterCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ":"c, "="c)). WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, ":"c, "="c)) Protected Overrides Function GetDescriptionWorkerAsync(document As Document, item As CompletionItem, cancellationToken As CancellationToken) As Task(Of CompletionDescription) Return SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken) End Function Private Shared Function IsValid(parameterList As ImmutableArray(Of ISymbol), existingNamedParameters As ISet(Of String)) As Boolean ' A parameter list is valid if it has parameters that match in name all the existing ; ' named parameters that have been provided. Return existingNamedParameters.Except(parameterList.Select(Function(p) p.Name)).IsEmpty() End Function Private Shared Function GetExistingNamedParameters(argumentList As ArgumentListSyntax, position As Integer) As ISet(Of String) Dim existingArguments = argumentList.Arguments.OfType(Of SimpleArgumentSyntax). Where(Function(n) n.IsNamed AndAlso Not n.NameColonEquals.ColonEqualsToken.IsMissing AndAlso n.NameColonEquals.Span.End <= position). Select(Function(a) a.NameColonEquals.Name.Identifier.ValueText). Where(Function(i) Not String.IsNullOrWhiteSpace(i)) Return existingArguments.ToSet() End Function Private Shared Function GetParameterLists(semanticModel As SemanticModel, position As Integer, invocableNode As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Return invocableNode.TypeSwitch( Function(attribute As AttributeSyntax) GetAttributeParameterLists(semanticModel, position, attribute, cancellationToken), Function(invocationExpression As InvocationExpressionSyntax) GetInvocationExpressionParameterLists(semanticModel, position, invocationExpression, cancellationToken), Function(objectCreationExpression As ObjectCreationExpressionSyntax) GetObjectCreationExpressionParameterLists(semanticModel, position, objectCreationExpression, cancellationToken)) End Function Private Shared Function GetObjectCreationExpressionParameterLists(semanticModel As SemanticModel, position As Integer, objectCreationExpression As ObjectCreationExpressionSyntax, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Dim type = TryCast(semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type, INamedTypeSymbol) Dim within = semanticModel.GetEnclosingNamedType(position, cancellationToken) If type IsNot Nothing AndAlso within IsNot Nothing AndAlso type.TypeKind <> TypeKind.[Delegate] Then Return type.InstanceConstructors.Where(Function(c) c.IsAccessibleWithin(within)). Select(Function(c) c.Parameters.As(Of ISymbol)()) End If Return Nothing End Function Private Shared Function GetAttributeParameterLists(semanticModel As SemanticModel, position As Integer, attribute As AttributeSyntax, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Dim within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken) Dim attributeType = TryCast(semanticModel.GetTypeInfo(attribute, cancellationToken).Type, INamedTypeSymbol) Dim namedParameters = attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within) Return SpecializedCollections.SingletonEnumerable( ImmutableArray.CreateRange(namedParameters)) End Function Private Shared Function GetInvocationExpressionParameterLists(semanticModel As SemanticModel, position As Integer, invocationExpression As InvocationExpressionSyntax, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Dim within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken) Dim expression = invocationExpression.GetExpression() If within IsNot Nothing AndAlso expression IsNot Nothing Then Dim memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken) Dim expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type Dim indexers = If(expressionType Is Nothing, SpecializedCollections.EmptyList(Of IPropertySymbol), semanticModel.LookupSymbols(position, expressionType, includeReducedExtensionMethods:=True).OfType(Of IPropertySymbol).Where(Function(p) p.IsIndexer).ToList()) If memberGroup.Length > 0 Then Dim accessibleMembers = memberGroup.Where(Function(m) m.IsAccessibleWithin(within)) Dim methodParameters = accessibleMembers.OfType(Of IMethodSymbol).Select(Function(m) m.Parameters.As(Of ISymbol)()) Dim propertyParameters = accessibleMembers.OfType(Of IPropertySymbol).Select(Function(p) p.Parameters.As(Of ISymbol)()) Return methodParameters.Concat(propertyParameters) ElseIf expressionType.IsDelegateType() Then Dim delegateType = DirectCast(expressionType, INamedTypeSymbol) Return SpecializedCollections.SingletonEnumerable(delegateType.DelegateInvokeMethod.Parameters.As(Of ISymbol)()) ElseIf indexers.Count > 0 Then Return indexers.Where(Function(i) i.IsAccessibleWithin(within, throughType:=expressionType)). Select(Function(i) i.Parameters.As(Of ISymbol)()) End If End If Return Nothing End Function Private Shared Sub GetInvocableNode(token As SyntaxToken, ByRef invocableNode As SyntaxNode, ByRef argumentList As ArgumentListSyntax) Dim current = token.Parent While current IsNot Nothing If TypeOf current Is AttributeSyntax Then invocableNode = current argumentList = (DirectCast(current, AttributeSyntax)).ArgumentList Return End If If TypeOf current Is InvocationExpressionSyntax Then invocableNode = current argumentList = (DirectCast(current, InvocationExpressionSyntax)).ArgumentList Return End If If TypeOf current Is ObjectCreationExpressionSyntax Then invocableNode = current argumentList = (DirectCast(current, ObjectCreationExpressionSyntax)).ArgumentList Return End If If TypeOf current Is TypeArgumentListSyntax Then Exit While End If current = current.Parent End While invocableNode = Nothing argumentList = Nothing End Sub Protected Overrides Function GetTextChangeAsync(selectedItem As CompletionItem, ch As Char?, cancellationToken As CancellationToken) As Task(Of TextChange?) Dim symbolItem = selectedItem Dim insertionText = SymbolCompletionItem.GetInsertionText(selectedItem) Dim change As TextChange If ch.HasValue AndAlso ch.Value = ":"c Then change = New TextChange(symbolItem.Span, insertionText.Substring(0, insertionText.Length - s_colonEquals.Length)) ElseIf ch.HasValue AndAlso ch.Value = "="c Then change = New TextChange(selectedItem.Span, insertionText.Substring(0, insertionText.Length - (s_colonEquals.Length - 1))) Else change = New TextChange(symbolItem.Span, insertionText) End If Return Task.FromResult(Of TextChange?)(change) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.ErrorReporting Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(NamedParameterCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(EnumCompletionProvider))> <[Shared]> Partial Friend Class NamedParameterCompletionProvider Inherits LSPCompletionProvider Friend Const s_colonEquals As String = ":=" <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return CompletionUtilities.IsDefaultTriggerCharacter(text, characterPosition, options) End Function Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.CommonTriggerChars Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task Try Dim document = context.Document Dim position = context.Position Dim cancellationToken = context.CancellationToken Dim syntaxTree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False) If syntaxTree.IsInNonUserCode(position, cancellationToken) OrElse syntaxTree.IsInSkippedText(position, cancellationToken) Then Return End If Dim token = syntaxTree.GetTargetToken(position, cancellationToken) If Not token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) Then Return End If Dim argumentList = TryCast(token.Parent, ArgumentListSyntax) If argumentList Is Nothing Then Return End If If token.Kind = SyntaxKind.CommaToken Then ' Consider refining this logic to mandate completion with an argument name, if preceded by an out-of-position name ' See https://github.com/dotnet/roslyn/issues/20657 Dim languageVersion = DirectCast(document.Project.ParseOptions, VisualBasicParseOptions).LanguageVersion If languageVersion < LanguageVersion.VisualBasic15_5 AndAlso token.IsMandatoryNamedParameterPosition() Then context.IsExclusive = True End If End If Dim semanticModel = Await document.ReuseExistingSpeculativeModelAsync(argumentList, cancellationToken).ConfigureAwait(False) Dim parameterLists = GetParameterLists(semanticModel, position, argumentList.Parent, cancellationToken) If parameterLists Is Nothing Then Return End If Dim existingNamedParameters = GetExistingNamedParameters(argumentList, position) parameterLists = parameterLists.Where(Function(p) IsValid(p, existingNamedParameters)) Dim unspecifiedParameters = parameterLists.SelectMany(Function(pl) pl). Where(Function(p) Not existingNamedParameters.Contains(p.Name)) Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False) For Each parameter In unspecifiedParameters context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText:=parameter.Name, displayTextSuffix:=s_colonEquals, insertionText:=parameter.Name.ToIdentifierToken().ToString() & s_colonEquals, symbols:=ImmutableArray.Create(parameter), contextPosition:=position, rules:=s_itemRules)) Next Catch e As Exception When FatalError.ReportAndCatchUnlessCanceled(e) ' nop End Try End Function ' Typing : or = should not filter the list, but they should commit the list. Private Shared ReadOnly s_itemRules As CompletionItemRules = CompletionItemRules.Default. WithFilterCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ":"c, "="c)). WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, ":"c, "="c)) Protected Overrides Function GetDescriptionWorkerAsync(document As Document, item As CompletionItem, cancellationToken As CancellationToken) As Task(Of CompletionDescription) Return SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken) End Function Private Shared Function IsValid(parameterList As ImmutableArray(Of ISymbol), existingNamedParameters As ISet(Of String)) As Boolean ' A parameter list is valid if it has parameters that match in name all the existing ; ' named parameters that have been provided. Return existingNamedParameters.Except(parameterList.Select(Function(p) p.Name)).IsEmpty() End Function Private Shared Function GetExistingNamedParameters(argumentList As ArgumentListSyntax, position As Integer) As ISet(Of String) Dim existingArguments = argumentList.Arguments.OfType(Of SimpleArgumentSyntax). Where(Function(n) n.IsNamed AndAlso Not n.NameColonEquals.ColonEqualsToken.IsMissing AndAlso n.NameColonEquals.Span.End <= position). Select(Function(a) a.NameColonEquals.Name.Identifier.ValueText). Where(Function(i) Not String.IsNullOrWhiteSpace(i)) Return existingArguments.ToSet() End Function Private Shared Function GetParameterLists(semanticModel As SemanticModel, position As Integer, invocableNode As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Return invocableNode.TypeSwitch( Function(attribute As AttributeSyntax) GetAttributeParameterLists(semanticModel, position, attribute, cancellationToken), Function(invocationExpression As InvocationExpressionSyntax) GetInvocationExpressionParameterLists(semanticModel, position, invocationExpression, cancellationToken), Function(objectCreationExpression As ObjectCreationExpressionSyntax) GetObjectCreationExpressionParameterLists(semanticModel, position, objectCreationExpression, cancellationToken)) End Function Private Shared Function GetObjectCreationExpressionParameterLists(semanticModel As SemanticModel, position As Integer, objectCreationExpression As ObjectCreationExpressionSyntax, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Dim type = TryCast(semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type, INamedTypeSymbol) Dim within = semanticModel.GetEnclosingNamedType(position, cancellationToken) If type IsNot Nothing AndAlso within IsNot Nothing AndAlso type.TypeKind <> TypeKind.[Delegate] Then Return type.InstanceConstructors.Where(Function(c) c.IsAccessibleWithin(within)). Select(Function(c) c.Parameters.As(Of ISymbol)()) End If Return Nothing End Function Private Shared Function GetAttributeParameterLists(semanticModel As SemanticModel, position As Integer, attribute As AttributeSyntax, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Dim within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken) Dim attributeType = TryCast(semanticModel.GetTypeInfo(attribute, cancellationToken).Type, INamedTypeSymbol) Dim namedParameters = attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within) Return SpecializedCollections.SingletonEnumerable( ImmutableArray.CreateRange(namedParameters)) End Function Private Shared Function GetInvocationExpressionParameterLists(semanticModel As SemanticModel, position As Integer, invocationExpression As InvocationExpressionSyntax, cancellationToken As CancellationToken) As IEnumerable(Of ImmutableArray(Of ISymbol)) Dim within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken) Dim expression = invocationExpression.GetExpression() If within IsNot Nothing AndAlso expression IsNot Nothing Then Dim memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken) Dim expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type Dim indexers = If(expressionType Is Nothing, SpecializedCollections.EmptyList(Of IPropertySymbol), semanticModel.LookupSymbols(position, expressionType, includeReducedExtensionMethods:=True).OfType(Of IPropertySymbol).Where(Function(p) p.IsIndexer).ToList()) If memberGroup.Length > 0 Then Dim accessibleMembers = memberGroup.Where(Function(m) m.IsAccessibleWithin(within)) Dim methodParameters = accessibleMembers.OfType(Of IMethodSymbol).Select(Function(m) m.Parameters.As(Of ISymbol)()) Dim propertyParameters = accessibleMembers.OfType(Of IPropertySymbol).Select(Function(p) p.Parameters.As(Of ISymbol)()) Return methodParameters.Concat(propertyParameters) ElseIf expressionType.IsDelegateType() Then Dim delegateType = DirectCast(expressionType, INamedTypeSymbol) Return SpecializedCollections.SingletonEnumerable(delegateType.DelegateInvokeMethod.Parameters.As(Of ISymbol)()) ElseIf indexers.Count > 0 Then Return indexers.Where(Function(i) i.IsAccessibleWithin(within, throughType:=expressionType)). Select(Function(i) i.Parameters.As(Of ISymbol)()) End If End If Return Nothing End Function Private Shared Sub GetInvocableNode(token As SyntaxToken, ByRef invocableNode As SyntaxNode, ByRef argumentList As ArgumentListSyntax) Dim current = token.Parent While current IsNot Nothing If TypeOf current Is AttributeSyntax Then invocableNode = current argumentList = (DirectCast(current, AttributeSyntax)).ArgumentList Return End If If TypeOf current Is InvocationExpressionSyntax Then invocableNode = current argumentList = (DirectCast(current, InvocationExpressionSyntax)).ArgumentList Return End If If TypeOf current Is ObjectCreationExpressionSyntax Then invocableNode = current argumentList = (DirectCast(current, ObjectCreationExpressionSyntax)).ArgumentList Return End If If TypeOf current Is TypeArgumentListSyntax Then Exit While End If current = current.Parent End While invocableNode = Nothing argumentList = Nothing End Sub Protected Overrides Function GetTextChangeAsync(selectedItem As CompletionItem, ch As Char?, cancellationToken As CancellationToken) As Task(Of TextChange?) Dim symbolItem = selectedItem Dim insertionText = SymbolCompletionItem.GetInsertionText(selectedItem) Dim change As TextChange If ch.HasValue AndAlso ch.Value = ":"c Then change = New TextChange(symbolItem.Span, insertionText.Substring(0, insertionText.Length - s_colonEquals.Length)) ElseIf ch.HasValue AndAlso ch.Value = "="c Then change = New TextChange(selectedItem.Span, insertionText.Substring(0, insertionText.Length - (s_colonEquals.Length - 1))) Else change = New TextChange(symbolItem.Span, insertionText) End If Return Task.FromResult(Of TextChange?)(change) End Function End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/VisualBasicTest/Structure/SyncLockBlockStructureTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class SyncLockBlockStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of SyncLockBlockSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New SyncLockBlockStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestSyncLockBlock1() As Task Const code = " Class C Sub M() {|span:SyncLock x $$ End SyncLock|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "SyncLock x ...", autoCollapse:=False)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class SyncLockBlockStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of SyncLockBlockSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New SyncLockBlockStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestSyncLockBlock1() As Task Const code = " Class C Sub M() {|span:SyncLock x $$ End SyncLock|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "SyncLock x ...", autoCollapse:=False)) End Function End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.ru.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ru" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Диагностика Roslyn</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ru" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Диагностика Roslyn</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/ManageNamingStylesInfoDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { /// <summary> /// Interaction logic for NamingStyleDialog.xaml /// </summary> internal partial class ManageNamingStylesInfoDialog : DialogWindow { private readonly IManageNamingStylesInfoDialogViewModel _viewModel; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string CannotBeDeletedExplanation => ServicesVSResources.This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule; public string AddItemAutomationText => ServicesVSResources.Add_item; public string EditButtonAutomationText => ServicesVSResources.Edit_item; public string RemoveButtonAutomationText => ServicesVSResources.Remove_item; internal ManageNamingStylesInfoDialog(IManageNamingStylesInfoDialogViewModel viewModel) { _viewModel = viewModel; InitializeComponent(); DataContext = viewModel; } private void AddButton_Click(object sender, RoutedEventArgs e) => _viewModel.AddItem(); private void RemoveButton_Click(object sender, RoutedEventArgs e) { var button = (Button)sender; var item = button.DataContext as INamingStylesInfoDialogViewModel; _viewModel.RemoveItem(item); } private void EditButton_Click(object sender, RoutedEventArgs e) { var button = (Button)sender; var item = button.DataContext as INamingStylesInfoDialogViewModel; _viewModel.EditItem(item); } private void OK_Click(object sender, RoutedEventArgs e) => DialogResult = true; private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { /// <summary> /// Interaction logic for NamingStyleDialog.xaml /// </summary> internal partial class ManageNamingStylesInfoDialog : DialogWindow { private readonly IManageNamingStylesInfoDialogViewModel _viewModel; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; public string CannotBeDeletedExplanation => ServicesVSResources.This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule; public string AddItemAutomationText => ServicesVSResources.Add_item; public string EditButtonAutomationText => ServicesVSResources.Edit_item; public string RemoveButtonAutomationText => ServicesVSResources.Remove_item; internal ManageNamingStylesInfoDialog(IManageNamingStylesInfoDialogViewModel viewModel) { _viewModel = viewModel; InitializeComponent(); DataContext = viewModel; } private void AddButton_Click(object sender, RoutedEventArgs e) => _viewModel.AddItem(); private void RemoveButton_Click(object sender, RoutedEventArgs e) { var button = (Button)sender; var item = button.DataContext as INamingStylesInfoDialogViewModel; _viewModel.RemoveItem(item); } private void EditButton_Click(object sender, RoutedEventArgs e) { var button = (Button)sender; var item = button.DataContext as INamingStylesInfoDialogViewModel; _viewModel.EditItem(item); } private void OK_Click(object sender, RoutedEventArgs e) => DialogResult = true; private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.StateSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// this contains all states regarding a <see cref="DiagnosticAnalyzer"/> /// </summary> private sealed class StateSet { public readonly string Language; public readonly DiagnosticAnalyzer Analyzer; public readonly string ErrorSourceName; private readonly PersistentNames _persistentNames; private readonly ConcurrentDictionary<DocumentId, ActiveFileState> _activeFileStates; private readonly ConcurrentDictionary<ProjectId, ProjectState> _projectStates; public StateSet(string language, DiagnosticAnalyzer analyzer, string errorSourceName) { Language = language; Analyzer = analyzer; ErrorSourceName = errorSourceName; _persistentNames = PersistentNames.Create(Analyzer); _activeFileStates = new ConcurrentDictionary<DocumentId, ActiveFileState>(concurrencyLevel: 2, capacity: 10); _projectStates = new ConcurrentDictionary<ProjectId, ProjectState>(concurrencyLevel: 2, capacity: 1); } public string StateName => _persistentNames.StateName; public string SyntaxStateName => _persistentNames.SyntaxStateName; public string SemanticStateName => _persistentNames.SemanticStateName; public string NonLocalStateName => _persistentNames.NonLocalStateName; [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/34761", AllowCaptures = false, AllowGenericEnumeration = false)] public bool ContainsAnyDocumentOrProjectDiagnostics(ProjectId projectId) { foreach (var (documentId, state) in _activeFileStates) { if (documentId.ProjectId == projectId && !state.IsEmpty) { return true; } } return _projectStates.TryGetValue(projectId, out var projectState) && !projectState.IsEmpty(); } public IEnumerable<ProjectId> GetProjectsWithDiagnostics() { // quick bail out if (_activeFileStates.IsEmpty && _projectStates.IsEmpty) { return SpecializedCollections.EmptyEnumerable<ProjectId>(); } if (_activeFileStates.Count == 1 && _projectStates.IsEmpty) { // see whether we actually have diagnostics var (documentId, state) = _activeFileStates.First(); if (state.IsEmpty) { return SpecializedCollections.EmptyEnumerable<ProjectId>(); } // we do have diagnostics return SpecializedCollections.SingletonEnumerable(documentId.ProjectId); } return new HashSet<ProjectId>( _activeFileStates.Where(kv => !kv.Value.IsEmpty) .Select(kv => kv.Key.ProjectId) .Concat(_projectStates.Where(kv => !kv.Value.IsEmpty()) .Select(kv => kv.Key))); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/34761", AllowCaptures = false, AllowGenericEnumeration = false)] public void CollectDocumentsWithDiagnostics(ProjectId projectId, HashSet<DocumentId> set) { RoslynDebug.Assert(set != null); // Collect active documents with diagnostics foreach (var (documentId, state) in _activeFileStates) { if (documentId.ProjectId == projectId && !state.IsEmpty) { set.Add(documentId); } } if (_projectStates.TryGetValue(projectId, out var projectState) && !projectState.IsEmpty()) { set.UnionWith(projectState.GetDocumentsWithDiagnostics()); } } public bool IsActiveFile(DocumentId documentId) => _activeFileStates.ContainsKey(documentId); public bool FromBuild(ProjectId projectId) => _projectStates.TryGetValue(projectId, out var projectState) && projectState.FromBuild; public bool TryGetActiveFileState(DocumentId documentId, [NotNullWhen(true)] out ActiveFileState? state) => _activeFileStates.TryGetValue(documentId, out state); public bool TryGetProjectState(ProjectId projectId, [NotNullWhen(true)] out ProjectState? state) => _projectStates.TryGetValue(projectId, out state); public ActiveFileState GetOrCreateActiveFileState(DocumentId documentId) => _activeFileStates.GetOrAdd(documentId, id => new ActiveFileState(id)); public ProjectState GetOrCreateProjectState(ProjectId projectId) => _projectStates.GetOrAdd(projectId, id => new ProjectState(this, id)); public async Task<bool> OnDocumentOpenedAsync(TextDocument document) { // can not be cancelled if (!TryGetProjectState(document.Project.Id, out var projectState) || projectState.IsEmpty(document.Id)) { // nothing to do return false; } var result = await projectState.GetAnalysisDataAsync(document, avoidLoadingData: false, CancellationToken.None).ConfigureAwait(false); // store analysis result to active file state: var activeFileState = GetOrCreateActiveFileState(document.Id); activeFileState.Save(AnalysisKind.Syntax, new DocumentAnalysisData(result.Version, result.GetDocumentDiagnostics(document.Id, AnalysisKind.Syntax))); activeFileState.Save(AnalysisKind.Semantic, new DocumentAnalysisData(result.Version, result.GetDocumentDiagnostics(document.Id, AnalysisKind.Semantic))); return true; } public async Task<bool> OnDocumentClosedAsync(TextDocument document) { // can not be cancelled // remove active file state and put it in project state if (!_activeFileStates.TryRemove(document.Id, out var activeFileState)) { return false; } // active file exist, put it in the project state var projectState = GetOrCreateProjectState(document.Project.Id); await projectState.MergeAsync(activeFileState, document).ConfigureAwait(false); return true; } public bool OnDocumentReset(TextDocument document) { var changed = false; // can not be cancelled // remove active file state and put it in project state if (TryGetActiveFileState(document.Id, out var activeFileState)) { activeFileState.ResetVersion(); changed |= true; } if (TryGetProjectState(document.Project.Id, out var projectState)) { projectState.ResetVersion(); changed |= true; } return changed; } public bool OnDocumentRemoved(DocumentId id) { // remove active file state for removed document var removed = false; if (_activeFileStates.TryRemove(id, out _)) { removed = true; } // remove state for the file that got removed. if (_projectStates.TryGetValue(id.ProjectId, out var state)) { removed |= state.OnDocumentRemoved(id); } return removed; } public bool OnProjectRemoved(ProjectId id) { // remove state for project that got removed. if (_projectStates.TryRemove(id, out var state)) { return state.OnProjectRemoved(id); } return false; } public void OnRemoved() { // ths stateset is being removed. // TODO: we do this since InMemoryCache is static type. we might consider making it instance object // of something. InMemoryStorage.DropCache(Analyzer); } private sealed class PersistentNames { private const string UserDiagnosticsPrefixTableName = "<UserDiagnostics2>"; private static readonly ConcurrentDictionary<string, PersistentNames> s_analyzerStateNameCache = new(concurrencyLevel: 2, capacity: 10); private PersistentNames(string assemblyQualifiedName) { StateName = UserDiagnosticsPrefixTableName + "_" + assemblyQualifiedName; SyntaxStateName = StateName + ".Syntax"; SemanticStateName = StateName + ".Semantic"; NonLocalStateName = StateName + ".NonLocal"; } /// <summary> /// Get the unique state name for the given analyzer. /// Note that this name is used by the underlying persistence stream of the corresponding <see cref="ProjectState"/> to Read/Write diagnostic data into the stream. /// If any two distinct analyzer have the same diagnostic state name, we will end up sharing the persistence stream between them, leading to duplicate/missing/incorrect diagnostic data. /// </summary> public string StateName { get; } public string SyntaxStateName { get; } public string SemanticStateName { get; } public string NonLocalStateName { get; } public static PersistentNames Create(DiagnosticAnalyzer diagnosticAnalyzer) => s_analyzerStateNameCache.GetOrAdd(diagnosticAnalyzer.GetAnalyzerId(), t => new PersistentNames(t)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// this contains all states regarding a <see cref="DiagnosticAnalyzer"/> /// </summary> private sealed class StateSet { public readonly string Language; public readonly DiagnosticAnalyzer Analyzer; public readonly string ErrorSourceName; private readonly PersistentNames _persistentNames; private readonly ConcurrentDictionary<DocumentId, ActiveFileState> _activeFileStates; private readonly ConcurrentDictionary<ProjectId, ProjectState> _projectStates; public StateSet(string language, DiagnosticAnalyzer analyzer, string errorSourceName) { Language = language; Analyzer = analyzer; ErrorSourceName = errorSourceName; _persistentNames = PersistentNames.Create(Analyzer); _activeFileStates = new ConcurrentDictionary<DocumentId, ActiveFileState>(concurrencyLevel: 2, capacity: 10); _projectStates = new ConcurrentDictionary<ProjectId, ProjectState>(concurrencyLevel: 2, capacity: 1); } public string StateName => _persistentNames.StateName; public string SyntaxStateName => _persistentNames.SyntaxStateName; public string SemanticStateName => _persistentNames.SemanticStateName; public string NonLocalStateName => _persistentNames.NonLocalStateName; [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/34761", AllowCaptures = false, AllowGenericEnumeration = false)] public bool ContainsAnyDocumentOrProjectDiagnostics(ProjectId projectId) { foreach (var (documentId, state) in _activeFileStates) { if (documentId.ProjectId == projectId && !state.IsEmpty) { return true; } } return _projectStates.TryGetValue(projectId, out var projectState) && !projectState.IsEmpty(); } public IEnumerable<ProjectId> GetProjectsWithDiagnostics() { // quick bail out if (_activeFileStates.IsEmpty && _projectStates.IsEmpty) { return SpecializedCollections.EmptyEnumerable<ProjectId>(); } if (_activeFileStates.Count == 1 && _projectStates.IsEmpty) { // see whether we actually have diagnostics var (documentId, state) = _activeFileStates.First(); if (state.IsEmpty) { return SpecializedCollections.EmptyEnumerable<ProjectId>(); } // we do have diagnostics return SpecializedCollections.SingletonEnumerable(documentId.ProjectId); } return new HashSet<ProjectId>( _activeFileStates.Where(kv => !kv.Value.IsEmpty) .Select(kv => kv.Key.ProjectId) .Concat(_projectStates.Where(kv => !kv.Value.IsEmpty()) .Select(kv => kv.Key))); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/34761", AllowCaptures = false, AllowGenericEnumeration = false)] public void CollectDocumentsWithDiagnostics(ProjectId projectId, HashSet<DocumentId> set) { RoslynDebug.Assert(set != null); // Collect active documents with diagnostics foreach (var (documentId, state) in _activeFileStates) { if (documentId.ProjectId == projectId && !state.IsEmpty) { set.Add(documentId); } } if (_projectStates.TryGetValue(projectId, out var projectState) && !projectState.IsEmpty()) { set.UnionWith(projectState.GetDocumentsWithDiagnostics()); } } public bool IsActiveFile(DocumentId documentId) => _activeFileStates.ContainsKey(documentId); public bool FromBuild(ProjectId projectId) => _projectStates.TryGetValue(projectId, out var projectState) && projectState.FromBuild; public bool TryGetActiveFileState(DocumentId documentId, [NotNullWhen(true)] out ActiveFileState? state) => _activeFileStates.TryGetValue(documentId, out state); public bool TryGetProjectState(ProjectId projectId, [NotNullWhen(true)] out ProjectState? state) => _projectStates.TryGetValue(projectId, out state); public ActiveFileState GetOrCreateActiveFileState(DocumentId documentId) => _activeFileStates.GetOrAdd(documentId, id => new ActiveFileState(id)); public ProjectState GetOrCreateProjectState(ProjectId projectId) => _projectStates.GetOrAdd(projectId, id => new ProjectState(this, id)); public async Task<bool> OnDocumentOpenedAsync(TextDocument document) { // can not be cancelled if (!TryGetProjectState(document.Project.Id, out var projectState) || projectState.IsEmpty(document.Id)) { // nothing to do return false; } var result = await projectState.GetAnalysisDataAsync(document, avoidLoadingData: false, CancellationToken.None).ConfigureAwait(false); // store analysis result to active file state: var activeFileState = GetOrCreateActiveFileState(document.Id); activeFileState.Save(AnalysisKind.Syntax, new DocumentAnalysisData(result.Version, result.GetDocumentDiagnostics(document.Id, AnalysisKind.Syntax))); activeFileState.Save(AnalysisKind.Semantic, new DocumentAnalysisData(result.Version, result.GetDocumentDiagnostics(document.Id, AnalysisKind.Semantic))); return true; } public async Task<bool> OnDocumentClosedAsync(TextDocument document) { // can not be cancelled // remove active file state and put it in project state if (!_activeFileStates.TryRemove(document.Id, out var activeFileState)) { return false; } // active file exist, put it in the project state var projectState = GetOrCreateProjectState(document.Project.Id); await projectState.MergeAsync(activeFileState, document).ConfigureAwait(false); return true; } public bool OnDocumentReset(TextDocument document) { var changed = false; // can not be cancelled // remove active file state and put it in project state if (TryGetActiveFileState(document.Id, out var activeFileState)) { activeFileState.ResetVersion(); changed |= true; } if (TryGetProjectState(document.Project.Id, out var projectState)) { projectState.ResetVersion(); changed |= true; } return changed; } public bool OnDocumentRemoved(DocumentId id) { // remove active file state for removed document var removed = false; if (_activeFileStates.TryRemove(id, out _)) { removed = true; } // remove state for the file that got removed. if (_projectStates.TryGetValue(id.ProjectId, out var state)) { removed |= state.OnDocumentRemoved(id); } return removed; } public bool OnProjectRemoved(ProjectId id) { // remove state for project that got removed. if (_projectStates.TryRemove(id, out var state)) { return state.OnProjectRemoved(id); } return false; } public void OnRemoved() { // ths stateset is being removed. // TODO: we do this since InMemoryCache is static type. we might consider making it instance object // of something. InMemoryStorage.DropCache(Analyzer); } private sealed class PersistentNames { private const string UserDiagnosticsPrefixTableName = "<UserDiagnostics2>"; private static readonly ConcurrentDictionary<string, PersistentNames> s_analyzerStateNameCache = new(concurrencyLevel: 2, capacity: 10); private PersistentNames(string assemblyQualifiedName) { StateName = UserDiagnosticsPrefixTableName + "_" + assemblyQualifiedName; SyntaxStateName = StateName + ".Syntax"; SemanticStateName = StateName + ".Semantic"; NonLocalStateName = StateName + ".NonLocal"; } /// <summary> /// Get the unique state name for the given analyzer. /// Note that this name is used by the underlying persistence stream of the corresponding <see cref="ProjectState"/> to Read/Write diagnostic data into the stream. /// If any two distinct analyzer have the same diagnostic state name, we will end up sharing the persistence stream between them, leading to duplicate/missing/incorrect diagnostic data. /// </summary> public string StateName { get; } public string SyntaxStateName { get; } public string SemanticStateName { get; } public string NonLocalStateName { get; } public static PersistentNames Create(DiagnosticAnalyzer diagnosticAnalyzer) => s_analyzerStateNameCache.GetOrAdd(diagnosticAnalyzer.GetAnalyzerId(), t => new PersistentNames(t)); } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/Navigation/NavigableItemFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Navigation { internal static partial class NavigableItemFactory { public static INavigableItem GetItemFromSymbolLocation( Solution solution, ISymbol symbol, Location location, ImmutableArray<TaggedText>? displayTaggedParts) { return new SymbolLocationNavigableItem( solution, symbol, location, displayTaggedParts); } public static ImmutableArray<INavigableItem> GetItemsFromPreferredSourceLocations( Solution solution, ISymbol symbol, ImmutableArray<TaggedText>? displayTaggedParts, CancellationToken cancellationToken) { var locations = GetPreferredSourceLocations(solution, symbol, cancellationToken); return locations.SelectAsArray(loc => GetItemFromSymbolLocation( solution, symbol, loc, displayTaggedParts)); } public static IEnumerable<Location> GetPreferredSourceLocations( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { // Prefer non-generated source locations over generated ones. var sourceLocations = GetPreferredSourceLocations(symbol); var candidateLocationGroups = from c in sourceLocations let doc = solution.GetDocument(c.SourceTree) where doc != null group c by doc.IsGeneratedCode(cancellationToken); var generatedSourceLocations = candidateLocationGroups.SingleOrDefault(g => g.Key) ?? SpecializedCollections.EmptyEnumerable<Location>(); var nonGeneratedSourceLocations = candidateLocationGroups.SingleOrDefault(g => !g.Key) ?? SpecializedCollections.EmptyEnumerable<Location>(); return nonGeneratedSourceLocations.Any() ? nonGeneratedSourceLocations : generatedSourceLocations; } private static IEnumerable<Location> GetPreferredSourceLocations(ISymbol symbol) { var locations = symbol.Locations; // First return visible source locations if we have them. Else, go to the non-visible // source locations. var visibleSourceLocations = locations.Where(loc => loc.IsVisibleSourceLocation()); return visibleSourceLocations.Any() ? visibleSourceLocations : locations.Where(loc => loc.IsInSource); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Navigation { internal static partial class NavigableItemFactory { public static INavigableItem GetItemFromSymbolLocation( Solution solution, ISymbol symbol, Location location, ImmutableArray<TaggedText>? displayTaggedParts) { return new SymbolLocationNavigableItem( solution, symbol, location, displayTaggedParts); } public static ImmutableArray<INavigableItem> GetItemsFromPreferredSourceLocations( Solution solution, ISymbol symbol, ImmutableArray<TaggedText>? displayTaggedParts, CancellationToken cancellationToken) { var locations = GetPreferredSourceLocations(solution, symbol, cancellationToken); return locations.SelectAsArray(loc => GetItemFromSymbolLocation( solution, symbol, loc, displayTaggedParts)); } public static IEnumerable<Location> GetPreferredSourceLocations( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { // Prefer non-generated source locations over generated ones. var sourceLocations = GetPreferredSourceLocations(symbol); var candidateLocationGroups = from c in sourceLocations let doc = solution.GetDocument(c.SourceTree) where doc != null group c by doc.IsGeneratedCode(cancellationToken); var generatedSourceLocations = candidateLocationGroups.SingleOrDefault(g => g.Key) ?? SpecializedCollections.EmptyEnumerable<Location>(); var nonGeneratedSourceLocations = candidateLocationGroups.SingleOrDefault(g => !g.Key) ?? SpecializedCollections.EmptyEnumerable<Location>(); return nonGeneratedSourceLocations.Any() ? nonGeneratedSourceLocations : generatedSourceLocations; } private static IEnumerable<Location> GetPreferredSourceLocations(ISymbol symbol) { var locations = symbol.Locations; // First return visible source locations if we have them. Else, go to the non-visible // source locations. var visibleSourceLocations = locations.Where(loc => loc.IsVisibleSourceLocation()); return visibleSourceLocations.Any() ? visibleSourceLocations : locations.Where(loc => loc.IsInSource); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ComVisible(true)] public partial class AutomationObject : AbstractAutomationObject { internal AutomationObject(Workspace workspace) : base(workspace, LanguageNames.CSharp) { } private int GetBooleanOption(Option2<bool> key) => GetOption(key) ? 1 : 0; private int GetBooleanOption(PerLanguageOption2<bool> key) => GetOption(key) ? 1 : 0; private void SetBooleanOption(Option2<bool> key, int value) => SetOption(key, value != 0); private void SetBooleanOption(PerLanguageOption2<bool> key, int value) => SetOption(key, value != 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ComVisible(true)] public partial class AutomationObject : AbstractAutomationObject { internal AutomationObject(Workspace workspace) : base(workspace, LanguageNames.CSharp) { } private int GetBooleanOption(Option2<bool> key) => GetOption(key) ? 1 : 0; private int GetBooleanOption(PerLanguageOption2<bool> key) => GetOption(key) ? 1 : 0; private void SetBooleanOption(Option2<bool> key, int value) => SetOption(key, value != 0); private void SetBooleanOption(PerLanguageOption2<bool> key, int value) => SetOption(key, value != 0); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Portable/Symbols/Source/SourceSimpleParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A source parameter that has no default value, no attributes, /// and is not params. /// </summary> internal sealed class SourceSimpleParameterSymbol : SourceParameterSymbol { public SourceSimpleParameterSymbol( Symbol owner, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, string name, ImmutableArray<Location> locations) : base(owner, parameterType, ordinal, refKind, name, locations) { } public override bool IsDiscard => false; internal override ConstantValue? ExplicitDefaultConstantValue { get { return null; } } internal override bool IsMetadataOptional { get { return false; } } public override bool IsParams { get { return false; } } internal override bool HasDefaultArgumentSyntax { get { return false; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } internal override SyntaxReference? SyntaxReference { get { return null; } } internal override bool IsExtensionMethodThis { get { return false; } } internal override bool IsIDispatchConstant { get { return false; } } internal override bool IsIUnknownConstant { get { return false; } } internal override bool IsCallerFilePath { get { return false; } } internal override bool IsCallerLineNumber { get { return false; } } internal override bool IsCallerMemberName { get { return false; } } internal override int CallerArgumentExpressionParameterIndex { get { return -1; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => false; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return FlowAnalysisAnnotations.None; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; internal override MarshalPseudoCustomAttributeData? MarshallingInformation { get { return null; } } internal override bool HasOptionalAttribute { get { return false; } } internal override SyntaxList<AttributeListSyntax> AttributeDeclarationList { get { return default(SyntaxList<AttributeListSyntax>); } } internal override CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { state.NotePartComplete(CompletionPart.Attributes); return CustomAttributesBag<CSharpAttributeData>.Empty; } internal override ConstantValue DefaultValueFromAttributes { get { return ConstantValue.NotAvailable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A source parameter that has no default value, no attributes, /// and is not params. /// </summary> internal sealed class SourceSimpleParameterSymbol : SourceParameterSymbol { public SourceSimpleParameterSymbol( Symbol owner, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, string name, ImmutableArray<Location> locations) : base(owner, parameterType, ordinal, refKind, name, locations) { } public override bool IsDiscard => false; internal override ConstantValue? ExplicitDefaultConstantValue { get { return null; } } internal override bool IsMetadataOptional { get { return false; } } public override bool IsParams { get { return false; } } internal override bool HasDefaultArgumentSyntax { get { return false; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } internal override SyntaxReference? SyntaxReference { get { return null; } } internal override bool IsExtensionMethodThis { get { return false; } } internal override bool IsIDispatchConstant { get { return false; } } internal override bool IsIUnknownConstant { get { return false; } } internal override bool IsCallerFilePath { get { return false; } } internal override bool IsCallerLineNumber { get { return false; } } internal override bool IsCallerMemberName { get { return false; } } internal override int CallerArgumentExpressionParameterIndex { get { return -1; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => false; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return FlowAnalysisAnnotations.None; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; internal override MarshalPseudoCustomAttributeData? MarshallingInformation { get { return null; } } internal override bool HasOptionalAttribute { get { return false; } } internal override SyntaxList<AttributeListSyntax> AttributeDeclarationList { get { return default(SyntaxList<AttributeListSyntax>); } } internal override CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { state.NotePartComplete(CompletionPart.Attributes); return CustomAttributesBag<CSharpAttributeData>.Empty; } internal override ConstantValue DefaultValueFromAttributes { get { return ConstantValue.NotAvailable; } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Portable/DocumentationComments/DocumentationCommentIDVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class DocumentationCommentIDVisitor : CSharpSymbolVisitor<StringBuilder, object> { public static readonly DocumentationCommentIDVisitor Instance = new DocumentationCommentIDVisitor(); private DocumentationCommentIDVisitor() { } public override object DefaultVisit(Symbol symbol, StringBuilder builder) { // We need to return something to API users, but this should never happen within Roslyn. return null; } public override object VisitNamespace(NamespaceSymbol symbol, StringBuilder builder) { if (!symbol.IsGlobalNamespace) { builder.Append("N:"); PartVisitor.Instance.Visit(symbol, builder); } return null; } public override object VisitMethod(MethodSymbol symbol, StringBuilder builder) { builder.Append("M:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitField(FieldSymbol symbol, StringBuilder builder) { builder.Append("F:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitEvent(EventSymbol symbol, StringBuilder builder) { builder.Append("E:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitProperty(PropertySymbol symbol, StringBuilder builder) { builder.Append("P:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitNamedType(NamedTypeSymbol symbol, StringBuilder builder) { builder.Append("T:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitDynamicType(DynamicTypeSymbol symbol, StringBuilder builder) { // NOTE: Unlike dev11, roslyn allows "dynamic" in parameter types. However, it still // does not allow direct references to "dynamic" (because "dynamic" is only a candidate // in type-only contexts). Therefore, if you ask the dynamic type for its doc comment // ID, it should return null. return DefaultVisit(symbol, builder); } public override object VisitErrorType(ErrorTypeSymbol symbol, StringBuilder builder) { builder.Append("!:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitTypeParameter(TypeParameterSymbol symbol, StringBuilder builder) { builder.Append("!:"); builder.Append(symbol.Name); return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class DocumentationCommentIDVisitor : CSharpSymbolVisitor<StringBuilder, object> { public static readonly DocumentationCommentIDVisitor Instance = new DocumentationCommentIDVisitor(); private DocumentationCommentIDVisitor() { } public override object DefaultVisit(Symbol symbol, StringBuilder builder) { // We need to return something to API users, but this should never happen within Roslyn. return null; } public override object VisitNamespace(NamespaceSymbol symbol, StringBuilder builder) { if (!symbol.IsGlobalNamespace) { builder.Append("N:"); PartVisitor.Instance.Visit(symbol, builder); } return null; } public override object VisitMethod(MethodSymbol symbol, StringBuilder builder) { builder.Append("M:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitField(FieldSymbol symbol, StringBuilder builder) { builder.Append("F:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitEvent(EventSymbol symbol, StringBuilder builder) { builder.Append("E:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitProperty(PropertySymbol symbol, StringBuilder builder) { builder.Append("P:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitNamedType(NamedTypeSymbol symbol, StringBuilder builder) { builder.Append("T:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitDynamicType(DynamicTypeSymbol symbol, StringBuilder builder) { // NOTE: Unlike dev11, roslyn allows "dynamic" in parameter types. However, it still // does not allow direct references to "dynamic" (because "dynamic" is only a candidate // in type-only contexts). Therefore, if you ask the dynamic type for its doc comment // ID, it should return null. return DefaultVisit(symbol, builder); } public override object VisitErrorType(ErrorTypeSymbol symbol, StringBuilder builder) { builder.Append("!:"); PartVisitor.Instance.Visit(symbol, builder); return null; } public override object VisitTypeParameter(TypeParameterSymbol symbol, StringBuilder builder) { builder.Append("!:"); builder.Append(symbol.Name); return null; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Test/Resources/Core/SymbolsTests/Versioning/V2/C.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL;P!  ^$ @ _@$W@`  H.textd  `.rsrc@@@.reloc ` @B@$H  t ( *0 +*( * 7D6$'K5>UXOHVUVçd՝v\bHd2K,݁l2Ǝ] gi$;WRt9;iޮ6M)xQOBSJB v4.0.30319l #~x#Strings#US#GUID(#BlobG %3 T4t4P ' X -l '  ' '' .. 2<Module>mscorlibCD`1SystemObject.ctorMainTSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeC.dll Q2B-d#?z\V4  $$RSA1oO6vk3$jMҭ2eRcعU[IFo2eު3J߾plV nY½%R;=3! K`ay0TWrapNonExceptionThrows,$N$ @$_CorDllMainmscoree.dll% 0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion2.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion2.0.0.08Assembly Version2.0.0.0 `4
MZ@ !L!This program cannot be run in DOS mode. $PEL;P!  ^$ @ _@$W@`  H.textd  `.rsrc@@@.reloc ` @B@$H  t ( *0 +*( * 7D6$'K5>UXOHVUVçd՝v\bHd2K,݁l2Ǝ] gi$;WRt9;iޮ6M)xQOBSJB v4.0.30319l #~x#Strings#US#GUID(#BlobG %3 T4t4P ' X -l '  ' '' .. 2<Module>mscorlibCD`1SystemObject.ctorMainTSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeC.dll Q2B-d#?z\V4  $$RSA1oO6vk3$jMҭ2eRcعU[IFo2eު3J߾plV nY½%R;=3! K`ay0TWrapNonExceptionThrows,$N$ @$_CorDllMainmscoree.dll% 0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion2.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion2.0.0.08Assembly Version2.0.0.0 `4
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Dependencies/Collections/Internal/ArraySortHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; #if NETCOREAPP using System.Numerics; #else using System.Runtime.InteropServices; #endif #if !NET5_0 && !NET5_0_OR_GREATER using Half = System.Single; #endif namespace Microsoft.CodeAnalysis.Collections.Internal { #region ArraySortHelper for single arrays internal static class SegmentedArraySortHelper<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer<T>.Default; IntrospectiveSort(keys, comparer.Compare); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { try { comparer ??= Comparer<T>.Default; return InternalBinarySearch(array, index, length, value, comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } internal static void Sort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, comparer!); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } internal static int InternalBinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T> comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(array[i], value); if (order == 0) return i; if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreater(SegmentedArraySegment<T> keys, Comparison<T> comparer, int i, int j) { Debug.Assert(i != j); if (comparer(keys[i], keys[j]) > 0) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<T> a, int i, int j) { Debug.Assert(i != j); T t = a[i]; a[i] = a[j]; a[j] = t; } internal static void IntrospectiveSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); if (keys.Length > 1) { IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit, Comparison<T> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(keys, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer!, 0, 1); SwapIfGreater(keys, comparer!, 0, 2); SwapIfGreater(keys, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreater(keys, comparer!, 0, middle); // swap the low with the mid point SwapIfGreater(keys, comparer!, 0, hi); // swap the low with the high SwapIfGreater(keys, comparer!, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, 0, i - 1); DownHeap(keys, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && comparer(t, keys[j]) < 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } internal static class SegmentedGenericArraySortHelper<T> where T : IComparable<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { try { if (comparer == null || comparer == Comparer<T>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(T) == typeof(double) || typeof(T) == typeof(float) || typeof(T) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, default(Span<byte>)); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); } IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<T>.IntrospectiveSort(keys, comparer.Compare); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { return BinarySearch(array, index, length, value); } else { return SegmentedArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer); } } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable<T>.CompareTo here. // We can avoid boxing for value type and casting for reference types. private static int BinarySearch(SegmentedArray<T> array, int index, int length, T value) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; if (array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo(value!); } if (order == 0) { return i; } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } /// <summary>Swaps the values in the two references if the first is greater than the second.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SwapIfGreater(ref T i, ref T j) { if (i != null && GreaterThan(ref i, ref j)) { Swap(ref i, ref j); } } /// <summary>Swaps the values in the two references, regardless of whether the two references are the same.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(ref T i, ref T j) { Debug.Assert(!Unsafe.AreSame(ref i, ref j)); T t = i; i = j; j = t; } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(ref keys[0], ref keys[1]); return; } if (partitionSize == 3) { ref T hiRef = ref keys[2]; ref T him1Ref = ref keys[1]; ref T loRef = ref keys[0]; SwapIfGreater(ref loRef, ref him1Ref); SwapIfGreater(ref loRef, ref hiRef); SwapIfGreater(ref him1Ref, ref hiRef); return; } InsertionSort(keys.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); // Use median-of-three to select a pivot. Grab a reference to the 0th, Length-1th, and Length/2th elements, and sort them. int zeroIndex = 0; int lastIndex = keys.Length - 1; int middleIndex = (keys.Length - 1) >> 1; SwapIfGreater(ref keys[zeroIndex], ref keys[middleIndex]); SwapIfGreater(ref keys[zeroIndex], ref keys[lastIndex]); SwapIfGreater(ref keys[middleIndex], ref keys[lastIndex]); // Select the middle value as the pivot, and move it to be just before the last element. int nextToLastIndex = keys.Length - 2; T pivot = keys[middleIndex]; Swap(ref keys[middleIndex], ref keys[nextToLastIndex]); // Walk the left and right pointers, swapping elements as necessary, until they cross. int leftIndex = zeroIndex, rightIndex = nextToLastIndex; while (leftIndex < rightIndex) { if (pivot == null) { while (leftIndex < nextToLastIndex && keys[++leftIndex] == null) { // Intentionally empty } while (rightIndex > zeroIndex && keys[--rightIndex] != null) { // Intentionally empty } } else { while (leftIndex < nextToLastIndex && GreaterThan(ref pivot, ref keys[++leftIndex])) { // Intentionally empty } while (rightIndex > zeroIndex && LessThan(ref pivot, ref keys[--rightIndex])) { // Intentionally empty } } if (leftIndex >= rightIndex) { break; } Swap(ref keys[leftIndex], ref keys[rightIndex]); } // Put the pivot in the correct location. if (leftIndex != nextToLastIndex) { Swap(ref keys[leftIndex], ref keys[nextToLastIndex]); } return leftIndex; } private static void HeapSort(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0); } for (int i = n; i > 1; i--) { Swap(ref keys[0], ref keys[i - 1]); DownHeap(keys, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t!; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion #region ArraySortHelper for paired key and value arrays internal static class SegmentedArraySortHelper<TKey, TValue> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { IntrospectiveSort(keys, values, comparer ?? Comparer<TKey>.Default); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer, int i, int j) { Debug.Assert(comparer != null); Debug.Assert(0 <= i && i < keys.Length && i < values.Length); Debug.Assert(0 <= j && j < keys.Length && j < values.Length); Debug.Assert(i != j); if (comparer!.Compare(keys[i], keys[j]) > 0) { TKey key = keys[i]; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } internal static void IntrospectiveSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length == values.Length); if (keys.Length > 1) { IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit, IComparer<TKey> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); SwapIfGreaterWithValues(keys, values, comparer!, 0, 2); SwapIfGreaterWithValues(keys, values, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, comparer!, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, comparer!, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, comparer!, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!.Compare(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer.Compare(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!.Compare(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && comparer!.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } internal static class SegmentedGenericArraySortHelper<TKey, TValue> where TKey : IComparable<TKey> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float) || typeof(TKey) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, values); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); values = values.Slice(nanLeft); } IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, comparer); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); ref TKey keyRef = ref keys[i]; if (keyRef != null && GreaterThan(ref keyRef, ref keys[j])) { TKey key = keyRef; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, 0, 1); SwapIfGreaterWithValues(keys, values, 0, 2); SwapIfGreaterWithValues(keys, values, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) { // Intentionally empty } while (right > 0 && keys[--right] != null) { // Intentionally empty } } else { while (GreaterThan(ref pivot, ref keys[++left])) { // Intentionally empty } while (LessThan(ref pivot, ref keys[--right])) { // Intentionally empty } } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t!; values[j + 1] = tValue; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion /// <summary>Helper methods for use in array/span sorting routines.</summary> internal static class SegmentedArraySortUtils { #if !NETCOREAPP private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32] { 00, 09, 01, 10, 13, 21, 02, 29, 11, 14, 16, 18, 22, 25, 03, 30, 08, 12, 20, 28, 15, 17, 24, 07, 19, 27, 23, 06, 26, 05, 04, 31, }; #endif public static int MoveNansToFront<TKey, TValue>(SegmentedArraySegment<TKey> keys, Span<TValue> values) where TKey : notnull { Debug.Assert(typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float)); int left = 0; for (int i = 0; i < keys.Length; i++) { if ((typeof(TKey) == typeof(double) && double.IsNaN((double)(object)keys[i])) || (typeof(TKey) == typeof(float) && float.IsNaN((float)(object)keys[i])) || (typeof(TKey) == typeof(Half) && Half.IsNaN((Half)(object)keys[i]))) { TKey temp = keys[left]; keys[left] = keys[i]; keys[i] = temp; if ((uint)i < (uint)values.Length) // check to see if we have values { TValue tempValue = values[left]; values[left] = values[i]; values[i] = tempValue; } left++; } } return left; } public static int Log2(uint value) { #if NETCOREAPP return BitOperations.Log2(value); #else // Fallback contract is 0->0 return Log2SoftwareFallback(value); #endif } #if !NETCOREAPP /// <summary> /// Returns the integer (floor) log of the specified value, base 2. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined. /// Does not directly use any hardware intrinsics, nor does it incur branching. /// </summary> /// <param name="value">The value.</param> private static int Log2SoftwareFallback(uint value) { // No AggressiveInlining due to large method size // Has conventional contract 0->0 (Log(0) is undefined) // Fill trailing zeros with ones, eg 00010010 becomes 00011111 value |= value >> 01; value |= value >> 02; value |= value >> 04; value |= value >> 08; value |= value >> 16; // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check return Unsafe.AddByteOffset( // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u ref MemoryMarshal.GetReference(Log2DeBruijn), // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here (IntPtr)(int)((value * 0x07C4ACDDu) >> 27)); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; #if NETCOREAPP using System.Numerics; #else using System.Runtime.InteropServices; #endif #if !NET5_0 && !NET5_0_OR_GREATER using Half = System.Single; #endif namespace Microsoft.CodeAnalysis.Collections.Internal { #region ArraySortHelper for single arrays internal static class SegmentedArraySortHelper<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer<T>.Default; IntrospectiveSort(keys, comparer.Compare); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { try { comparer ??= Comparer<T>.Default; return InternalBinarySearch(array, index, length, value, comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } internal static void Sort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, comparer!); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } internal static int InternalBinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T> comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(array[i], value); if (order == 0) return i; if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreater(SegmentedArraySegment<T> keys, Comparison<T> comparer, int i, int j) { Debug.Assert(i != j); if (comparer(keys[i], keys[j]) > 0) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<T> a, int i, int j) { Debug.Assert(i != j); T t = a[i]; a[i] = a[j]; a[j] = t; } internal static void IntrospectiveSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); if (keys.Length > 1) { IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit, Comparison<T> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(keys, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer!, 0, 1); SwapIfGreater(keys, comparer!, 0, 2); SwapIfGreater(keys, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreater(keys, comparer!, 0, middle); // swap the low with the mid point SwapIfGreater(keys, comparer!, 0, hi); // swap the low with the high SwapIfGreater(keys, comparer!, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, 0, i - 1); DownHeap(keys, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && comparer(t, keys[j]) < 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } internal static class SegmentedGenericArraySortHelper<T> where T : IComparable<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { try { if (comparer == null || comparer == Comparer<T>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(T) == typeof(double) || typeof(T) == typeof(float) || typeof(T) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, default(Span<byte>)); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); } IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<T>.IntrospectiveSort(keys, comparer.Compare); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { return BinarySearch(array, index, length, value); } else { return SegmentedArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer); } } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable<T>.CompareTo here. // We can avoid boxing for value type and casting for reference types. private static int BinarySearch(SegmentedArray<T> array, int index, int length, T value) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; if (array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo(value!); } if (order == 0) { return i; } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } /// <summary>Swaps the values in the two references if the first is greater than the second.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SwapIfGreater(ref T i, ref T j) { if (i != null && GreaterThan(ref i, ref j)) { Swap(ref i, ref j); } } /// <summary>Swaps the values in the two references, regardless of whether the two references are the same.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(ref T i, ref T j) { Debug.Assert(!Unsafe.AreSame(ref i, ref j)); T t = i; i = j; j = t; } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(ref keys[0], ref keys[1]); return; } if (partitionSize == 3) { ref T hiRef = ref keys[2]; ref T him1Ref = ref keys[1]; ref T loRef = ref keys[0]; SwapIfGreater(ref loRef, ref him1Ref); SwapIfGreater(ref loRef, ref hiRef); SwapIfGreater(ref him1Ref, ref hiRef); return; } InsertionSort(keys.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); // Use median-of-three to select a pivot. Grab a reference to the 0th, Length-1th, and Length/2th elements, and sort them. int zeroIndex = 0; int lastIndex = keys.Length - 1; int middleIndex = (keys.Length - 1) >> 1; SwapIfGreater(ref keys[zeroIndex], ref keys[middleIndex]); SwapIfGreater(ref keys[zeroIndex], ref keys[lastIndex]); SwapIfGreater(ref keys[middleIndex], ref keys[lastIndex]); // Select the middle value as the pivot, and move it to be just before the last element. int nextToLastIndex = keys.Length - 2; T pivot = keys[middleIndex]; Swap(ref keys[middleIndex], ref keys[nextToLastIndex]); // Walk the left and right pointers, swapping elements as necessary, until they cross. int leftIndex = zeroIndex, rightIndex = nextToLastIndex; while (leftIndex < rightIndex) { if (pivot == null) { while (leftIndex < nextToLastIndex && keys[++leftIndex] == null) { // Intentionally empty } while (rightIndex > zeroIndex && keys[--rightIndex] != null) { // Intentionally empty } } else { while (leftIndex < nextToLastIndex && GreaterThan(ref pivot, ref keys[++leftIndex])) { // Intentionally empty } while (rightIndex > zeroIndex && LessThan(ref pivot, ref keys[--rightIndex])) { // Intentionally empty } } if (leftIndex >= rightIndex) { break; } Swap(ref keys[leftIndex], ref keys[rightIndex]); } // Put the pivot in the correct location. if (leftIndex != nextToLastIndex) { Swap(ref keys[leftIndex], ref keys[nextToLastIndex]); } return leftIndex; } private static void HeapSort(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0); } for (int i = n; i > 1; i--) { Swap(ref keys[0], ref keys[i - 1]); DownHeap(keys, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t!; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion #region ArraySortHelper for paired key and value arrays internal static class SegmentedArraySortHelper<TKey, TValue> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { IntrospectiveSort(keys, values, comparer ?? Comparer<TKey>.Default); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer, int i, int j) { Debug.Assert(comparer != null); Debug.Assert(0 <= i && i < keys.Length && i < values.Length); Debug.Assert(0 <= j && j < keys.Length && j < values.Length); Debug.Assert(i != j); if (comparer!.Compare(keys[i], keys[j]) > 0) { TKey key = keys[i]; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } internal static void IntrospectiveSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length == values.Length); if (keys.Length > 1) { IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit, IComparer<TKey> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); SwapIfGreaterWithValues(keys, values, comparer!, 0, 2); SwapIfGreaterWithValues(keys, values, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, comparer!, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, comparer!, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, comparer!, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!.Compare(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer.Compare(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!.Compare(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && comparer!.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } internal static class SegmentedGenericArraySortHelper<TKey, TValue> where TKey : IComparable<TKey> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float) || typeof(TKey) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, values); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); values = values.Slice(nanLeft); } IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, comparer); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); ref TKey keyRef = ref keys[i]; if (keyRef != null && GreaterThan(ref keyRef, ref keys[j])) { TKey key = keyRef; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, 0, 1); SwapIfGreaterWithValues(keys, values, 0, 2); SwapIfGreaterWithValues(keys, values, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) { // Intentionally empty } while (right > 0 && keys[--right] != null) { // Intentionally empty } } else { while (GreaterThan(ref pivot, ref keys[++left])) { // Intentionally empty } while (LessThan(ref pivot, ref keys[--right])) { // Intentionally empty } } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t!; values[j + 1] = tValue; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion /// <summary>Helper methods for use in array/span sorting routines.</summary> internal static class SegmentedArraySortUtils { #if !NETCOREAPP private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32] { 00, 09, 01, 10, 13, 21, 02, 29, 11, 14, 16, 18, 22, 25, 03, 30, 08, 12, 20, 28, 15, 17, 24, 07, 19, 27, 23, 06, 26, 05, 04, 31, }; #endif public static int MoveNansToFront<TKey, TValue>(SegmentedArraySegment<TKey> keys, Span<TValue> values) where TKey : notnull { Debug.Assert(typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float)); int left = 0; for (int i = 0; i < keys.Length; i++) { if ((typeof(TKey) == typeof(double) && double.IsNaN((double)(object)keys[i])) || (typeof(TKey) == typeof(float) && float.IsNaN((float)(object)keys[i])) || (typeof(TKey) == typeof(Half) && Half.IsNaN((Half)(object)keys[i]))) { TKey temp = keys[left]; keys[left] = keys[i]; keys[i] = temp; if ((uint)i < (uint)values.Length) // check to see if we have values { TValue tempValue = values[left]; values[left] = values[i]; values[i] = tempValue; } left++; } } return left; } public static int Log2(uint value) { #if NETCOREAPP return BitOperations.Log2(value); #else // Fallback contract is 0->0 return Log2SoftwareFallback(value); #endif } #if !NETCOREAPP /// <summary> /// Returns the integer (floor) log of the specified value, base 2. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined. /// Does not directly use any hardware intrinsics, nor does it incur branching. /// </summary> /// <param name="value">The value.</param> private static int Log2SoftwareFallback(uint value) { // No AggressiveInlining due to large method size // Has conventional contract 0->0 (Log(0) is undefined) // Fill trailing zeros with ones, eg 00010010 becomes 00011111 value |= value >> 01; value |= value >> 02; value |= value >> 04; value |= value >> 08; value |= value >> 16; // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check return Unsafe.AddByteOffset( // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u ref MemoryMarshal.GetReference(Log2DeBruijn), // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here (IntPtr)(int)((value * 0x07C4ACDDu) >> 27)); } #endif } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/PropertyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public class PropertyTests : CSharpTestBase { [Fact] public void SetGetOnlyAutoPropNoExperimental() { // One would think this creates an error, but it doesn't because // language version is a property of the parser and there are // no syntactical changes to the language for get-only autoprops CreateCompilationWithMscorlib45(@" class C { public int P { get; } }").VerifyDiagnostics(); } [Fact] public void SetGetOnlyAutoPropInConstructor() { CreateCompilationWithMscorlib45(@" class C { public int P { get; } public C() { P = 10; } }").VerifyDiagnostics(); } [Fact] public void GetOnlyAutoPropBadOverride() { CreateCompilationWithMscorlib45(@" class Base { public virtual int P { get; set; } public virtual int P1 { get { return 1; } set { } } } class C : Base { public override int P { get; } public override int P1 { get; } public C() { P = 10; P1 = 10; } }").VerifyDiagnostics( // (12,25): error CS8080: "Auto-implemented properties must override all accessors of the overridden property." // public override int P { get; } Diagnostic(ErrorCode.ERR_AutoPropertyMustOverrideSet, "P").WithArguments("C.P").WithLocation(12, 25), // (13,25): error CS8080: "Auto-implemented properties must override all accessors of the overridden property." // public override int P1 { get; } Diagnostic(ErrorCode.ERR_AutoPropertyMustOverrideSet, "P1").WithArguments("C.P1").WithLocation(13, 25) ); } [Fact] public void SetGetOnlyAutoPropOutOfConstructor() { CreateCompilationWithMscorlib45(@" class C { public int P { get; } public static int Ps { get; } public C() { Ps = 3; } public void M() { P = 10; C.Ps = 1; } } struct S { public int P { get; } public static int Ps { get; } public S() { this = default(S); Ps = 5; } public void M() { P = 10; S.Ps = 1; } } ", parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,9): error CS0200: Property or indexer 'C.Ps' cannot be assigned to -- it is read only // Ps = 3; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Ps").WithArguments("C.Ps").WithLocation(9, 9), // (14,9): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only // P = 10; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(14, 9), // (15,9): error CS0200: Property or indexer 'C.Ps' cannot be assigned to -- it is read only // C.Ps = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "C.Ps").WithArguments("C.Ps").WithLocation(15, 9), // (24,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S").WithArguments("parameterless struct constructors", "10.0").WithLocation(24, 12), // (27,9): error CS0200: Property or indexer 'S.Ps' cannot be assigned to -- it is read only // Ps = 5; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Ps").WithArguments("S.Ps").WithLocation(27, 9), // (32,9): error CS0200: Property or indexer 'S.P' cannot be assigned to -- it is read only // P = 10; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("S.P").WithLocation(32, 9), // (33,9): error CS0200: Property or indexer 'S.Ps' cannot be assigned to -- it is read only // S.Ps = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "S.Ps").WithArguments("S.Ps").WithLocation(33, 9)); } [Fact] public void StructWithSameNameFieldAndProperty() { var text = @" struct S { int a = 2; int a { get { return 1; } set {} } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,9): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // int a = 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(4, 9), // (5,9): error CS0102: The type 'S' already contains a definition for 'a' // int a { get { return 1; } set {} } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "a").WithArguments("S", "a").WithLocation(5, 9), // (4,9): warning CS0414: The field 'S.a' is assigned but its value is never used // int a = 2; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("S.a").WithLocation(4, 9)); } [Fact] public void AutoWithInitializerInClass() { var text = @"class C { public int P { get; set; } = 1; internal protected static long Q { get; } = 10; public decimal R { get; } = 300; }"; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<PropertySymbol>("P"); Assert.NotNull(p.GetMethod); Assert.NotNull(p.SetMethod); var q = c.GetMember<PropertySymbol>("Q"); Assert.NotNull(q.GetMethod); Assert.Null(q.SetMethod); var r = c.GetMember<PropertySymbol>("R"); Assert.NotNull(r.GetMethod); Assert.Null(r.SetMethod); } [Fact] public void AutoWithInitializerInStruct1() { var text = @" struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "P").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (6,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(6, 20)); } [Fact] public void AutoWithInitializerInStruct2() { var text = @"struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int i) : this() {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "P").WithArguments("struct field initializers", "10.0").WithLocation(3, 16), // (5,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(5, 20)); var global = comp.GlobalNamespace; var s = global.GetTypeMember("S"); var p = s.GetMember<PropertySymbol>("P"); Assert.NotNull(p.GetMethod); Assert.NotNull(p.SetMethod); var q = s.GetMember<PropertySymbol>("Q"); Assert.NotNull(q.GetMethod); Assert.Null(q.SetMethod); var r = s.GetMember<PropertySymbol>("R"); Assert.NotNull(r.GetMethod); Assert.Null(r.SetMethod); } [Fact] public void AutoInitializerInInterface() { var text = @"interface I { int P { get; } = 0; }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (3,9): error CS8053: Instance properties in interfaces cannot have initializers. // int P { get; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P").WithArguments("I.P").WithLocation(3, 9)); } [Fact] public void AutoNoSetOrInitializer() { var text = @"class C { public int P { get; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics(); } [Fact] public void AutoNoGet() { var text = @"class C { public int P { set {} } public int Q { set; } = 0; public int R { set; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (4,20): error CS8051: Auto-implemented properties must have get accessors. // public int Q { set; } = 0; Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C.Q.set").WithLocation(4, 20), // (5,20): error CS8051: Auto-implemented properties must have get accessors. // public int R { set; } Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C.R.set").WithLocation(5, 20)); } [Fact] public void AutoRefReturn() { var text = @"class C { public ref int P { get; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (3,20): error CS8080: Auto-implemented properties cannot return by reference // public ref int P { get; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "P").WithArguments("C.P").WithLocation(3, 20)); } [Fact] public void AutoRefReadOnlyReturn() { var text = @" class C { public ref readonly int P1 { get; set; } }"; var comp = CreateCompilation(text).VerifyDiagnostics( // (4,29): error CS8145: Auto-implemented properties cannot return by reference // public ref readonly int P1 { get; set; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "P1").WithArguments("C.P1").WithLocation(4, 29), // (4,39): error CS8147: Properties which return by reference cannot have set accessors // public ref readonly int P1 { get; set; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.P1.set").WithLocation(4, 39)); } [WorkItem(542745, "DevDiv")] [WorkItem(542745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542745")] [Fact()] public void AutoImplementedAccessorNotImplicitlyDeclared() { var text = @" class A { abstract int P { get; set; } internal int P2 { get; set; } } interface I { int Q {get; set; } } "; // Per design meeting (see bug 11253), in C#, if there's a "get" or "set" written, // then IsImplicitDeclared should be false. var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var i = global.GetTypeMembers("I", 0).Single(); var p = a.GetMembers("P").SingleOrDefault() as PropertySymbol; Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.False(p.SetMethod.IsImplicitlyDeclared); p = a.GetMembers("P2").SingleOrDefault() as PropertySymbol; Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.False(p.SetMethod.IsImplicitlyDeclared); var q = i.GetMembers("Q").SingleOrDefault() as PropertySymbol; Assert.False(q.GetMethod.IsImplicitlyDeclared); Assert.False(q.SetMethod.IsImplicitlyDeclared); } [WorkItem(542746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542746")] [Fact] public void AutoImplementedBackingFieldLocation() { var text = @" class C { int Prop { get; set; } struct S { string Prop { get; set; } } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var type01 = global.GetTypeMembers("C").Single(); var type02 = type01.GetTypeMembers("S").Single(); var mems = type01.GetMembers(); FieldSymbol backField = null; // search but not use internal backfield name // there is exact ONE field symbol in this test foreach (var m in mems) { if (m.Kind == SymbolKind.Field) { backField = m as FieldSymbol; break; } } // Back field location should be same as Property Assert.NotNull(backField); Assert.False(backField.Locations.IsEmpty); var prop = type01.GetMembers("Prop").Single() as PropertySymbol; Assert.Equal(prop.Locations.Length, backField.Locations.Length); Assert.Equal(prop.Locations[0].ToString(), backField.Locations[0].ToString()); // ------------------------------------- mems = type02.GetMembers(); backField = null; // search but not use internal backfield name // there is exact ONE field symbol in this test foreach (var m in mems) { if (m.Kind == SymbolKind.Field) { backField = m as FieldSymbol; break; } } // Back field location should be same as Property Assert.NotNull(backField); Assert.False(backField.Locations.IsEmpty); prop = type02.GetMembers("Prop").Single() as PropertySymbol; Assert.Equal(prop.Locations.Length, backField.Locations.Length); Assert.Equal(prop.Locations[0].ToString(), backField.Locations[0].ToString()); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void EventEscapedIdentifier() { var text = @" delegate void @out(); class C1 { @out @in { get; }; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(); PropertySymbol ein = (PropertySymbol)c1.GetMembers("in").Single(); Assert.Equal("in", ein.Name); Assert.Equal("C1.@in", ein.ToString()); NamedTypeSymbol dout = (NamedTypeSymbol)ein.Type; Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [ClrOnlyFact] public void PropertyNonDefaultAccessorNames() { var source = @" class Program { static void M(Valid i) { i.Instance = 0; System.Console.Write(""{0}"", i.Instance); } static void Main() { Valid.Static = 0; System.Console.Write(""{0}"", Valid.Static); } } "; var compilation = CompileAndVerify(source, new[] { s_propertiesDll }, expectedOutput: "0"); compilation.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""void Valid.Static.set"" IL_0006: ldstr ""{0}"" IL_000b: call ""int Valid.Static.get"" IL_0010: box ""int"" IL_0015: call ""void System.Console.Write(string, object)"" IL_001a: ret } "); } [WorkItem(528633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528633")] [Fact] public void MismatchedAccessorTypes() { var source = @" class Program { static void M(Mismatched i) { i.Instance = 0; System.Console.Write(""{0}"", i.Instance); } static void N(Signatures i) { i.StaticAndInstance = 0; i.GetUsedAsSet = 0; } static void Main() { Mismatched.Static = 0; System.Console.Write(""{0}"", Mismatched.Static); } } "; var compilation = CompileWithCustomPropertiesAssembly(source); var actualErrors = compilation.GetDiagnostics(); compilation.VerifyDiagnostics( // (6,11): error CS1061: 'Mismatched' does not contain a definition for 'Instance' and no extension method 'Instance' accepting a first argument of type 'Mismatched' could be found (are you missing a using directive or an assembly reference?) // i.Instance = 0; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Instance").WithArguments("Mismatched", "Instance"), // (7,39): error CS1061: 'Mismatched' does not contain a definition for 'Instance' and no extension method 'Instance' accepting a first argument of type 'Mismatched' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write("{0}", i.Instance); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Instance").WithArguments("Mismatched", "Instance"), // (11,11): error CS1545: Property, indexer, or event 'Signatures.StaticAndInstance' is not supported by the language; try directly calling accessor methods 'Signatures.GoodStatic.get' or 'Signatures.GoodInstance.set' // i.StaticAndInstance = 0; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "StaticAndInstance").WithArguments("Signatures.StaticAndInstance", "Signatures.GoodStatic.get", "Signatures.GoodInstance.set"), // (12,11): error CS1545: Property, indexer, or event 'Signatures.GetUsedAsSet' is not supported by the language; try directly calling accessor methods 'Signatures.GoodInstance.get' or 'Signatures.GoodInstance.get' // i.GetUsedAsSet = 0; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "GetUsedAsSet").WithArguments("Signatures.GetUsedAsSet", "Signatures.GoodInstance.get", "Signatures.GoodInstance.get"), // (16,20): error CS0117: 'Mismatched' does not contain a definition for 'Static' // Mismatched.Static = 0; Diagnostic(ErrorCode.ERR_NoSuchMember, "Static").WithArguments("Mismatched", "Static"), // (17,48): error CS0117: 'Mismatched' does not contain a definition for 'Static' // System.Console.Write("{0}", Mismatched.Static); Diagnostic(ErrorCode.ERR_NoSuchMember, "Static").WithArguments("Mismatched", "Static")); } /// <summary> /// Properties should refer to methods /// in the type members collection. /// </summary> [ClrOnlyFact] public void MethodsAndAccessorsSame() { var source = @"class A { public static object P { get; set; } public object Q { get; set; } } class B<T> { public static T P { get; set; } public T Q { get; set; } } class C : B<string> { } "; Action<ModuleSymbol> validator = module => { // Non-generic type. var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); Assert.Equal(0, type.TypeParameters.Length); Assert.Same(type, type.ConstructedFrom); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("P")); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("Q")); // Generic type. type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("B"); Assert.Equal(1, type.TypeParameters.Length); Assert.Same(type, type.ConstructedFrom); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("P")); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("Q")); // Generic type with parameter substitution. type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").BaseType(); Assert.Equal(1, type.TypeParameters.Length); Assert.NotSame(type, type.ConstructedFrom); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("P")); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("Q")); }; CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator); } private void VerifyMethodsAndAccessorsSame(NamedTypeSymbol type, PropertySymbol property) { VerifyMethodAndAccessorSame(type, property, property.GetMethod); VerifyMethodAndAccessorSame(type, property, property.SetMethod); } private void VerifyMethodAndAccessorSame(NamedTypeSymbol type, PropertySymbol property, MethodSymbol accessor) { Assert.NotNull(accessor); Assert.Equal(type, accessor.ContainingType); Assert.Equal(type, accessor.ContainingSymbol); var method = type.GetMembers(accessor.Name).Single(); Assert.NotNull(method); Assert.Equal(accessor, method); Assert.True(accessor.MethodKind == MethodKind.PropertyGet || accessor.MethodKind == MethodKind.PropertySet, "Accessor kind: " + accessor.MethodKind.ToString()); Assert.Equal(accessor.AssociatedSymbol, property); } [WorkItem(538789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538789")] [Fact] public void NoAccessors() { var source = @" class Program { static void M(NoAccessors i) { i.Instance = NoAccessors.Static; } } "; var compilation = CompileWithCustomPropertiesAssembly(source); var actualErrors = compilation.GetDiagnostics(); DiagnosticsUtils.VerifyErrorCodes(actualErrors, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 6, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMember, Line = 6, Column = 34 }); var type = (PENamedTypeSymbol)compilation.GlobalNamespace.GetMembers("NoAccessors").Single(); // Methods are available. Assert.NotNull(type.GetMembers("StaticMethod").SingleOrDefault()); Assert.NotNull(type.GetMembers("InstanceMethod").SingleOrDefault()); Assert.Equal(2, type.GetMembers().OfType<MethodSymbol>().Count()); // Properties are not available. Assert.Null(type.GetMembers("Static").SingleOrDefault()); Assert.Null(type.GetMembers("Instance").SingleOrDefault()); Assert.Equal(0, type.GetMembers().OfType<PropertySymbol>().Count()); } /// <summary> /// Calling bogus methods directly should be allowed. /// </summary> [ClrOnlyFact] public void CallMethodsDirectly() { var source = @" class Program { static void M(Mismatched i) { i.InstanceBoolSet(false); System.Console.Write(""{0}"", i.InstanceInt32Get()); } static void Main() { Mismatched.StaticBoolSet(false); System.Console.Write(""{0}"", Mismatched.StaticInt32Get()); } } "; var compilation = CompileAndVerify(source, new[] { s_propertiesDll }, expectedOutput: "0"); compilation.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""void Mismatched.StaticBoolSet(bool)"" IL_0006: ldstr ""{0}"" IL_000b: call ""int Mismatched.StaticInt32Get()"" IL_0010: box ""int"" IL_0015: call ""void System.Console.Write(string, object)"" IL_001a: ret } "); } [ClrOnlyFact] public void MethodsReferencedInMultipleProperties() { var source = @" class Program { static void M(Signatures i) { i.GoodInstance = 0; System.Console.Write(""{0}"", i.GoodInstance); } static void Main() { Signatures.GoodStatic = 0; System.Console.Write(""{0}"", Signatures.GoodStatic); } } "; var verifier = CompileAndVerify(source, new[] { s_propertiesDll }, expectedOutput: "0"); verifier.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""void Signatures.GoodStatic.set"" IL_0006: ldstr ""{0}"" IL_000b: call ""int Signatures.GoodStatic.get"" IL_0010: box ""int"" IL_0015: call ""void System.Console.Write(string, object)"" IL_001a: ret } "); var type = (PENamedTypeSymbol)verifier.Compilation.GlobalNamespace.GetMembers("Signatures").Single().GetSymbol(); // Valid static property, property with signature that does not match accessors, // and property with accessors that do not match each other. var goodStatic = (PEPropertySymbol)type.GetMembers("GoodStatic").Single(); var badStatic = (PEPropertySymbol)type.GetMembers("BadStatic").Single(); var mismatchedStatic = (PEPropertySymbol)type.GetMembers("MismatchedStatic").Single(); Assert.False(goodStatic.MustCallMethodsDirectly); Assert.True(badStatic.MustCallMethodsDirectly); Assert.True(mismatchedStatic.MustCallMethodsDirectly); VerifyAccessor(goodStatic.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(goodStatic.SetMethod, goodStatic, MethodKind.PropertySet); VerifyAccessor(badStatic.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(badStatic.SetMethod, goodStatic, MethodKind.PropertySet); VerifyAccessor(mismatchedStatic.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(mismatchedStatic.SetMethod, null, MethodKind.Ordinary); // Valid instance property, property with signature that does not match accessors, // and property with accessors that do not match each other. var goodInstance = (PEPropertySymbol)type.GetMembers("GoodInstance").Single(); var badInstance = (PEPropertySymbol)type.GetMembers("BadInstance").Single(); var mismatchedInstance = (PEPropertySymbol)type.GetMembers("MismatchedInstance").Single(); Assert.False(goodInstance.MustCallMethodsDirectly); Assert.True(badInstance.MustCallMethodsDirectly); Assert.True(mismatchedInstance.MustCallMethodsDirectly); VerifyAccessor(goodInstance.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(goodInstance.SetMethod, goodInstance, MethodKind.PropertySet); VerifyAccessor(badInstance.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(badInstance.SetMethod, goodInstance, MethodKind.PropertySet); VerifyAccessor(mismatchedInstance.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(mismatchedInstance.SetMethod, null, MethodKind.Ordinary); // Mix of static and instance accessors. var staticAndInstance = (PEPropertySymbol)type.GetMembers("StaticAndInstance").Single(); VerifyAccessor(staticAndInstance.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(staticAndInstance.SetMethod, goodInstance, MethodKind.PropertySet); Assert.True(staticAndInstance.MustCallMethodsDirectly); // Property with get and set accessors both referring to the same get method. var getUsedAsSet = (PEPropertySymbol)type.GetMembers("GetUsedAsSet").Single(); VerifyAccessor(getUsedAsSet.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(getUsedAsSet.SetMethod, goodInstance, MethodKind.PropertyGet); Assert.True(getUsedAsSet.MustCallMethodsDirectly); } private void VerifyAccessor(MethodSymbol accessor, PEPropertySymbol associatedProperty, MethodKind methodKind) { Assert.NotNull(accessor); Assert.Equal(accessor.AssociatedSymbol, associatedProperty); Assert.Equal(accessor.MethodKind, methodKind); if (associatedProperty != null) { var method = (methodKind == MethodKind.PropertyGet) ? associatedProperty.GetMethod : associatedProperty.SetMethod; Assert.Equal(accessor, method); } } /// <summary> /// Support mixes of family and assembly. /// </summary> [Fact] public void FamilyAssembly() { var source = @" class Program { static void Main() { System.Console.Write(""{0}"", Signatures.StaticGet()); } } "; var compilation = CompileWithCustomPropertiesAssembly(source, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var type = (PENamedTypeSymbol)compilation.GlobalNamespace.GetMembers("FamilyAssembly").Single(); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyGetAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.Protected, Accessibility.Internal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyGetFamilyOrAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.Protected, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyGetFamilyAndAssemblySetStatic").Single(), Accessibility.Protected, Accessibility.Protected, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("AssemblyGetFamilyOrAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.Internal, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("AssemblyGetFamilyAndAssemblySetStatic").Single(), Accessibility.Internal, Accessibility.Internal, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyOrAssemblyGetFamilyOrAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyOrAssemblyGetFamilyAndAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyAndAssemblyGetFamilyAndAssemblySetStatic").Single(), Accessibility.ProtectedAndInternal, Accessibility.ProtectedAndInternal, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyAndAssemblyGetOnlyInstance").Single(), Accessibility.ProtectedAndInternal, Accessibility.ProtectedAndInternal, Accessibility.NotApplicable); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyOrAssemblySetOnlyInstance").Single(), Accessibility.ProtectedOrInternal, Accessibility.NotApplicable, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyAndAssemblyGetFamilyOrAssemblySetInstance").Single(), Accessibility.ProtectedOrInternal, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal); } // Property and getter with void type. Dev10 treats this as a valid // property. Would it be better to treat the property as invalid? [Fact] public void VoidPropertyAndAccessorType() { const string ilSource = @" .class public A { .method public static void get_P() { ret } .property void P() { .get void A::get_P() } .method public instance void get_Q() { ret } .property void Q() { .get instance void A::get_Q() } } "; const string cSharpSource = @" class C { static void M(A x) { N(A.P); N(x.Q); } static void N(object o) { } }"; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgType, "A.P").WithArguments("1", "void", "object"), Diagnostic(ErrorCode.ERR_BadArgType, "x.Q").WithArguments("1", "void", "object")); } /// <summary> /// Properties where the property and accessor signatures differ by /// modopt only should be supported (as in the native compiler). /// </summary> [ClrOnlyFact] public void SignaturesDifferByModOptsOnly() { const string ilSource = @".class public A { } .class public B { } .class public C { .method public instance int32 get_noopt() { ldc.i4.0 ret } .method public instance int32 modopt(A) get_returnopt() { ldc.i4.0 ret } .method public instance void set_noopt(int32 val) { ret } .method public instance void set_argopt(int32 modopt(A) val) { ret } .method public instance void modopt(A) set_returnopt(int32 val) { ret } // Modifier on property but not accessors. .property int32 modopt(A) P1() { .get instance int32 C::get_noopt() .set instance void C::set_noopt(int32) } // Modifier on accessors but not property. .property int32 P2() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_argopt(int32 modopt(A)) } // Modifier on getter only. .property int32 P3() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_noopt(int32) } // Modifier on setter only. .property int32 P4() { .get instance int32 C::get_noopt() .set instance void C::set_argopt(int32 modopt(A)) } // Modifier on setter return type. .property int32 P5() { .get instance int32 C::get_noopt() .set instance void modopt(A) C::set_returnopt(int32) } // Modifier on property and different modifier on accessors. .property int32 modopt(B) P6() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_argopt(int32 modopt(A)) } }"; const string cSharpSource = @"class D { static void M(C c) { c.P1 = c.P1; c.P2 = c.P2; c.P3 = c.P3; c.P4 = c.P4; c.P5 = c.P5; c.P6 = c.P6; } }"; CompileWithCustomILSource(cSharpSource, ilSource); } [WorkItem(538956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538956")] [ClrOnlyFact] public void PropertyAccessorDoesNotHideMethod() { const string cSharpSource = @" interface IA { string get_Goo(); } interface IB : IA { int Goo { get; } } class Program { static void Main() { IB x = null; string s = x.get_Goo().ToLower(); } } "; CompileWithCustomILSource(cSharpSource, null); } [WorkItem(538956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538956")] [ClrOnlyFact] public void PropertyAccessorDoesNotConflictWithMethod() { const string cSharpSource = @" interface IA { string get_Goo(); } interface IB { int Goo { get; } } interface IC : IA, IB { } class Program { static void Main() { IC x = null; string s = x.get_Goo().ToLower(); } } "; CompileWithCustomILSource(cSharpSource, null); } [WorkItem(538956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538956")] [Fact] public void PropertyAccessorCannotBeCalledAsMethod() { const string cSharpSource = @" interface I { int Goo { get; } } class Program { static void Main() { I x = null; string s = x.get_Goo(); } } "; CreateCompilation(cSharpSource).VerifyDiagnostics( // (9,22): error CS0571: 'I.Goo.get': cannot explicitly call operator or accessor // string s = x.get_Goo(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Goo").WithArguments("I.Goo.get")); } [WorkItem(538992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538992")] [Fact] public void CanNotAccessPropertyThroughParenthesizedType() { const string cSharpSource = @" class Program { static void Main() { (Program).X = 1; } static int X { get; set; } } "; CreateCompilation(cSharpSource).VerifyDiagnostics( // (6,10): error CS0119: 'Program' is a type, which is not valid in the given context // (Program).X = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type")); } [ClrOnlyFact] public void CanReadInstancePropertyWithStaticGetterAsStatic() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property instance int32 Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [Fact] public void CanNotReadInstancePropertyWithStaticGetterAsInstance() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property instance int32 Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { A a = null; int x = a.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (5,13): error CS0176: Member 'A.Goo' cannot be accessed with an instance reference; qualify it with a type name instead // int x = a.Goo; Diagnostic(ErrorCode.ERR_ObjectProhibited, "a.Goo").WithArguments("A.Goo")); } [WorkItem(527658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527658")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS1546ERR_BindToBogusProp1_PropertyWithPinnedModifierIsBogus() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property instance int32 pinned Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,18): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // object x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(538850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538850")] [Fact] public void PropertyWithMismatchedReturnTypeOfGetterIsBogus() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property string Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,18): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // object x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(527659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527659")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void PropertyWithCircularReturnTypeIsNotSupported() { const string ilSource = @" .class public E extends E { } .class public A { .method public static class E get_Goo() { ldnull throw } .property class E Goo() { .get class E A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; B y = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (5,11): error CS0268: Imported type 'E' is invalid. It contains a circular base type dependency. // B y = A.Goo; Diagnostic(ErrorCode.ERR_ImportedCircularBase, "A.Goo").WithArguments("E", "E"), // (5,11): error CS0029: Cannot implicitly convert type 'E' to 'B' // B y = A.Goo; Diagnostic(ErrorCode.ERR_NoImplicitConv, "A.Goo").WithArguments("E", "B") ); // Dev10 errors: // error CS0268: Imported type 'E' is invalid. It contains a circular base type dependency. // error CS0570: 'A.Goo' is not supported by the language } [WorkItem(527664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527664")] [Fact(Skip = "527664")] public void PropertyWithOpenGenericTypeAsTypeArgumentOfReturnTypeIsNotSupported() { const string ilSource = @" .class public E<T> { } .class public A { .method public static class E<class E> get_Goo() { ldnull throw } .property class E<class E> Goo() { .get class E<class E> A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); // TODO: check diagnostics when it is implemented } [WorkItem(527657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527657")] [Fact(Skip = "527657")] public void Dev10IgnoresSentinelInPropertySignature() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo(...) { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadModOptProperty() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(int32) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [WorkItem(527660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527660")] [Fact(Skip = "527660")] public void CanReadPropertyWithModOptInBaseClassOfReturnType() { const string ilSource = @" .class public E extends class [mscorlib]System.Collections.Generic.List`1<int32> modopt(int8) { } .class public A { .method public static class E get_Goo() { ldnull throw } .property class E Goo() { .get class E A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyOfArrayTypeWithModOptElement() { const string ilSource = @" .class public A { .method public static int32 modopt(int32)[] get_Goo() { ldnull throw } .property int32 modopt(int32)[] Goo() { .get int32 modopt(int32)[] A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int[] x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadModOptPropertyWithNonModOptGetter() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property int32 modopt(int32) Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [WorkItem(527656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527656")] [Fact(Skip = "527656")] public void CanReadNonModOptPropertyWithOpenGenericModOptGetter() { const string ilSource = @" .class public A { .method public static int32 modopt(class [mscorlib]System.IComparable`1) get_Goo() { ldnull throw } .property int32 Goo() { .get int32 modopt(class [mscorlib]System.IComparable`1) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadNonModOptPropertyWithModOptGetter() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadModOptPropertyWithDifferentModOptGetter() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(string) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics(); } [WorkItem(538845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538845")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyWithMultipleAndNestedModOpts() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(int8) modopt(native int modopt(uint8)*[] modopt(void)) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,15): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // int x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyWithModReqsNestedWithinModOpts() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(class [mscorlib]System.IComparable`1<method void*()[]> modreq(bool)) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,15): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // int x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(538846, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538846")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanNotReadPropertyWithModReq() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property int32 modreq(int8) Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,18): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // object x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(527662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527662")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyWithModReqInBaseClassOfReturnType() { const string ilSource = @" .class public E extends class [mscorlib]System.Collections.Generic.List`1<int32 modreq(int8)[]> { } .class public A { .method public static class E get_Goo() { ldnull throw } .property class E Goo() { .get class E A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics(); } [WorkItem(538787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538787")] [Fact] public void CanNotReadPropertyOfUnsupportedType() { const string ilSource = @" .class public auto ansi beforefieldinit Indexers extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(string modreq(int16) x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(string modreq(int16)) { .get instance int32 Indexers::get_Item(string modreq(int16)) } } // end of class Indexers "; const string cSharpSource = @" class C { static void Main() { object goo = new Indexers()[null]; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,22): error CS1546: Property, indexer, or event 'Indexers.this[string]' is not supported by the language; try directly calling accessor method 'Indexers.get_Item(string)' // object goo = new Indexers()[null]; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "new Indexers()[null]").WithArguments("Indexers.this[string]", "Indexers.get_Item(string)").WithLocation(4, 22)); } [WorkItem(538791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538791")] [Fact] public void CanNotReadAmbiguousProperty() { const string ilSource = @" .class public B { .method public instance void .ctor() { ldarg.0 call instance void class System.Object::.ctor() ret } .method public static int32 get_Goo() { ldnull throw } .method public static int32[] get_Goo() { ldnull throw } .property int32 Goo() { .get int32 B::get_Goo() } .property int32[] Goo() { .get int32[] B::get_Goo() } } "; const string cSharpSource = @" class C { static void Main() { object goo = B.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,24): error CS0229: Ambiguity between 'B.Goo' and 'B.Goo' // object goo = B.Goo; Diagnostic(ErrorCode.ERR_AmbigMember, "Goo").WithArguments("B.Goo", "B.Goo")); } [Fact] public void VoidReturningPropertyHidesMembersFromBase() { const string ilSource = @" .class public B { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo() { .get int32 B::get_Goo() } } .class public A extends B { .method public static void get_Goo() { ldnull throw } .property void Goo() { .get void A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,16): error CS0029: Cannot implicitly convert type 'void' to 'object' // object x = A.Goo; Diagnostic(ErrorCode.ERR_NoImplicitConv, "A.Goo").WithArguments("void", "object")); } [WorkItem(527663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527663")] [Fact] public void CanNotReadPropertyFromAmbiguousGenericClass() { const string ilSource = @" .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '09f9df97-a228-4ca4-9b71-151909f205e6' { } .class public A`1<T> { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo() { .get int32 A`1::get_Goo() } } .class public A<T> { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo() { .get int32 A::get_Goo() } } "; var ref0 = CompileIL(ilSource, prependDefaultHeader: false); const string cSharpSource = @" class B { static void Main() { object x = A<int>.Goo; } } "; CreateCompilation(cSharpSource, references: new[] { ref0 }).VerifyDiagnostics( // (4,16): error CS0433: The type 'A<T>' exists in both '09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and '09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // object x = A<int>.Goo; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "A<int>").WithArguments("09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "A<T>", "09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 16)); } [WorkItem(538789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538789")] [Fact] public void PropertyWithoutAccessorsIsBogus() { const string ilSource = @" .class public B { .method public instance void .ctor() { ldarg.0 call instance void class System.Object::.ctor() ret } .property int32 Goo() { } } "; const string cSharpSource = @" class C { static void Main() { object goo = B.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,24): error CS0117: 'B' does not contain a definition for 'Goo' // object goo = B.Goo; Diagnostic(ErrorCode.ERR_NoSuchMember, "Goo").WithArguments("B", "Goo")); } [WorkItem(538946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538946")] [Fact] public void FalseAmbiguity() { const string text = @" interface IA { int Goo { get; } } interface IB<T> : IA { } interface IC : IB<int>, IB<string> { } class C { static void Main() { IC x = null; int y = x.Goo; } } "; var comp = CreateCompilation(Parse(text)); var diagnostics = comp.GetDiagnostics(); Assert.Empty(diagnostics); } [WorkItem(539320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539320")] [Fact] public void FalseWarningCS0109ForNewModifier() { const string text = @" class MyBase { public int MyProp { get { return 1; } } } class MyClass : MyBase { int intI = 0; new int MyProp { get { return intI; } set { intI = value; } } } "; var comp = CreateCompilation(Parse(text)); var diagnostics = comp.GetDiagnostics(); Assert.Empty(diagnostics); } [WorkItem(539319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539319")] [Fact] public void FalseErrorCS0103ForValueKeywordInExpImpl() { const string text = @" interface MyInter { int MyProp { get; set; } } class MyClass : MyInter { static int intI = 0; int MyInter.MyProp { get { return intI; } set { intI = value; } } } "; var comp = CreateCompilation(Parse(text)); var diagnostics = comp.GetDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void ExplicitInterfaceImplementationSimple() { string text = @" interface I { int P { get; set; } } class C : I { int I.P { get; set; } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceProperty = (PropertySymbol)@interface.GetMembers("P").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classProperty = (PropertySymbol)@class.GetMembers("I.P").Single(); CheckPropertyExplicitImplementation(@class, classProperty, interfaceProperty); } [Fact] public void ExplicitInterfaceImplementationRefReturn() { string text = @" interface I { ref int P { get; } } class C : I { int field; ref int I.P { get { return ref field; } } } "; var comp = CreateCompilationWithMscorlib45(text); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceProperty = (PropertySymbol)@interface.GetMembers("P").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classProperty = (PropertySymbol)@class.GetMembers("I.P").Single(); Assert.Equal(RefKind.Ref, classProperty.RefKind); CheckRefPropertyExplicitImplementation(@class, classProperty, interfaceProperty); } [Fact] public void ExplicitInterfaceImplementationGeneric() { string text = @" namespace N { interface I<T> { T P { get; set; } } } class C : N.I<int> { int N.I<int>.P { get; set; } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var @namespace = (NamespaceSymbol)globalNamespace.GetMembers("N").Single(); var @interface = (NamedTypeSymbol)@namespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceProperty = (PropertySymbol)@interface.GetMembers("P").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var classProperty = (PropertySymbol)@class.GetMembers("N.I<System.Int32>.P").Single(); var substitutedInterface = @class.Interfaces().Single(); Assert.Equal(@interface, substitutedInterface.ConstructedFrom); var substitutedInterfaceProperty = (PropertySymbol)substitutedInterface.GetMembers("P").Single(); CheckPropertyExplicitImplementation(@class, classProperty, substitutedInterfaceProperty); } [Fact] public void ImportPropertiesWithParameters() { //TODO: To be implemented once indexer properties implemented } [WorkItem(539998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539998")] [ClrOnlyFact] public void ImportDefaultPropertiesWithParameters() { var source = @" class Program { public static WithParameterizedProps testClass = new WithParameterizedProps(); static void Main() { testClass.set_P(1, null); System.Console.Write(testClass.get_P(1)); testClass.set_P(""2"", null); System.Console.Write(testClass.get_P(""2"")); testClass.set_P(1, ""2"", null); System.Console.Write(testClass.get_P(1, ""2"")); } } "; var compilation = CreateCompilation( source, new[] { TestReferences.SymbolsTests.Properties }, TestOptions.ReleaseExe); Action<ModuleSymbol> validator = module => { var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Program"); var field = program.GetMember<FieldSymbol>("testClass"); var type = field.Type; // Non-generic type. //var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("WithParameterizedProps"); var getters = type.GetMembers("get_P").OfType<MethodSymbol>(); Assert.Equal(2, getters.Count(getter => getter.Parameters.Length == 1)); Assert.Equal(1, getters.Count(getter => getter.Parameters.Length == 2)); Assert.True(getters.Any(getter => getter.Parameters[0].Type.SpecialType == SpecialType.System_Int32)); Assert.True(getters.Any(getter => getter.Parameters[0].Type.SpecialType == SpecialType.System_String)); Assert.True(getters.Any(getter => getter.Parameters.Length == 2 && getter.Parameters[0].Type.SpecialType == SpecialType.System_Int32 && getter.Parameters[1].Type.SpecialType == SpecialType.System_String)); }; // TODO: it would be nice to validate the emitted symbols, but CompileAndVerify currently has a limitation // where it won't pick up the referenced assemblies from the compilation when it creates the ModuleSymbol // for the emitted assembly (i.e. WithParameterizedProps will be missing). CompileAndVerify(compilation, sourceSymbolValidator: validator, /*symbolValidator: validator,*/ expectedOutput: "1221"); } [WorkItem(540342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540342")] [ClrOnlyFact] public void NoSequencePointsForAutoPropertyAccessors() { var text = @" class C { object P { get; set; } }"; CompileAndVerify(text).VerifyDiagnostics(); } [WorkItem(541688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541688")] [Fact] public void Simple2() { var text = @" using System; public class A : Attribute { public A X { get; set; } public A X { get; set; } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var xs = a.GetMembers("X"); Assert.Equal(2, xs.Length); foreach (var x in xs) { Assert.Equal(a, (x as PropertySymbol).Type); // duplicate, but all the same. } var errors = comp.GetDeclarationDiagnostics(); var one = errors.Single(); Assert.Equal(ErrorCode.ERR_DuplicateNameInClass, (ErrorCode)one.Code); } [WorkItem(528769, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528769")] [Fact] public void IndexerGetSetParameterLocation() { string text = @"using System; class Test { public int this[int i] { get { return i; } set { } } } "; var comp = CreateCompilation(text); var globalNamespace = comp.SourceModule.GlobalNamespace; var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Test").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var accessor = @class.GetMembers("get_Item").Single() as MethodSymbol; Assert.Equal(1, accessor.Parameters.Length); var locs = accessor.Parameters[0].Locations; // i Assert.Equal(1, locs.Length); Assert.True(locs[0].IsInSource, "InSource"); accessor = @class.GetMembers("set_Item").Single() as MethodSymbol; Assert.Equal(2, accessor.Parameters.Length); // i locs = accessor.Parameters[0].Locations; Assert.Equal(1, locs.Length); Assert.True(locs[0].IsInSource, "InSource"); } [WorkItem(545682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545682")] [ClrOnlyFact] public void PropertyWithParametersHidingMethod01() { var source1 = @"Public Class A Public Shared Function P() As Object Return Nothing End Function Public Function Q() As Object Return Nothing End Function End Class Public Class B1 Inherits A Public Shared Shadows Property P As Object Public Shadows Property Q As Object End Class Public Class B2 Inherits A Public Shared Shadows ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property Public Shadows ReadOnly Property Q(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static void M(B1 b) { object o; o = B1.P; o = B1.P(); o = b.Q; o = b.Q(); } }"; var compilation2 = CompileAndVerify(source2, new[] { reference1 }); compilation2.VerifyDiagnostics(); compilation2.VerifyIL("C.M(B1)", @"{ // Code size 27 (0x1b) .maxstack 1 IL_0000: call ""object B1.P.get"" IL_0005: pop IL_0006: call ""object A.P()"" IL_000b: pop IL_000c: ldarg.0 IL_000d: callvirt ""object B1.Q.get"" IL_0012: pop IL_0013: ldarg.0 IL_0014: callvirt ""object A.Q()"" IL_0019: pop IL_001a: ret }"); var source3 = @"class C { static void M(B2 b) { object o; o = B2.P; o = B2.P(); o = b.Q; o = b.Q(); } }"; var compilation3 = CreateCompilation(source3, new[] { reference1 }); compilation3.VerifyDiagnostics( // (6,16): error CS0428: Cannot convert method group 'P' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "P").WithArguments("P", "object").WithLocation(6, 16), // (8,15): error CS0428: Cannot convert method group 'Q' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Q").WithArguments("Q", "object").WithLocation(8, 15)); } [ClrOnlyFact] public void PropertyWithParametersHidingMethod02() { var source1 = @"Public Class A Public ReadOnly Property P(x As Object, y As Object) As Object Get Return Nothing End Get End Property End Class Public Class B Inherits A Public Shadows ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); // Property with parameters hiding property with parameters. var source2 = @"class C { static void M(B b) { object o; o = b.P; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,15): error CS1546: Property, indexer, or event 'B.P[object]' is not supported by the language; try directly calling accessor method 'B.get_P(object)' Diagnostic(ErrorCode.ERR_BindToBogusProp1, "P").WithArguments("B.P[object]", "B.get_P(object)").WithLocation(6, 15)); // Property with parameters and extension method. var source3 = @"class C { static void M(A a) { object o; o = a.P; } } static class E { internal static object P(this object o) { return null; } }"; var compilation3 = CreateCompilationWithMscorlib40AndSystemCore(source3, new[] { reference1 }); compilation3.VerifyDiagnostics( // (6,15): error CS0428: Cannot convert method group 'P' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "P").WithArguments("P", "object").WithLocation(6, 15)); } [ClrOnlyFact] public void PropertyWithParametersHidingMethod03() { var source1 = @"Public Class A Public Function P1() As Object Return Nothing End Function Public Function P2() As Object Return Nothing End Function Public Function P3() As Object Return Nothing End Function Friend Function P4() As Object Return Nothing End Function Friend Function P5() As Object Return Nothing End Function Friend Function P6() As Object Return Nothing End Function Protected Function P7() As Object Return Nothing End Function Protected Function P8() As Object Return Nothing End Function Protected Function P9() As Object Return Nothing End Function End Class Public Class B Inherits A Public Shadows ReadOnly Property P1(o As Object) As Object Get Return Nothing End Get End Property Friend Shadows ReadOnly Property P2(o As Object) As Object Get Return Nothing End Get End Property Protected Shadows ReadOnly Property P3(o As Object) As Object Get Return Nothing End Get End Property Public Shadows ReadOnly Property P4(o As Object) As Object Get Return Nothing End Get End Property Friend Shadows ReadOnly Property P5(o As Object) As Object Get Return Nothing End Get End Property Protected Shadows ReadOnly Property P6(o As Object) As Object Get Return Nothing End Get End Property Public Shadows ReadOnly Property P7(o As Object) As Object Get Return Nothing End Get End Property Friend Shadows ReadOnly Property P8(o As Object) As Object Get Return Nothing End Get End Property Protected Shadows ReadOnly Property P9(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C : B { void M() { object o; o = this.P1(); o = this.P2(); o = this.P3(); o = this.P4(); o = this.P5(); o = this.P6(); o = this.P7(); o = this.P8(); o = this.P9(); } } class D { static void M(B b) { object o; o = b.P1(); o = b.P2(); o = b.P3(); o = b.P4(); o = b.P5(); o = b.P6(); o = b.P7(); o = b.P8(); o = b.P9(); } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (9,18): error CS1955: Non-invocable member 'B.P4[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P4").WithArguments("B.P4[object]").WithLocation(9, 18), // (10,18): error CS1061: 'C' does not contain a definition for 'P5' and no extension method 'P5' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P5").WithArguments("C", "P5").WithLocation(10, 18), // (11,18): error CS1955: Non-invocable member 'B.P6[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P6").WithArguments("B.P6[object]").WithLocation(11, 18), // (25,15): error CS1955: Non-invocable member 'B.P4[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P4").WithArguments("B.P4[object]").WithLocation(25, 15), // (26,15): error CS1061: 'B' does not contain a definition for 'P5' and no extension method 'P5' accepting a first argument of type 'B' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P5").WithArguments("B", "P5").WithLocation(26, 15), // (27,15): error CS1955: Non-invocable member 'B.P6[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P6").WithArguments("B.P6[object]").WithLocation(27, 15), // (28,15): error CS1955: Non-invocable member 'B.P7[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P7").WithArguments("B.P7[object]").WithLocation(28, 15), // (29,15): error CS0122: 'A.P8()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "P8").WithArguments("A.P8()").WithLocation(29, 15), // (30,15): error CS1955: Non-invocable member 'B.P9[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P9").WithArguments("B.P9[object]").WithLocation(30, 15)); } [ClrOnlyFact] public void PropertyWithParametersAndOtherErrors() { var source1 = @"Public Class A Public Shared ReadOnly Property P1(o As Object) As Object Get Return Nothing End Get End Property Public ReadOnly Property P2(o As Object) As Object Get Return Nothing End Get End Property Protected ReadOnly Property P3(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class B { static void M(A a) { object o; o = a.P1; o = A.P2; o = a.P3; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,15): error CS1546: Property, indexer, or event 'A.P1[object]' is not supported by the language; try directly calling accessor method 'A.get_P1(object)' Diagnostic(ErrorCode.ERR_BindToBogusProp1, "P1").WithArguments("A.P1[object]", "A.get_P1(object)").WithLocation(6, 15), // (7,15): error CS1546: Property, indexer, or event 'A.P2[object]' is not supported by the language; try directly calling accessor method 'A.get_P2(object)' Diagnostic(ErrorCode.ERR_BindToBogusProp1, "P2").WithArguments("A.P2[object]", "A.get_P2(object)").WithLocation(7, 15), // (8,15): error CS0122: 'A.P3[object]' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("A.P3[object]").WithLocation(8, 15)); } [ClrOnlyFact] public void SubstitutedPropertyWithParameters() { var source1 = @"Public Class A(Of T) Public Property P(o As Object) As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class B { static void M(A<object> a) { object o; o = a.P; a.P = o; o = a.get_P(null); a.set_P(null, o); } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,15): error CS1545: Property, indexer, or event 'A<object>.P[object]' is not supported by the language; try directly calling accessor methods 'A<object>.get_P(object)' or 'A<object>.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P").WithArguments("A<object>.P[object]", "A<object>.get_P(object)", "A<object>.set_P(object, object)").WithLocation(6, 15), // (7,11): error CS1545: Property, indexer, or event 'A<object>.P[object]' is not supported by the language; try directly calling accessor methods 'A<object>.get_P(object)' or 'A<object>.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P").WithArguments("A<object>.P[object]", "A<object>.get_P(object)", "A<object>.set_P(object, object)").WithLocation(7, 11)); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void DifferentAccessorSignatures_ByRef() { var source1 = @".class public A1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object P(object) { .get instance object A1::get_P(object) .set instance void A1::set_P(object, object v) } } .class public A2 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object P(object) { .get instance object A2::get_P(object) .set instance void A2::set_P(object&, object v) } } .class public A3 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object P(object) { .get instance object A3::get_P(object) .set instance void A3::set_P(object, object& v) } } .class public A4 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object& P(object) { .get instance object& A4::get_P(object) .set instance void A4::set_P(object, object v) } } .class public A5 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object& P(object) { .get instance object& A5::get_P(object) .set instance void A5::set_P(object&, object v) } } .class public A6 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object& P(object) { .get instance object& A6::get_P(object) .set instance void A6::set_P(object, object& v) } } .class public A7 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object P(object&) { .get instance object A7::get_P(object&) .set instance void A7::set_P(object, object v) } } .class public A8 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object P(object&) { .get instance object A8::get_P(object&) .set instance void A8::set_P(object&, object v) } } .class public A9 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object P(object&) { .get instance object A9::get_P(object&) .set instance void A9::set_P(object, object& v) } }"; var reference1 = CompileIL(source1); var source2 = @"class C { static void M(A1 _1, A2 _2, A3 _3, A4 _4, A5 _5, A6 _6, A7 _7, A8 _8, A9 _9) { object x = null; object y = null; _1[y] = _1[x]; _2[y] = _2[x]; _3[y] = _3[x]; _4[y] = _4[x]; _5[y] = _5[x]; _6[y] = _6[x]; _7[ref y] = _7[ref x]; _8[ref y] = _8[ref x]; _9[ref y] = _9[ref x]; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,9): error CS1545: Property, indexer, or event 'A2.this[object]' is not supported by the language; try directly calling accessor methods 'A2.get_P(object)' or 'A2.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_2[y]").WithArguments("A2.this[object]", "A2.get_P(object)", "A2.set_P(ref object, object)").WithLocation(8, 9), // (8,17): error CS1545: Property, indexer, or event 'A2.this[object]' is not supported by the language; try directly calling accessor methods 'A2.get_P(object)' or 'A2.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_2[x]").WithArguments("A2.this[object]", "A2.get_P(object)", "A2.set_P(ref object, object)").WithLocation(8, 17), // (9,9): error CS1545: Property, indexer, or event 'A3.this[object]' is not supported by the language; try directly calling accessor methods 'A3.get_P(object)' or 'A3.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_3[y]").WithArguments("A3.this[object]", "A3.get_P(object)", "A3.set_P(object, ref object)").WithLocation(9, 9), // (9,17): error CS1545: Property, indexer, or event 'A3.this[object]' is not supported by the language; try directly calling accessor methods 'A3.get_P(object)' or 'A3.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_3[x]").WithArguments("A3.this[object]", "A3.get_P(object)", "A3.set_P(object, ref object)").WithLocation(9, 17), // (10,9): error CS1545: Property, indexer, or event 'A4.this[object]' is not supported by the language; try directly calling accessor methods 'A4.get_P(object)' or 'A4.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_4[y]").WithArguments("A4.this[object]", "A4.get_P(object)", "A4.set_P(object, object)").WithLocation(10, 9), // (10,17): error CS1545: Property, indexer, or event 'A4.this[object]' is not supported by the language; try directly calling accessor methods 'A4.get_P(object)' or 'A4.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_4[x]").WithArguments("A4.this[object]", "A4.get_P(object)", "A4.set_P(object, object)").WithLocation(10, 17), // (11,9): error CS1545: Property, indexer, or event 'A5.this[object]' is not supported by the language; try directly calling accessor methods 'A5.get_P(object)' or 'A5.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_5[y]").WithArguments("A5.this[object]", "A5.get_P(object)", "A5.set_P(ref object, object)").WithLocation(11, 9), // (11,17): error CS1545: Property, indexer, or event 'A5.this[object]' is not supported by the language; try directly calling accessor methods 'A5.get_P(object)' or 'A5.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_5[x]").WithArguments("A5.this[object]", "A5.get_P(object)", "A5.set_P(ref object, object)").WithLocation(11, 17), // (12,9): error CS1545: Property, indexer, or event 'A6.this[object]' is not supported by the language; try directly calling accessor methods 'A6.get_P(object)' or 'A6.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_6[y]").WithArguments("A6.this[object]", "A6.get_P(object)", "A6.set_P(object, ref object)").WithLocation(12, 9), // (12,17): error CS1545: Property, indexer, or event 'A6.this[object]' is not supported by the language; try directly calling accessor methods 'A6.get_P(object)' or 'A6.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_6[x]").WithArguments("A6.this[object]", "A6.get_P(object)", "A6.set_P(object, ref object)").WithLocation(12, 17), // (13,9): error CS1545: Property, indexer, or event 'A7.this[ref object]' is not supported by the language; try directly calling accessor methods 'A7.get_P(ref object)' or 'A7.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_7[ref y]").WithArguments("A7.this[ref object]", "A7.get_P(ref object)", "A7.set_P(object, object)").WithLocation(13, 9), // (13,21): error CS1545: Property, indexer, or event 'A7.this[ref object]' is not supported by the language; try directly calling accessor methods 'A7.get_P(ref object)' or 'A7.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_7[ref x]").WithArguments("A7.this[ref object]", "A7.get_P(ref object)", "A7.set_P(object, object)").WithLocation(13, 21), // (14,9): error CS1545: Property, indexer, or event 'A8.this[ref object]' is not supported by the language; try directly calling accessor methods 'A8.get_P(ref object)' or 'A8.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_8[ref y]").WithArguments("A8.this[ref object]", "A8.get_P(ref object)", "A8.set_P(ref object, object)").WithLocation(14, 9), // (14,21): error CS1545: Property, indexer, or event 'A8.this[ref object]' is not supported by the language; try directly calling accessor methods 'A8.get_P(ref object)' or 'A8.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_8[ref x]").WithArguments("A8.this[ref object]", "A8.get_P(ref object)", "A8.set_P(ref object, object)").WithLocation(14, 21), // (15,9): error CS1545: Property, indexer, or event 'A9.this[ref object]' is not supported by the language; try directly calling accessor methods 'A9.get_P(ref object)' or 'A9.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_9[ref y]").WithArguments("A9.this[ref object]", "A9.get_P(ref object)", "A9.set_P(object, ref object)").WithLocation(15, 9), // (15,21): error CS1545: Property, indexer, or event 'A9.this[ref object]' is not supported by the language; try directly calling accessor methods 'A9.get_P(ref object)' or 'A9.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_9[ref x]").WithArguments("A9.this[ref object]", "A9.get_P(ref object)", "A9.set_P(object, ref object)").WithLocation(15, 21)); } #region "helpers" private static void CheckPropertyExplicitImplementation(NamedTypeSymbol @class, PropertySymbol classProperty, PropertySymbol interfaceProperty) { var interfacePropertyGetter = interfaceProperty.GetMethod; Assert.NotNull(interfacePropertyGetter); var interfacePropertySetter = interfaceProperty.SetMethod; Assert.NotNull(interfacePropertySetter); Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single()); var classPropertyGetter = classProperty.GetMethod; Assert.NotNull(classPropertyGetter); var classPropertySetter = classProperty.SetMethod; Assert.NotNull(classPropertySetter); Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single()); Assert.Equal(interfacePropertySetter, classPropertySetter.ExplicitInterfaceImplementations.Single()); var typeDef = (Microsoft.Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverrides = typeDef.GetExplicitImplementationOverrides(context); Assert.Equal(2, explicitOverrides.Count()); Assert.True(explicitOverrides.All(@override => ReferenceEquals(@class, @override.ContainingType.GetInternalSymbol()))); // We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements var getterOverride = explicitOverrides.First(); Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name); var setterOverride = explicitOverrides.Last(); Assert.Equal(classPropertySetter, setterOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfacePropertySetter.ContainingType, setterOverride.ImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(interfacePropertySetter.Name, setterOverride.ImplementedMethod.Name); context.Diagnostics.Verify(); } private static void CheckRefPropertyExplicitImplementation(NamedTypeSymbol @class, PropertySymbol classProperty, PropertySymbol interfaceProperty) { var interfacePropertyGetter = interfaceProperty.GetMethod; Assert.NotNull(interfacePropertyGetter); var interfacePropertySetter = interfaceProperty.SetMethod; Assert.Null(interfacePropertySetter); Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single()); var classPropertyGetter = classProperty.GetMethod; Assert.NotNull(classPropertyGetter); var classPropertySetter = classProperty.SetMethod; Assert.Null(classPropertySetter); Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single()); var typeDef = (Microsoft.Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverrides = typeDef.GetExplicitImplementationOverrides(context); Assert.Equal(1, explicitOverrides.Count()); Assert.True(explicitOverrides.All(@override => ReferenceEquals(@class, @override.ContainingType.GetInternalSymbol()))); // We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements var getterOverride = explicitOverrides.Single(); Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name); } private static void VerifyAccessibility(PEPropertySymbol property, Accessibility propertyAccessibility, Accessibility getAccessibility, Accessibility setAccessibility) { Assert.Equal(property.DeclaredAccessibility, propertyAccessibility); Assert.False(property.MustCallMethodsDirectly); VerifyAccessorAccessibility(property.GetMethod, getAccessibility); VerifyAccessorAccessibility(property.SetMethod, setAccessibility); } private static void VerifyAccessorAccessibility(MethodSymbol accessor, Accessibility accessorAccessibility) { if (accessorAccessibility == Accessibility.NotApplicable) { Assert.Null(accessor); } else { Assert.NotNull(accessor); Assert.Equal(accessor.DeclaredAccessibility, accessorAccessibility); } } private CSharpCompilation CompileWithCustomPropertiesAssembly(string source, CSharpCompilationOptions options = null) { return CreateCompilation(source, new[] { s_propertiesDll }, options ?? TestOptions.ReleaseDll); } private static readonly MetadataReference s_propertiesDll = TestReferences.SymbolsTests.Properties; #endregion [ConditionalFact(typeof(DesktopOnly))] public void InteropDynamification() { var refSrc = @" using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""C35913A8-93FF-40B1-94AC-8F363CC17589"")] [ComImport] [Guid(""D541FDE7-A872-4AF7-8F68-DC9C2FC8DCC9"")] public interface IA { object P { get; } object M(); string P2 { get; } string M2(); }"; var refComp = CSharpCompilation.Create("DLL", options: TestOptions.DebugDll, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(refSrc) }, references: new MetadataReference[] { MscorlibRef }); var refData = AssemblyMetadata.CreateFromImage(refComp.EmitToArray()); var mdRef = refData.GetReference(embedInteropTypes: false); var comp = CreateCompilationWithMscorlib46("", new[] { mdRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.False(comp.ExternalReferences[1].Properties.EmbedInteropTypes); var ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); var iap = ia.GetMember<PropertySymbol>("P"); Assert.False(iap.Type.IsDynamic()); var iam = ia.GetMember<MethodSymbol>("M"); Assert.False(iam.ReturnType.IsDynamic()); var iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); var iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); var compRef = refComp.ToMetadataReference(embedInteropTypes: false); comp = CreateCompilationWithMscorlib46("", new[] { compRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.False(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.False(iap.Type.IsDynamic()); iam = ia.GetMember<MethodSymbol>("M"); Assert.False(iam.ReturnType.IsDynamic()); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); mdRef = refData.GetReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { mdRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.True(iap.Type.IsDynamic()); iam = ia.GetMember<MethodSymbol>("M"); Assert.True(iam.ReturnType.IsDynamic()); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); compRef = refComp.ToMetadataReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { compRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.True(iap.Type.IsDynamic()); iam = ia.GetMember<MethodSymbol>("M"); Assert.True(iam.ReturnType.IsDynamic()); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); Assert.Equal(2, comp.ExternalReferences.Length); refSrc = @" using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""C35913A8-93FF-40B1-94AC-8F363CC17589"")] public interface IA { object P { get; } object M(); string P2 { get; } string M2(); }"; refComp = CSharpCompilation.Create("DLL", options: TestOptions.DebugDll, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(refSrc) }, references: new[] { MscorlibRef }); refData = AssemblyMetadata.CreateFromImage(refComp.EmitToArray()); mdRef = refData.GetReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { mdRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.Equal(SpecialType.System_Object, iap.Type.SpecialType); iam = ia.GetMember<MethodSymbol>("M"); Assert.Equal(SpecialType.System_Object, iam.ReturnType.SpecialType); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); compRef = refComp.ToMetadataReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { compRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.Equal(SpecialType.System_Object, iap.Type.SpecialType); iam = ia.GetMember<MethodSymbol>("M"); Assert.Equal(SpecialType.System_Object, iam.ReturnType.SpecialType); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); } private delegate void VerifyType(bool isWinMd, params string[] expectedMembers); /// <summary> /// When the output type is .winmdobj properties should emit put_Property methods instead /// of set_Property methods. /// </summary> [ClrOnlyFact] public void WinRtPropertySet() { const string libSrc = @"namespace Test { public sealed class C { public int a; public int A { get { return a; } set { a = value; } } } }"; Func<string[], Action<ModuleSymbol>> getValidator = expectedMembers => m => { var actualMembers = m.GlobalNamespace.GetMember<NamespaceSymbol>("Test"). GetMember<NamedTypeSymbol>("C").GetMembers().ToArray(); AssertEx.SetEqual(actualMembers.Select(s => s.Name), expectedMembers); }; VerifyType verify = (winmd, expected) => { var validator = getValidator(expected); // We should see the same members from both source and metadata var verifier = CompileAndVerify( libSrc, sourceSymbolValidator: validator, symbolValidator: validator, options: winmd ? TestOptions.ReleaseWinMD : TestOptions.ReleaseDll); verifier.VerifyDiagnostics(); }; // Test winmd verify(true, "a", "A", "get_A", "put_A", WellKnownMemberNames.InstanceConstructorName); // Test normal verify(false, "a", "A", "get_A", "set_A", WellKnownMemberNames.InstanceConstructorName); } /// <summary> /// Accessor type names that conflict should cause the appropriate diagnostic /// (i.e., set_ for dll, put_ for winmdobj) /// </summary> [Fact] public void WinRtPropertyAccessorNameConflict() { const string libSrc = @"namespace Test { public sealed class C { public int A { get; set; } public void put_A(int value) {} public void set_A(int value) {} } }"; var comp = CreateCompilation(libSrc, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (7,18): error CS0082: Type 'Test.C' already reserves a member called 'set_A' with the same parameter types // get; set; Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_A", "Test.C")); comp = CreateCompilation(libSrc, options: TestOptions.ReleaseWinMD); comp.VerifyDiagnostics( // (7,18): error CS0082: Type 'Test.C' already reserves a member called 'put_A' with the same parameter types // get; set; Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("put_A", "Test.C")); } [Fact] public void AutoPropertiesBeforeCSharp3() { var source = @" interface I { int P { get; set; } // Fine } abstract class A { public abstract int P { get; set; } // Fine } class C { public int P { get; set; } // Error } "; CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3)).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp2)).VerifyDiagnostics( // (14,16): error CS8023: Feature 'automatically implemented properties' is not available in C# 2. Please use language version 3 or greater. // public int P { get; set; } // Error Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion2, "P").WithArguments("automatically implemented properties", "3")); } [WorkItem(1073332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073332")] [ClrOnlyFact] public void Bug1073332_01() { var text = @" class Test { static int[] property { get; } = { 1, 2, 3 }; static void Main(string[] args) { foreach (var x in property) { System.Console.Write(x); } } } "; CompileAndVerify(text, expectedOutput: "123").VerifyDiagnostics(); } [WorkItem(1073332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073332")] [Fact] public void Bug1073332_02() { var text = @" unsafe class Test { int* property { get; } = stackalloc int[256]; static void Main(string[] args) { } } "; CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (4,30): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible. // int* property { get; } = stackalloc int[256]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[256]").WithArguments("int", "int*").WithLocation(4, 30) ); } [Fact] public void RefPropertyWithoutGetter() { var source = @" class C { ref int P { set { } } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,17): error CS8080: Properties with by-reference returns must have a get accessor. // ref int P { set { } } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void RefPropertyWithGetterAndSetter() { var source = @" class C { int field = 0; ref int P { get { return ref field; } set { } } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,47): error CS8081: Properties with by-reference returns cannot have set accessors. // ref int P { get { return ref field; } set { } } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.P.set").WithLocation(5, 47)); } [Fact, WorkItem(4696, "https://github.com/dotnet/roslyn/issues/4696")] public void LangVersionAndReadonlyAutoProperty() { var source = @" public class Class1 { public Class1() { Prop1 = ""Test""; } public string Prop1 { get; } } abstract class Class2 { public abstract string Prop2 { get; } } interface I1 { string Prop3 { get; } } "; var comp = CreateCompilation(source, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); comp.GetDeclarationDiagnostics().Verify( // (9,19): error CS8026: Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater. // public string Prop1 { get; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "Prop1").WithArguments("readonly automatically implemented properties", "6").WithLocation(9, 19) ); } [Fact] public void StaticPropertyDoesNotRequireInstanceReceiver() { var source = @" class C { public static int P { get; } }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var property = compilation.GetMember<PropertySymbol>("C.P"); Assert.False(property.RequiresInstanceReceiver); } [Fact] public void InstancePropertyRequiresInstanceReceiver() { var source = @" class C { public int P { get; } }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var property = compilation.GetMember<PropertySymbol>("C.P"); Assert.True(property.RequiresInstanceReceiver); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public class PropertyTests : CSharpTestBase { [Fact] public void SetGetOnlyAutoPropNoExperimental() { // One would think this creates an error, but it doesn't because // language version is a property of the parser and there are // no syntactical changes to the language for get-only autoprops CreateCompilationWithMscorlib45(@" class C { public int P { get; } }").VerifyDiagnostics(); } [Fact] public void SetGetOnlyAutoPropInConstructor() { CreateCompilationWithMscorlib45(@" class C { public int P { get; } public C() { P = 10; } }").VerifyDiagnostics(); } [Fact] public void GetOnlyAutoPropBadOverride() { CreateCompilationWithMscorlib45(@" class Base { public virtual int P { get; set; } public virtual int P1 { get { return 1; } set { } } } class C : Base { public override int P { get; } public override int P1 { get; } public C() { P = 10; P1 = 10; } }").VerifyDiagnostics( // (12,25): error CS8080: "Auto-implemented properties must override all accessors of the overridden property." // public override int P { get; } Diagnostic(ErrorCode.ERR_AutoPropertyMustOverrideSet, "P").WithArguments("C.P").WithLocation(12, 25), // (13,25): error CS8080: "Auto-implemented properties must override all accessors of the overridden property." // public override int P1 { get; } Diagnostic(ErrorCode.ERR_AutoPropertyMustOverrideSet, "P1").WithArguments("C.P1").WithLocation(13, 25) ); } [Fact] public void SetGetOnlyAutoPropOutOfConstructor() { CreateCompilationWithMscorlib45(@" class C { public int P { get; } public static int Ps { get; } public C() { Ps = 3; } public void M() { P = 10; C.Ps = 1; } } struct S { public int P { get; } public static int Ps { get; } public S() { this = default(S); Ps = 5; } public void M() { P = 10; S.Ps = 1; } } ", parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (9,9): error CS0200: Property or indexer 'C.Ps' cannot be assigned to -- it is read only // Ps = 3; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Ps").WithArguments("C.Ps").WithLocation(9, 9), // (14,9): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only // P = 10; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(14, 9), // (15,9): error CS0200: Property or indexer 'C.Ps' cannot be assigned to -- it is read only // C.Ps = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "C.Ps").WithArguments("C.Ps").WithLocation(15, 9), // (24,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S").WithArguments("parameterless struct constructors", "10.0").WithLocation(24, 12), // (27,9): error CS0200: Property or indexer 'S.Ps' cannot be assigned to -- it is read only // Ps = 5; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Ps").WithArguments("S.Ps").WithLocation(27, 9), // (32,9): error CS0200: Property or indexer 'S.P' cannot be assigned to -- it is read only // P = 10; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("S.P").WithLocation(32, 9), // (33,9): error CS0200: Property or indexer 'S.Ps' cannot be assigned to -- it is read only // S.Ps = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "S.Ps").WithArguments("S.Ps").WithLocation(33, 9)); } [Fact] public void StructWithSameNameFieldAndProperty() { var text = @" struct S { int a = 2; int a { get { return 1; } set {} } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,9): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // int a = 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(4, 9), // (5,9): error CS0102: The type 'S' already contains a definition for 'a' // int a { get { return 1; } set {} } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "a").WithArguments("S", "a").WithLocation(5, 9), // (4,9): warning CS0414: The field 'S.a' is assigned but its value is never used // int a = 2; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("S.a").WithLocation(4, 9)); } [Fact] public void AutoWithInitializerInClass() { var text = @"class C { public int P { get; set; } = 1; internal protected static long Q { get; } = 10; public decimal R { get; } = 300; }"; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<PropertySymbol>("P"); Assert.NotNull(p.GetMethod); Assert.NotNull(p.SetMethod); var q = c.GetMember<PropertySymbol>("Q"); Assert.NotNull(q.GetMethod); Assert.Null(q.SetMethod); var r = c.GetMember<PropertySymbol>("R"); Assert.NotNull(r.GetMethod); Assert.Null(r.SetMethod); } [Fact] public void AutoWithInitializerInStruct1() { var text = @" struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "P").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (6,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(6, 20)); } [Fact] public void AutoWithInitializerInStruct2() { var text = @"struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int i) : this() {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "P").WithArguments("struct field initializers", "10.0").WithLocation(3, 16), // (5,20): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "R").WithArguments("struct field initializers", "10.0").WithLocation(5, 20)); var global = comp.GlobalNamespace; var s = global.GetTypeMember("S"); var p = s.GetMember<PropertySymbol>("P"); Assert.NotNull(p.GetMethod); Assert.NotNull(p.SetMethod); var q = s.GetMember<PropertySymbol>("Q"); Assert.NotNull(q.GetMethod); Assert.Null(q.SetMethod); var r = s.GetMember<PropertySymbol>("R"); Assert.NotNull(r.GetMethod); Assert.Null(r.SetMethod); } [Fact] public void AutoInitializerInInterface() { var text = @"interface I { int P { get; } = 0; }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (3,9): error CS8053: Instance properties in interfaces cannot have initializers. // int P { get; } = 0; Diagnostic(ErrorCode.ERR_InstancePropertyInitializerInInterface, "P").WithArguments("I.P").WithLocation(3, 9)); } [Fact] public void AutoNoSetOrInitializer() { var text = @"class C { public int P { get; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics(); } [Fact] public void AutoNoGet() { var text = @"class C { public int P { set {} } public int Q { set; } = 0; public int R { set; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (4,20): error CS8051: Auto-implemented properties must have get accessors. // public int Q { set; } = 0; Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C.Q.set").WithLocation(4, 20), // (5,20): error CS8051: Auto-implemented properties must have get accessors. // public int R { set; } Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C.R.set").WithLocation(5, 20)); } [Fact] public void AutoRefReturn() { var text = @"class C { public ref int P { get; } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (3,20): error CS8080: Auto-implemented properties cannot return by reference // public ref int P { get; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "P").WithArguments("C.P").WithLocation(3, 20)); } [Fact] public void AutoRefReadOnlyReturn() { var text = @" class C { public ref readonly int P1 { get; set; } }"; var comp = CreateCompilation(text).VerifyDiagnostics( // (4,29): error CS8145: Auto-implemented properties cannot return by reference // public ref readonly int P1 { get; set; } Diagnostic(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, "P1").WithArguments("C.P1").WithLocation(4, 29), // (4,39): error CS8147: Properties which return by reference cannot have set accessors // public ref readonly int P1 { get; set; } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.P1.set").WithLocation(4, 39)); } [WorkItem(542745, "DevDiv")] [WorkItem(542745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542745")] [Fact()] public void AutoImplementedAccessorNotImplicitlyDeclared() { var text = @" class A { abstract int P { get; set; } internal int P2 { get; set; } } interface I { int Q {get; set; } } "; // Per design meeting (see bug 11253), in C#, if there's a "get" or "set" written, // then IsImplicitDeclared should be false. var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var i = global.GetTypeMembers("I", 0).Single(); var p = a.GetMembers("P").SingleOrDefault() as PropertySymbol; Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.False(p.SetMethod.IsImplicitlyDeclared); p = a.GetMembers("P2").SingleOrDefault() as PropertySymbol; Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.False(p.SetMethod.IsImplicitlyDeclared); var q = i.GetMembers("Q").SingleOrDefault() as PropertySymbol; Assert.False(q.GetMethod.IsImplicitlyDeclared); Assert.False(q.SetMethod.IsImplicitlyDeclared); } [WorkItem(542746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542746")] [Fact] public void AutoImplementedBackingFieldLocation() { var text = @" class C { int Prop { get; set; } struct S { string Prop { get; set; } } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var type01 = global.GetTypeMembers("C").Single(); var type02 = type01.GetTypeMembers("S").Single(); var mems = type01.GetMembers(); FieldSymbol backField = null; // search but not use internal backfield name // there is exact ONE field symbol in this test foreach (var m in mems) { if (m.Kind == SymbolKind.Field) { backField = m as FieldSymbol; break; } } // Back field location should be same as Property Assert.NotNull(backField); Assert.False(backField.Locations.IsEmpty); var prop = type01.GetMembers("Prop").Single() as PropertySymbol; Assert.Equal(prop.Locations.Length, backField.Locations.Length); Assert.Equal(prop.Locations[0].ToString(), backField.Locations[0].ToString()); // ------------------------------------- mems = type02.GetMembers(); backField = null; // search but not use internal backfield name // there is exact ONE field symbol in this test foreach (var m in mems) { if (m.Kind == SymbolKind.Field) { backField = m as FieldSymbol; break; } } // Back field location should be same as Property Assert.NotNull(backField); Assert.False(backField.Locations.IsEmpty); prop = type02.GetMembers("Prop").Single() as PropertySymbol; Assert.Equal(prop.Locations.Length, backField.Locations.Length); Assert.Equal(prop.Locations[0].ToString(), backField.Locations[0].ToString()); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void EventEscapedIdentifier() { var text = @" delegate void @out(); class C1 { @out @in { get; }; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(); PropertySymbol ein = (PropertySymbol)c1.GetMembers("in").Single(); Assert.Equal("in", ein.Name); Assert.Equal("C1.@in", ein.ToString()); NamedTypeSymbol dout = (NamedTypeSymbol)ein.Type; Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [ClrOnlyFact] public void PropertyNonDefaultAccessorNames() { var source = @" class Program { static void M(Valid i) { i.Instance = 0; System.Console.Write(""{0}"", i.Instance); } static void Main() { Valid.Static = 0; System.Console.Write(""{0}"", Valid.Static); } } "; var compilation = CompileAndVerify(source, new[] { s_propertiesDll }, expectedOutput: "0"); compilation.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""void Valid.Static.set"" IL_0006: ldstr ""{0}"" IL_000b: call ""int Valid.Static.get"" IL_0010: box ""int"" IL_0015: call ""void System.Console.Write(string, object)"" IL_001a: ret } "); } [WorkItem(528633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528633")] [Fact] public void MismatchedAccessorTypes() { var source = @" class Program { static void M(Mismatched i) { i.Instance = 0; System.Console.Write(""{0}"", i.Instance); } static void N(Signatures i) { i.StaticAndInstance = 0; i.GetUsedAsSet = 0; } static void Main() { Mismatched.Static = 0; System.Console.Write(""{0}"", Mismatched.Static); } } "; var compilation = CompileWithCustomPropertiesAssembly(source); var actualErrors = compilation.GetDiagnostics(); compilation.VerifyDiagnostics( // (6,11): error CS1061: 'Mismatched' does not contain a definition for 'Instance' and no extension method 'Instance' accepting a first argument of type 'Mismatched' could be found (are you missing a using directive or an assembly reference?) // i.Instance = 0; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Instance").WithArguments("Mismatched", "Instance"), // (7,39): error CS1061: 'Mismatched' does not contain a definition for 'Instance' and no extension method 'Instance' accepting a first argument of type 'Mismatched' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write("{0}", i.Instance); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Instance").WithArguments("Mismatched", "Instance"), // (11,11): error CS1545: Property, indexer, or event 'Signatures.StaticAndInstance' is not supported by the language; try directly calling accessor methods 'Signatures.GoodStatic.get' or 'Signatures.GoodInstance.set' // i.StaticAndInstance = 0; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "StaticAndInstance").WithArguments("Signatures.StaticAndInstance", "Signatures.GoodStatic.get", "Signatures.GoodInstance.set"), // (12,11): error CS1545: Property, indexer, or event 'Signatures.GetUsedAsSet' is not supported by the language; try directly calling accessor methods 'Signatures.GoodInstance.get' or 'Signatures.GoodInstance.get' // i.GetUsedAsSet = 0; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "GetUsedAsSet").WithArguments("Signatures.GetUsedAsSet", "Signatures.GoodInstance.get", "Signatures.GoodInstance.get"), // (16,20): error CS0117: 'Mismatched' does not contain a definition for 'Static' // Mismatched.Static = 0; Diagnostic(ErrorCode.ERR_NoSuchMember, "Static").WithArguments("Mismatched", "Static"), // (17,48): error CS0117: 'Mismatched' does not contain a definition for 'Static' // System.Console.Write("{0}", Mismatched.Static); Diagnostic(ErrorCode.ERR_NoSuchMember, "Static").WithArguments("Mismatched", "Static")); } /// <summary> /// Properties should refer to methods /// in the type members collection. /// </summary> [ClrOnlyFact] public void MethodsAndAccessorsSame() { var source = @"class A { public static object P { get; set; } public object Q { get; set; } } class B<T> { public static T P { get; set; } public T Q { get; set; } } class C : B<string> { } "; Action<ModuleSymbol> validator = module => { // Non-generic type. var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); Assert.Equal(0, type.TypeParameters.Length); Assert.Same(type, type.ConstructedFrom); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("P")); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("Q")); // Generic type. type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("B"); Assert.Equal(1, type.TypeParameters.Length); Assert.Same(type, type.ConstructedFrom); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("P")); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("Q")); // Generic type with parameter substitution. type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").BaseType(); Assert.Equal(1, type.TypeParameters.Length); Assert.NotSame(type, type.ConstructedFrom); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("P")); VerifyMethodsAndAccessorsSame(type, type.GetMember<PropertySymbol>("Q")); }; CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator); } private void VerifyMethodsAndAccessorsSame(NamedTypeSymbol type, PropertySymbol property) { VerifyMethodAndAccessorSame(type, property, property.GetMethod); VerifyMethodAndAccessorSame(type, property, property.SetMethod); } private void VerifyMethodAndAccessorSame(NamedTypeSymbol type, PropertySymbol property, MethodSymbol accessor) { Assert.NotNull(accessor); Assert.Equal(type, accessor.ContainingType); Assert.Equal(type, accessor.ContainingSymbol); var method = type.GetMembers(accessor.Name).Single(); Assert.NotNull(method); Assert.Equal(accessor, method); Assert.True(accessor.MethodKind == MethodKind.PropertyGet || accessor.MethodKind == MethodKind.PropertySet, "Accessor kind: " + accessor.MethodKind.ToString()); Assert.Equal(accessor.AssociatedSymbol, property); } [WorkItem(538789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538789")] [Fact] public void NoAccessors() { var source = @" class Program { static void M(NoAccessors i) { i.Instance = NoAccessors.Static; } } "; var compilation = CompileWithCustomPropertiesAssembly(source); var actualErrors = compilation.GetDiagnostics(); DiagnosticsUtils.VerifyErrorCodes(actualErrors, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 6, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMember, Line = 6, Column = 34 }); var type = (PENamedTypeSymbol)compilation.GlobalNamespace.GetMembers("NoAccessors").Single(); // Methods are available. Assert.NotNull(type.GetMembers("StaticMethod").SingleOrDefault()); Assert.NotNull(type.GetMembers("InstanceMethod").SingleOrDefault()); Assert.Equal(2, type.GetMembers().OfType<MethodSymbol>().Count()); // Properties are not available. Assert.Null(type.GetMembers("Static").SingleOrDefault()); Assert.Null(type.GetMembers("Instance").SingleOrDefault()); Assert.Equal(0, type.GetMembers().OfType<PropertySymbol>().Count()); } /// <summary> /// Calling bogus methods directly should be allowed. /// </summary> [ClrOnlyFact] public void CallMethodsDirectly() { var source = @" class Program { static void M(Mismatched i) { i.InstanceBoolSet(false); System.Console.Write(""{0}"", i.InstanceInt32Get()); } static void Main() { Mismatched.StaticBoolSet(false); System.Console.Write(""{0}"", Mismatched.StaticInt32Get()); } } "; var compilation = CompileAndVerify(source, new[] { s_propertiesDll }, expectedOutput: "0"); compilation.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""void Mismatched.StaticBoolSet(bool)"" IL_0006: ldstr ""{0}"" IL_000b: call ""int Mismatched.StaticInt32Get()"" IL_0010: box ""int"" IL_0015: call ""void System.Console.Write(string, object)"" IL_001a: ret } "); } [ClrOnlyFact] public void MethodsReferencedInMultipleProperties() { var source = @" class Program { static void M(Signatures i) { i.GoodInstance = 0; System.Console.Write(""{0}"", i.GoodInstance); } static void Main() { Signatures.GoodStatic = 0; System.Console.Write(""{0}"", Signatures.GoodStatic); } } "; var verifier = CompileAndVerify(source, new[] { s_propertiesDll }, expectedOutput: "0"); verifier.VerifyIL("Program.Main", @"{ // Code size 27 (0x1b) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""void Signatures.GoodStatic.set"" IL_0006: ldstr ""{0}"" IL_000b: call ""int Signatures.GoodStatic.get"" IL_0010: box ""int"" IL_0015: call ""void System.Console.Write(string, object)"" IL_001a: ret } "); var type = (PENamedTypeSymbol)verifier.Compilation.GlobalNamespace.GetMembers("Signatures").Single().GetSymbol(); // Valid static property, property with signature that does not match accessors, // and property with accessors that do not match each other. var goodStatic = (PEPropertySymbol)type.GetMembers("GoodStatic").Single(); var badStatic = (PEPropertySymbol)type.GetMembers("BadStatic").Single(); var mismatchedStatic = (PEPropertySymbol)type.GetMembers("MismatchedStatic").Single(); Assert.False(goodStatic.MustCallMethodsDirectly); Assert.True(badStatic.MustCallMethodsDirectly); Assert.True(mismatchedStatic.MustCallMethodsDirectly); VerifyAccessor(goodStatic.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(goodStatic.SetMethod, goodStatic, MethodKind.PropertySet); VerifyAccessor(badStatic.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(badStatic.SetMethod, goodStatic, MethodKind.PropertySet); VerifyAccessor(mismatchedStatic.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(mismatchedStatic.SetMethod, null, MethodKind.Ordinary); // Valid instance property, property with signature that does not match accessors, // and property with accessors that do not match each other. var goodInstance = (PEPropertySymbol)type.GetMembers("GoodInstance").Single(); var badInstance = (PEPropertySymbol)type.GetMembers("BadInstance").Single(); var mismatchedInstance = (PEPropertySymbol)type.GetMembers("MismatchedInstance").Single(); Assert.False(goodInstance.MustCallMethodsDirectly); Assert.True(badInstance.MustCallMethodsDirectly); Assert.True(mismatchedInstance.MustCallMethodsDirectly); VerifyAccessor(goodInstance.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(goodInstance.SetMethod, goodInstance, MethodKind.PropertySet); VerifyAccessor(badInstance.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(badInstance.SetMethod, goodInstance, MethodKind.PropertySet); VerifyAccessor(mismatchedInstance.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(mismatchedInstance.SetMethod, null, MethodKind.Ordinary); // Mix of static and instance accessors. var staticAndInstance = (PEPropertySymbol)type.GetMembers("StaticAndInstance").Single(); VerifyAccessor(staticAndInstance.GetMethod, goodStatic, MethodKind.PropertyGet); VerifyAccessor(staticAndInstance.SetMethod, goodInstance, MethodKind.PropertySet); Assert.True(staticAndInstance.MustCallMethodsDirectly); // Property with get and set accessors both referring to the same get method. var getUsedAsSet = (PEPropertySymbol)type.GetMembers("GetUsedAsSet").Single(); VerifyAccessor(getUsedAsSet.GetMethod, goodInstance, MethodKind.PropertyGet); VerifyAccessor(getUsedAsSet.SetMethod, goodInstance, MethodKind.PropertyGet); Assert.True(getUsedAsSet.MustCallMethodsDirectly); } private void VerifyAccessor(MethodSymbol accessor, PEPropertySymbol associatedProperty, MethodKind methodKind) { Assert.NotNull(accessor); Assert.Equal(accessor.AssociatedSymbol, associatedProperty); Assert.Equal(accessor.MethodKind, methodKind); if (associatedProperty != null) { var method = (methodKind == MethodKind.PropertyGet) ? associatedProperty.GetMethod : associatedProperty.SetMethod; Assert.Equal(accessor, method); } } /// <summary> /// Support mixes of family and assembly. /// </summary> [Fact] public void FamilyAssembly() { var source = @" class Program { static void Main() { System.Console.Write(""{0}"", Signatures.StaticGet()); } } "; var compilation = CompileWithCustomPropertiesAssembly(source, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var type = (PENamedTypeSymbol)compilation.GlobalNamespace.GetMembers("FamilyAssembly").Single(); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyGetAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.Protected, Accessibility.Internal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyGetFamilyOrAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.Protected, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyGetFamilyAndAssemblySetStatic").Single(), Accessibility.Protected, Accessibility.Protected, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("AssemblyGetFamilyOrAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.Internal, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("AssemblyGetFamilyAndAssemblySetStatic").Single(), Accessibility.Internal, Accessibility.Internal, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyOrAssemblyGetFamilyOrAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyOrAssemblyGetFamilyAndAssemblySetStatic").Single(), Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyAndAssemblyGetFamilyAndAssemblySetStatic").Single(), Accessibility.ProtectedAndInternal, Accessibility.ProtectedAndInternal, Accessibility.ProtectedAndInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyAndAssemblyGetOnlyInstance").Single(), Accessibility.ProtectedAndInternal, Accessibility.ProtectedAndInternal, Accessibility.NotApplicable); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyOrAssemblySetOnlyInstance").Single(), Accessibility.ProtectedOrInternal, Accessibility.NotApplicable, Accessibility.ProtectedOrInternal); VerifyAccessibility( (PEPropertySymbol)type.GetMembers("FamilyAndAssemblyGetFamilyOrAssemblySetInstance").Single(), Accessibility.ProtectedOrInternal, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal); } // Property and getter with void type. Dev10 treats this as a valid // property. Would it be better to treat the property as invalid? [Fact] public void VoidPropertyAndAccessorType() { const string ilSource = @" .class public A { .method public static void get_P() { ret } .property void P() { .get void A::get_P() } .method public instance void get_Q() { ret } .property void Q() { .get instance void A::get_Q() } } "; const string cSharpSource = @" class C { static void M(A x) { N(A.P); N(x.Q); } static void N(object o) { } }"; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgType, "A.P").WithArguments("1", "void", "object"), Diagnostic(ErrorCode.ERR_BadArgType, "x.Q").WithArguments("1", "void", "object")); } /// <summary> /// Properties where the property and accessor signatures differ by /// modopt only should be supported (as in the native compiler). /// </summary> [ClrOnlyFact] public void SignaturesDifferByModOptsOnly() { const string ilSource = @".class public A { } .class public B { } .class public C { .method public instance int32 get_noopt() { ldc.i4.0 ret } .method public instance int32 modopt(A) get_returnopt() { ldc.i4.0 ret } .method public instance void set_noopt(int32 val) { ret } .method public instance void set_argopt(int32 modopt(A) val) { ret } .method public instance void modopt(A) set_returnopt(int32 val) { ret } // Modifier on property but not accessors. .property int32 modopt(A) P1() { .get instance int32 C::get_noopt() .set instance void C::set_noopt(int32) } // Modifier on accessors but not property. .property int32 P2() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_argopt(int32 modopt(A)) } // Modifier on getter only. .property int32 P3() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_noopt(int32) } // Modifier on setter only. .property int32 P4() { .get instance int32 C::get_noopt() .set instance void C::set_argopt(int32 modopt(A)) } // Modifier on setter return type. .property int32 P5() { .get instance int32 C::get_noopt() .set instance void modopt(A) C::set_returnopt(int32) } // Modifier on property and different modifier on accessors. .property int32 modopt(B) P6() { .get instance int32 modopt(A) C::get_returnopt() .set instance void C::set_argopt(int32 modopt(A)) } }"; const string cSharpSource = @"class D { static void M(C c) { c.P1 = c.P1; c.P2 = c.P2; c.P3 = c.P3; c.P4 = c.P4; c.P5 = c.P5; c.P6 = c.P6; } }"; CompileWithCustomILSource(cSharpSource, ilSource); } [WorkItem(538956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538956")] [ClrOnlyFact] public void PropertyAccessorDoesNotHideMethod() { const string cSharpSource = @" interface IA { string get_Goo(); } interface IB : IA { int Goo { get; } } class Program { static void Main() { IB x = null; string s = x.get_Goo().ToLower(); } } "; CompileWithCustomILSource(cSharpSource, null); } [WorkItem(538956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538956")] [ClrOnlyFact] public void PropertyAccessorDoesNotConflictWithMethod() { const string cSharpSource = @" interface IA { string get_Goo(); } interface IB { int Goo { get; } } interface IC : IA, IB { } class Program { static void Main() { IC x = null; string s = x.get_Goo().ToLower(); } } "; CompileWithCustomILSource(cSharpSource, null); } [WorkItem(538956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538956")] [Fact] public void PropertyAccessorCannotBeCalledAsMethod() { const string cSharpSource = @" interface I { int Goo { get; } } class Program { static void Main() { I x = null; string s = x.get_Goo(); } } "; CreateCompilation(cSharpSource).VerifyDiagnostics( // (9,22): error CS0571: 'I.Goo.get': cannot explicitly call operator or accessor // string s = x.get_Goo(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Goo").WithArguments("I.Goo.get")); } [WorkItem(538992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538992")] [Fact] public void CanNotAccessPropertyThroughParenthesizedType() { const string cSharpSource = @" class Program { static void Main() { (Program).X = 1; } static int X { get; set; } } "; CreateCompilation(cSharpSource).VerifyDiagnostics( // (6,10): error CS0119: 'Program' is a type, which is not valid in the given context // (Program).X = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type")); } [ClrOnlyFact] public void CanReadInstancePropertyWithStaticGetterAsStatic() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property instance int32 Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [Fact] public void CanNotReadInstancePropertyWithStaticGetterAsInstance() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property instance int32 Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { A a = null; int x = a.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (5,13): error CS0176: Member 'A.Goo' cannot be accessed with an instance reference; qualify it with a type name instead // int x = a.Goo; Diagnostic(ErrorCode.ERR_ObjectProhibited, "a.Goo").WithArguments("A.Goo")); } [WorkItem(527658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527658")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS1546ERR_BindToBogusProp1_PropertyWithPinnedModifierIsBogus() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property instance int32 pinned Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,18): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // object x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(538850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538850")] [Fact] public void PropertyWithMismatchedReturnTypeOfGetterIsBogus() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property string Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,18): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // object x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(527659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527659")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void PropertyWithCircularReturnTypeIsNotSupported() { const string ilSource = @" .class public E extends E { } .class public A { .method public static class E get_Goo() { ldnull throw } .property class E Goo() { .get class E A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; B y = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (5,11): error CS0268: Imported type 'E' is invalid. It contains a circular base type dependency. // B y = A.Goo; Diagnostic(ErrorCode.ERR_ImportedCircularBase, "A.Goo").WithArguments("E", "E"), // (5,11): error CS0029: Cannot implicitly convert type 'E' to 'B' // B y = A.Goo; Diagnostic(ErrorCode.ERR_NoImplicitConv, "A.Goo").WithArguments("E", "B") ); // Dev10 errors: // error CS0268: Imported type 'E' is invalid. It contains a circular base type dependency. // error CS0570: 'A.Goo' is not supported by the language } [WorkItem(527664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527664")] [Fact(Skip = "527664")] public void PropertyWithOpenGenericTypeAsTypeArgumentOfReturnTypeIsNotSupported() { const string ilSource = @" .class public E<T> { } .class public A { .method public static class E<class E> get_Goo() { ldnull throw } .property class E<class E> Goo() { .get class E<class E> A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); // TODO: check diagnostics when it is implemented } [WorkItem(527657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527657")] [Fact(Skip = "527657")] public void Dev10IgnoresSentinelInPropertySignature() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo(...) { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadModOptProperty() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(int32) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [WorkItem(527660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527660")] [Fact(Skip = "527660")] public void CanReadPropertyWithModOptInBaseClassOfReturnType() { const string ilSource = @" .class public E extends class [mscorlib]System.Collections.Generic.List`1<int32> modopt(int8) { } .class public A { .method public static class E get_Goo() { ldnull throw } .property class E Goo() { .get class E A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyOfArrayTypeWithModOptElement() { const string ilSource = @" .class public A { .method public static int32 modopt(int32)[] get_Goo() { ldnull throw } .property int32 modopt(int32)[] Goo() { .get int32 modopt(int32)[] A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int[] x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadModOptPropertyWithNonModOptGetter() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property int32 modopt(int32) Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [WorkItem(527656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527656")] [Fact(Skip = "527656")] public void CanReadNonModOptPropertyWithOpenGenericModOptGetter() { const string ilSource = @" .class public A { .method public static int32 modopt(class [mscorlib]System.IComparable`1) get_Goo() { ldnull throw } .property int32 Goo() { .get int32 modopt(class [mscorlib]System.IComparable`1) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadNonModOptPropertyWithModOptGetter() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CompileWithCustomILSource(cSharpSource, ilSource); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadModOptPropertyWithDifferentModOptGetter() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(string) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics(); } [WorkItem(538845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538845")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyWithMultipleAndNestedModOpts() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(int8) modopt(native int modopt(uint8)*[] modopt(void)) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,15): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // int x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyWithModReqsNestedWithinModOpts() { const string ilSource = @" .class public A { .method public static int32 modopt(int32) get_Goo() { ldnull throw } .property int32 modopt(class [mscorlib]System.IComparable`1<method void*()[]> modreq(bool)) Goo() { .get int32 modopt(int32) A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { int x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,15): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // int x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(538846, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538846")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanNotReadPropertyWithModReq() { const string ilSource = @" .class public A { .method public static int32 get_Goo() { ldnull throw } .property int32 modreq(int8) Goo() { .get int32 A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,18): error CS1546: Property, indexer, or event 'A.Goo' is not supported by the language; try directly calling accessor method 'A.get_Goo()' // object x = A.Goo; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "Goo").WithArguments("A.Goo", "A.get_Goo()")); } [WorkItem(527662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527662")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CanReadPropertyWithModReqInBaseClassOfReturnType() { const string ilSource = @" .class public E extends class [mscorlib]System.Collections.Generic.List`1<int32 modreq(int8)[]> { } .class public A { .method public static class E get_Goo() { ldnull throw } .property class E Goo() { .get class E A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics(); } [WorkItem(538787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538787")] [Fact] public void CanNotReadPropertyOfUnsupportedType() { const string ilSource = @" .class public auto ansi beforefieldinit Indexers extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Item')} .method public hidebysig specialname instance int32 get_Item(string modreq(int16) x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Item(string modreq(int16)) { .get instance int32 Indexers::get_Item(string modreq(int16)) } } // end of class Indexers "; const string cSharpSource = @" class C { static void Main() { object goo = new Indexers()[null]; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,22): error CS1546: Property, indexer, or event 'Indexers.this[string]' is not supported by the language; try directly calling accessor method 'Indexers.get_Item(string)' // object goo = new Indexers()[null]; Diagnostic(ErrorCode.ERR_BindToBogusProp1, "new Indexers()[null]").WithArguments("Indexers.this[string]", "Indexers.get_Item(string)").WithLocation(4, 22)); } [WorkItem(538791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538791")] [Fact] public void CanNotReadAmbiguousProperty() { const string ilSource = @" .class public B { .method public instance void .ctor() { ldarg.0 call instance void class System.Object::.ctor() ret } .method public static int32 get_Goo() { ldnull throw } .method public static int32[] get_Goo() { ldnull throw } .property int32 Goo() { .get int32 B::get_Goo() } .property int32[] Goo() { .get int32[] B::get_Goo() } } "; const string cSharpSource = @" class C { static void Main() { object goo = B.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,24): error CS0229: Ambiguity between 'B.Goo' and 'B.Goo' // object goo = B.Goo; Diagnostic(ErrorCode.ERR_AmbigMember, "Goo").WithArguments("B.Goo", "B.Goo")); } [Fact] public void VoidReturningPropertyHidesMembersFromBase() { const string ilSource = @" .class public B { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo() { .get int32 B::get_Goo() } } .class public A extends B { .method public static void get_Goo() { ldnull throw } .property void Goo() { .get void A::get_Goo() } } "; const string cSharpSource = @" class B { static void Main() { object x = A.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,16): error CS0029: Cannot implicitly convert type 'void' to 'object' // object x = A.Goo; Diagnostic(ErrorCode.ERR_NoImplicitConv, "A.Goo").WithArguments("void", "object")); } [WorkItem(527663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527663")] [Fact] public void CanNotReadPropertyFromAmbiguousGenericClass() { const string ilSource = @" .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '09f9df97-a228-4ca4-9b71-151909f205e6' { } .class public A`1<T> { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo() { .get int32 A`1::get_Goo() } } .class public A<T> { .method public static int32 get_Goo() { ldnull throw } .property int32 Goo() { .get int32 A::get_Goo() } } "; var ref0 = CompileIL(ilSource, prependDefaultHeader: false); const string cSharpSource = @" class B { static void Main() { object x = A<int>.Goo; } } "; CreateCompilation(cSharpSource, references: new[] { ref0 }).VerifyDiagnostics( // (4,16): error CS0433: The type 'A<T>' exists in both '09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and '09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // object x = A<int>.Goo; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "A<int>").WithArguments("09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "A<T>", "09f9df97-a228-4ca4-9b71-151909f205e6, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 16)); } [WorkItem(538789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538789")] [Fact] public void PropertyWithoutAccessorsIsBogus() { const string ilSource = @" .class public B { .method public instance void .ctor() { ldarg.0 call instance void class System.Object::.ctor() ret } .property int32 Goo() { } } "; const string cSharpSource = @" class C { static void Main() { object goo = B.Goo; } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (4,24): error CS0117: 'B' does not contain a definition for 'Goo' // object goo = B.Goo; Diagnostic(ErrorCode.ERR_NoSuchMember, "Goo").WithArguments("B", "Goo")); } [WorkItem(538946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538946")] [Fact] public void FalseAmbiguity() { const string text = @" interface IA { int Goo { get; } } interface IB<T> : IA { } interface IC : IB<int>, IB<string> { } class C { static void Main() { IC x = null; int y = x.Goo; } } "; var comp = CreateCompilation(Parse(text)); var diagnostics = comp.GetDiagnostics(); Assert.Empty(diagnostics); } [WorkItem(539320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539320")] [Fact] public void FalseWarningCS0109ForNewModifier() { const string text = @" class MyBase { public int MyProp { get { return 1; } } } class MyClass : MyBase { int intI = 0; new int MyProp { get { return intI; } set { intI = value; } } } "; var comp = CreateCompilation(Parse(text)); var diagnostics = comp.GetDiagnostics(); Assert.Empty(diagnostics); } [WorkItem(539319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539319")] [Fact] public void FalseErrorCS0103ForValueKeywordInExpImpl() { const string text = @" interface MyInter { int MyProp { get; set; } } class MyClass : MyInter { static int intI = 0; int MyInter.MyProp { get { return intI; } set { intI = value; } } } "; var comp = CreateCompilation(Parse(text)); var diagnostics = comp.GetDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void ExplicitInterfaceImplementationSimple() { string text = @" interface I { int P { get; set; } } class C : I { int I.P { get; set; } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceProperty = (PropertySymbol)@interface.GetMembers("P").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classProperty = (PropertySymbol)@class.GetMembers("I.P").Single(); CheckPropertyExplicitImplementation(@class, classProperty, interfaceProperty); } [Fact] public void ExplicitInterfaceImplementationRefReturn() { string text = @" interface I { ref int P { get; } } class C : I { int field; ref int I.P { get { return ref field; } } } "; var comp = CreateCompilationWithMscorlib45(text); var globalNamespace = comp.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceProperty = (PropertySymbol)@interface.GetMembers("P").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces().Contains(@interface)); var classProperty = (PropertySymbol)@class.GetMembers("I.P").Single(); Assert.Equal(RefKind.Ref, classProperty.RefKind); CheckRefPropertyExplicitImplementation(@class, classProperty, interfaceProperty); } [Fact] public void ExplicitInterfaceImplementationGeneric() { string text = @" namespace N { interface I<T> { T P { get; set; } } } class C : N.I<int> { int N.I<int>.P { get; set; } } "; var comp = CreateCompilation(Parse(text)); var globalNamespace = comp.GlobalNamespace; var @namespace = (NamespaceSymbol)globalNamespace.GetMembers("N").Single(); var @interface = (NamedTypeSymbol)@namespace.GetTypeMembers("I").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceProperty = (PropertySymbol)@interface.GetMembers("P").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var classProperty = (PropertySymbol)@class.GetMembers("N.I<System.Int32>.P").Single(); var substitutedInterface = @class.Interfaces().Single(); Assert.Equal(@interface, substitutedInterface.ConstructedFrom); var substitutedInterfaceProperty = (PropertySymbol)substitutedInterface.GetMembers("P").Single(); CheckPropertyExplicitImplementation(@class, classProperty, substitutedInterfaceProperty); } [Fact] public void ImportPropertiesWithParameters() { //TODO: To be implemented once indexer properties implemented } [WorkItem(539998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539998")] [ClrOnlyFact] public void ImportDefaultPropertiesWithParameters() { var source = @" class Program { public static WithParameterizedProps testClass = new WithParameterizedProps(); static void Main() { testClass.set_P(1, null); System.Console.Write(testClass.get_P(1)); testClass.set_P(""2"", null); System.Console.Write(testClass.get_P(""2"")); testClass.set_P(1, ""2"", null); System.Console.Write(testClass.get_P(1, ""2"")); } } "; var compilation = CreateCompilation( source, new[] { TestReferences.SymbolsTests.Properties }, TestOptions.ReleaseExe); Action<ModuleSymbol> validator = module => { var program = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Program"); var field = program.GetMember<FieldSymbol>("testClass"); var type = field.Type; // Non-generic type. //var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("WithParameterizedProps"); var getters = type.GetMembers("get_P").OfType<MethodSymbol>(); Assert.Equal(2, getters.Count(getter => getter.Parameters.Length == 1)); Assert.Equal(1, getters.Count(getter => getter.Parameters.Length == 2)); Assert.True(getters.Any(getter => getter.Parameters[0].Type.SpecialType == SpecialType.System_Int32)); Assert.True(getters.Any(getter => getter.Parameters[0].Type.SpecialType == SpecialType.System_String)); Assert.True(getters.Any(getter => getter.Parameters.Length == 2 && getter.Parameters[0].Type.SpecialType == SpecialType.System_Int32 && getter.Parameters[1].Type.SpecialType == SpecialType.System_String)); }; // TODO: it would be nice to validate the emitted symbols, but CompileAndVerify currently has a limitation // where it won't pick up the referenced assemblies from the compilation when it creates the ModuleSymbol // for the emitted assembly (i.e. WithParameterizedProps will be missing). CompileAndVerify(compilation, sourceSymbolValidator: validator, /*symbolValidator: validator,*/ expectedOutput: "1221"); } [WorkItem(540342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540342")] [ClrOnlyFact] public void NoSequencePointsForAutoPropertyAccessors() { var text = @" class C { object P { get; set; } }"; CompileAndVerify(text).VerifyDiagnostics(); } [WorkItem(541688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541688")] [Fact] public void Simple2() { var text = @" using System; public class A : Attribute { public A X { get; set; } public A X { get; set; } } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var xs = a.GetMembers("X"); Assert.Equal(2, xs.Length); foreach (var x in xs) { Assert.Equal(a, (x as PropertySymbol).Type); // duplicate, but all the same. } var errors = comp.GetDeclarationDiagnostics(); var one = errors.Single(); Assert.Equal(ErrorCode.ERR_DuplicateNameInClass, (ErrorCode)one.Code); } [WorkItem(528769, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528769")] [Fact] public void IndexerGetSetParameterLocation() { string text = @"using System; class Test { public int this[int i] { get { return i; } set { } } } "; var comp = CreateCompilation(text); var globalNamespace = comp.SourceModule.GlobalNamespace; var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Test").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var accessor = @class.GetMembers("get_Item").Single() as MethodSymbol; Assert.Equal(1, accessor.Parameters.Length); var locs = accessor.Parameters[0].Locations; // i Assert.Equal(1, locs.Length); Assert.True(locs[0].IsInSource, "InSource"); accessor = @class.GetMembers("set_Item").Single() as MethodSymbol; Assert.Equal(2, accessor.Parameters.Length); // i locs = accessor.Parameters[0].Locations; Assert.Equal(1, locs.Length); Assert.True(locs[0].IsInSource, "InSource"); } [WorkItem(545682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545682")] [ClrOnlyFact] public void PropertyWithParametersHidingMethod01() { var source1 = @"Public Class A Public Shared Function P() As Object Return Nothing End Function Public Function Q() As Object Return Nothing End Function End Class Public Class B1 Inherits A Public Shared Shadows Property P As Object Public Shadows Property Q As Object End Class Public Class B2 Inherits A Public Shared Shadows ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property Public Shadows ReadOnly Property Q(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static void M(B1 b) { object o; o = B1.P; o = B1.P(); o = b.Q; o = b.Q(); } }"; var compilation2 = CompileAndVerify(source2, new[] { reference1 }); compilation2.VerifyDiagnostics(); compilation2.VerifyIL("C.M(B1)", @"{ // Code size 27 (0x1b) .maxstack 1 IL_0000: call ""object B1.P.get"" IL_0005: pop IL_0006: call ""object A.P()"" IL_000b: pop IL_000c: ldarg.0 IL_000d: callvirt ""object B1.Q.get"" IL_0012: pop IL_0013: ldarg.0 IL_0014: callvirt ""object A.Q()"" IL_0019: pop IL_001a: ret }"); var source3 = @"class C { static void M(B2 b) { object o; o = B2.P; o = B2.P(); o = b.Q; o = b.Q(); } }"; var compilation3 = CreateCompilation(source3, new[] { reference1 }); compilation3.VerifyDiagnostics( // (6,16): error CS0428: Cannot convert method group 'P' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "P").WithArguments("P", "object").WithLocation(6, 16), // (8,15): error CS0428: Cannot convert method group 'Q' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Q").WithArguments("Q", "object").WithLocation(8, 15)); } [ClrOnlyFact] public void PropertyWithParametersHidingMethod02() { var source1 = @"Public Class A Public ReadOnly Property P(x As Object, y As Object) As Object Get Return Nothing End Get End Property End Class Public Class B Inherits A Public Shadows ReadOnly Property P(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); // Property with parameters hiding property with parameters. var source2 = @"class C { static void M(B b) { object o; o = b.P; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,15): error CS1546: Property, indexer, or event 'B.P[object]' is not supported by the language; try directly calling accessor method 'B.get_P(object)' Diagnostic(ErrorCode.ERR_BindToBogusProp1, "P").WithArguments("B.P[object]", "B.get_P(object)").WithLocation(6, 15)); // Property with parameters and extension method. var source3 = @"class C { static void M(A a) { object o; o = a.P; } } static class E { internal static object P(this object o) { return null; } }"; var compilation3 = CreateCompilationWithMscorlib40AndSystemCore(source3, new[] { reference1 }); compilation3.VerifyDiagnostics( // (6,15): error CS0428: Cannot convert method group 'P' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "P").WithArguments("P", "object").WithLocation(6, 15)); } [ClrOnlyFact] public void PropertyWithParametersHidingMethod03() { var source1 = @"Public Class A Public Function P1() As Object Return Nothing End Function Public Function P2() As Object Return Nothing End Function Public Function P3() As Object Return Nothing End Function Friend Function P4() As Object Return Nothing End Function Friend Function P5() As Object Return Nothing End Function Friend Function P6() As Object Return Nothing End Function Protected Function P7() As Object Return Nothing End Function Protected Function P8() As Object Return Nothing End Function Protected Function P9() As Object Return Nothing End Function End Class Public Class B Inherits A Public Shadows ReadOnly Property P1(o As Object) As Object Get Return Nothing End Get End Property Friend Shadows ReadOnly Property P2(o As Object) As Object Get Return Nothing End Get End Property Protected Shadows ReadOnly Property P3(o As Object) As Object Get Return Nothing End Get End Property Public Shadows ReadOnly Property P4(o As Object) As Object Get Return Nothing End Get End Property Friend Shadows ReadOnly Property P5(o As Object) As Object Get Return Nothing End Get End Property Protected Shadows ReadOnly Property P6(o As Object) As Object Get Return Nothing End Get End Property Public Shadows ReadOnly Property P7(o As Object) As Object Get Return Nothing End Get End Property Friend Shadows ReadOnly Property P8(o As Object) As Object Get Return Nothing End Get End Property Protected Shadows ReadOnly Property P9(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C : B { void M() { object o; o = this.P1(); o = this.P2(); o = this.P3(); o = this.P4(); o = this.P5(); o = this.P6(); o = this.P7(); o = this.P8(); o = this.P9(); } } class D { static void M(B b) { object o; o = b.P1(); o = b.P2(); o = b.P3(); o = b.P4(); o = b.P5(); o = b.P6(); o = b.P7(); o = b.P8(); o = b.P9(); } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (9,18): error CS1955: Non-invocable member 'B.P4[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P4").WithArguments("B.P4[object]").WithLocation(9, 18), // (10,18): error CS1061: 'C' does not contain a definition for 'P5' and no extension method 'P5' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P5").WithArguments("C", "P5").WithLocation(10, 18), // (11,18): error CS1955: Non-invocable member 'B.P6[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P6").WithArguments("B.P6[object]").WithLocation(11, 18), // (25,15): error CS1955: Non-invocable member 'B.P4[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P4").WithArguments("B.P4[object]").WithLocation(25, 15), // (26,15): error CS1061: 'B' does not contain a definition for 'P5' and no extension method 'P5' accepting a first argument of type 'B' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P5").WithArguments("B", "P5").WithLocation(26, 15), // (27,15): error CS1955: Non-invocable member 'B.P6[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P6").WithArguments("B.P6[object]").WithLocation(27, 15), // (28,15): error CS1955: Non-invocable member 'B.P7[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P7").WithArguments("B.P7[object]").WithLocation(28, 15), // (29,15): error CS0122: 'A.P8()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "P8").WithArguments("A.P8()").WithLocation(29, 15), // (30,15): error CS1955: Non-invocable member 'B.P9[object]' cannot be used like a method. Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P9").WithArguments("B.P9[object]").WithLocation(30, 15)); } [ClrOnlyFact] public void PropertyWithParametersAndOtherErrors() { var source1 = @"Public Class A Public Shared ReadOnly Property P1(o As Object) As Object Get Return Nothing End Get End Property Public ReadOnly Property P2(o As Object) As Object Get Return Nothing End Get End Property Protected ReadOnly Property P3(o As Object) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class B { static void M(A a) { object o; o = a.P1; o = A.P2; o = a.P3; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,15): error CS1546: Property, indexer, or event 'A.P1[object]' is not supported by the language; try directly calling accessor method 'A.get_P1(object)' Diagnostic(ErrorCode.ERR_BindToBogusProp1, "P1").WithArguments("A.P1[object]", "A.get_P1(object)").WithLocation(6, 15), // (7,15): error CS1546: Property, indexer, or event 'A.P2[object]' is not supported by the language; try directly calling accessor method 'A.get_P2(object)' Diagnostic(ErrorCode.ERR_BindToBogusProp1, "P2").WithArguments("A.P2[object]", "A.get_P2(object)").WithLocation(7, 15), // (8,15): error CS0122: 'A.P3[object]' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "P3").WithArguments("A.P3[object]").WithLocation(8, 15)); } [ClrOnlyFact] public void SubstitutedPropertyWithParameters() { var source1 = @"Public Class A(Of T) Public Property P(o As Object) As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class B { static void M(A<object> a) { object o; o = a.P; a.P = o; o = a.get_P(null); a.set_P(null, o); } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,15): error CS1545: Property, indexer, or event 'A<object>.P[object]' is not supported by the language; try directly calling accessor methods 'A<object>.get_P(object)' or 'A<object>.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P").WithArguments("A<object>.P[object]", "A<object>.get_P(object)", "A<object>.set_P(object, object)").WithLocation(6, 15), // (7,11): error CS1545: Property, indexer, or event 'A<object>.P[object]' is not supported by the language; try directly calling accessor methods 'A<object>.get_P(object)' or 'A<object>.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P").WithArguments("A<object>.P[object]", "A<object>.get_P(object)", "A<object>.set_P(object, object)").WithLocation(7, 11)); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void DifferentAccessorSignatures_ByRef() { var source1 = @".class public A1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object P(object) { .get instance object A1::get_P(object) .set instance void A1::set_P(object, object v) } } .class public A2 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object P(object) { .get instance object A2::get_P(object) .set instance void A2::set_P(object&, object v) } } .class public A3 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object P(object) { .get instance object A3::get_P(object) .set instance void A3::set_P(object, object& v) } } .class public A4 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object& P(object) { .get instance object& A4::get_P(object) .set instance void A4::set_P(object, object v) } } .class public A5 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object& P(object) { .get instance object& A5::get_P(object) .set instance void A5::set_P(object&, object v) } } .class public A6 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object& get_P(object i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object& P(object) { .get instance object& A6::get_P(object) .set instance void A6::set_P(object, object& v) } } .class public A7 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object i, object v) { ret } .property instance object P(object&) { .get instance object A7::get_P(object&) .set instance void A7::set_P(object, object v) } } .class public A8 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object& i, object v) { ret } .property instance object P(object&) { .get instance object A8::get_P(object&) .set instance void A8::set_P(object&, object v) } } .class public A9 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public instance object get_P(object& i) { ldnull ret } .method public instance void set_P(object i, object& v) { ret } .property instance object P(object&) { .get instance object A9::get_P(object&) .set instance void A9::set_P(object, object& v) } }"; var reference1 = CompileIL(source1); var source2 = @"class C { static void M(A1 _1, A2 _2, A3 _3, A4 _4, A5 _5, A6 _6, A7 _7, A8 _8, A9 _9) { object x = null; object y = null; _1[y] = _1[x]; _2[y] = _2[x]; _3[y] = _3[x]; _4[y] = _4[x]; _5[y] = _5[x]; _6[y] = _6[x]; _7[ref y] = _7[ref x]; _8[ref y] = _8[ref x]; _9[ref y] = _9[ref x]; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,9): error CS1545: Property, indexer, or event 'A2.this[object]' is not supported by the language; try directly calling accessor methods 'A2.get_P(object)' or 'A2.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_2[y]").WithArguments("A2.this[object]", "A2.get_P(object)", "A2.set_P(ref object, object)").WithLocation(8, 9), // (8,17): error CS1545: Property, indexer, or event 'A2.this[object]' is not supported by the language; try directly calling accessor methods 'A2.get_P(object)' or 'A2.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_2[x]").WithArguments("A2.this[object]", "A2.get_P(object)", "A2.set_P(ref object, object)").WithLocation(8, 17), // (9,9): error CS1545: Property, indexer, or event 'A3.this[object]' is not supported by the language; try directly calling accessor methods 'A3.get_P(object)' or 'A3.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_3[y]").WithArguments("A3.this[object]", "A3.get_P(object)", "A3.set_P(object, ref object)").WithLocation(9, 9), // (9,17): error CS1545: Property, indexer, or event 'A3.this[object]' is not supported by the language; try directly calling accessor methods 'A3.get_P(object)' or 'A3.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_3[x]").WithArguments("A3.this[object]", "A3.get_P(object)", "A3.set_P(object, ref object)").WithLocation(9, 17), // (10,9): error CS1545: Property, indexer, or event 'A4.this[object]' is not supported by the language; try directly calling accessor methods 'A4.get_P(object)' or 'A4.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_4[y]").WithArguments("A4.this[object]", "A4.get_P(object)", "A4.set_P(object, object)").WithLocation(10, 9), // (10,17): error CS1545: Property, indexer, or event 'A4.this[object]' is not supported by the language; try directly calling accessor methods 'A4.get_P(object)' or 'A4.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_4[x]").WithArguments("A4.this[object]", "A4.get_P(object)", "A4.set_P(object, object)").WithLocation(10, 17), // (11,9): error CS1545: Property, indexer, or event 'A5.this[object]' is not supported by the language; try directly calling accessor methods 'A5.get_P(object)' or 'A5.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_5[y]").WithArguments("A5.this[object]", "A5.get_P(object)", "A5.set_P(ref object, object)").WithLocation(11, 9), // (11,17): error CS1545: Property, indexer, or event 'A5.this[object]' is not supported by the language; try directly calling accessor methods 'A5.get_P(object)' or 'A5.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_5[x]").WithArguments("A5.this[object]", "A5.get_P(object)", "A5.set_P(ref object, object)").WithLocation(11, 17), // (12,9): error CS1545: Property, indexer, or event 'A6.this[object]' is not supported by the language; try directly calling accessor methods 'A6.get_P(object)' or 'A6.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_6[y]").WithArguments("A6.this[object]", "A6.get_P(object)", "A6.set_P(object, ref object)").WithLocation(12, 9), // (12,17): error CS1545: Property, indexer, or event 'A6.this[object]' is not supported by the language; try directly calling accessor methods 'A6.get_P(object)' or 'A6.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_6[x]").WithArguments("A6.this[object]", "A6.get_P(object)", "A6.set_P(object, ref object)").WithLocation(12, 17), // (13,9): error CS1545: Property, indexer, or event 'A7.this[ref object]' is not supported by the language; try directly calling accessor methods 'A7.get_P(ref object)' or 'A7.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_7[ref y]").WithArguments("A7.this[ref object]", "A7.get_P(ref object)", "A7.set_P(object, object)").WithLocation(13, 9), // (13,21): error CS1545: Property, indexer, or event 'A7.this[ref object]' is not supported by the language; try directly calling accessor methods 'A7.get_P(ref object)' or 'A7.set_P(object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_7[ref x]").WithArguments("A7.this[ref object]", "A7.get_P(ref object)", "A7.set_P(object, object)").WithLocation(13, 21), // (14,9): error CS1545: Property, indexer, or event 'A8.this[ref object]' is not supported by the language; try directly calling accessor methods 'A8.get_P(ref object)' or 'A8.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_8[ref y]").WithArguments("A8.this[ref object]", "A8.get_P(ref object)", "A8.set_P(ref object, object)").WithLocation(14, 9), // (14,21): error CS1545: Property, indexer, or event 'A8.this[ref object]' is not supported by the language; try directly calling accessor methods 'A8.get_P(ref object)' or 'A8.set_P(ref object, object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_8[ref x]").WithArguments("A8.this[ref object]", "A8.get_P(ref object)", "A8.set_P(ref object, object)").WithLocation(14, 21), // (15,9): error CS1545: Property, indexer, or event 'A9.this[ref object]' is not supported by the language; try directly calling accessor methods 'A9.get_P(ref object)' or 'A9.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_9[ref y]").WithArguments("A9.this[ref object]", "A9.get_P(ref object)", "A9.set_P(object, ref object)").WithLocation(15, 9), // (15,21): error CS1545: Property, indexer, or event 'A9.this[ref object]' is not supported by the language; try directly calling accessor methods 'A9.get_P(ref object)' or 'A9.set_P(object, ref object)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "_9[ref x]").WithArguments("A9.this[ref object]", "A9.get_P(ref object)", "A9.set_P(object, ref object)").WithLocation(15, 21)); } #region "helpers" private static void CheckPropertyExplicitImplementation(NamedTypeSymbol @class, PropertySymbol classProperty, PropertySymbol interfaceProperty) { var interfacePropertyGetter = interfaceProperty.GetMethod; Assert.NotNull(interfacePropertyGetter); var interfacePropertySetter = interfaceProperty.SetMethod; Assert.NotNull(interfacePropertySetter); Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single()); var classPropertyGetter = classProperty.GetMethod; Assert.NotNull(classPropertyGetter); var classPropertySetter = classProperty.SetMethod; Assert.NotNull(classPropertySetter); Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single()); Assert.Equal(interfacePropertySetter, classPropertySetter.ExplicitInterfaceImplementations.Single()); var typeDef = (Microsoft.Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverrides = typeDef.GetExplicitImplementationOverrides(context); Assert.Equal(2, explicitOverrides.Count()); Assert.True(explicitOverrides.All(@override => ReferenceEquals(@class, @override.ContainingType.GetInternalSymbol()))); // We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements var getterOverride = explicitOverrides.First(); Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name); var setterOverride = explicitOverrides.Last(); Assert.Equal(classPropertySetter, setterOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfacePropertySetter.ContainingType, setterOverride.ImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(interfacePropertySetter.Name, setterOverride.ImplementedMethod.Name); context.Diagnostics.Verify(); } private static void CheckRefPropertyExplicitImplementation(NamedTypeSymbol @class, PropertySymbol classProperty, PropertySymbol interfaceProperty) { var interfacePropertyGetter = interfaceProperty.GetMethod; Assert.NotNull(interfacePropertyGetter); var interfacePropertySetter = interfaceProperty.SetMethod; Assert.Null(interfacePropertySetter); Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single()); var classPropertyGetter = classProperty.GetMethod; Assert.NotNull(classPropertyGetter); var classPropertySetter = classProperty.SetMethod; Assert.Null(classPropertySetter); Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single()); var typeDef = (Microsoft.Cci.ITypeDefinition)@class.GetCciAdapter(); var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var explicitOverrides = typeDef.GetExplicitImplementationOverrides(context); Assert.Equal(1, explicitOverrides.Count()); Assert.True(explicitOverrides.All(@override => ReferenceEquals(@class, @override.ContainingType.GetInternalSymbol()))); // We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements var getterOverride = explicitOverrides.Single(); Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod.GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context).GetInternalSymbol()); Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name); } private static void VerifyAccessibility(PEPropertySymbol property, Accessibility propertyAccessibility, Accessibility getAccessibility, Accessibility setAccessibility) { Assert.Equal(property.DeclaredAccessibility, propertyAccessibility); Assert.False(property.MustCallMethodsDirectly); VerifyAccessorAccessibility(property.GetMethod, getAccessibility); VerifyAccessorAccessibility(property.SetMethod, setAccessibility); } private static void VerifyAccessorAccessibility(MethodSymbol accessor, Accessibility accessorAccessibility) { if (accessorAccessibility == Accessibility.NotApplicable) { Assert.Null(accessor); } else { Assert.NotNull(accessor); Assert.Equal(accessor.DeclaredAccessibility, accessorAccessibility); } } private CSharpCompilation CompileWithCustomPropertiesAssembly(string source, CSharpCompilationOptions options = null) { return CreateCompilation(source, new[] { s_propertiesDll }, options ?? TestOptions.ReleaseDll); } private static readonly MetadataReference s_propertiesDll = TestReferences.SymbolsTests.Properties; #endregion [ConditionalFact(typeof(DesktopOnly))] public void InteropDynamification() { var refSrc = @" using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""C35913A8-93FF-40B1-94AC-8F363CC17589"")] [ComImport] [Guid(""D541FDE7-A872-4AF7-8F68-DC9C2FC8DCC9"")] public interface IA { object P { get; } object M(); string P2 { get; } string M2(); }"; var refComp = CSharpCompilation.Create("DLL", options: TestOptions.DebugDll, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(refSrc) }, references: new MetadataReference[] { MscorlibRef }); var refData = AssemblyMetadata.CreateFromImage(refComp.EmitToArray()); var mdRef = refData.GetReference(embedInteropTypes: false); var comp = CreateCompilationWithMscorlib46("", new[] { mdRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.False(comp.ExternalReferences[1].Properties.EmbedInteropTypes); var ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); var iap = ia.GetMember<PropertySymbol>("P"); Assert.False(iap.Type.IsDynamic()); var iam = ia.GetMember<MethodSymbol>("M"); Assert.False(iam.ReturnType.IsDynamic()); var iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); var iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); var compRef = refComp.ToMetadataReference(embedInteropTypes: false); comp = CreateCompilationWithMscorlib46("", new[] { compRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.False(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.False(iap.Type.IsDynamic()); iam = ia.GetMember<MethodSymbol>("M"); Assert.False(iam.ReturnType.IsDynamic()); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); mdRef = refData.GetReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { mdRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.True(iap.Type.IsDynamic()); iam = ia.GetMember<MethodSymbol>("M"); Assert.True(iam.ReturnType.IsDynamic()); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); compRef = refComp.ToMetadataReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { compRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.True(iap.Type.IsDynamic()); iam = ia.GetMember<MethodSymbol>("M"); Assert.True(iam.ReturnType.IsDynamic()); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); Assert.Equal(2, comp.ExternalReferences.Length); refSrc = @" using System.Runtime.InteropServices; [assembly: PrimaryInteropAssembly(0, 0)] [assembly: Guid(""C35913A8-93FF-40B1-94AC-8F363CC17589"")] public interface IA { object P { get; } object M(); string P2 { get; } string M2(); }"; refComp = CSharpCompilation.Create("DLL", options: TestOptions.DebugDll, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(refSrc) }, references: new[] { MscorlibRef }); refData = AssemblyMetadata.CreateFromImage(refComp.EmitToArray()); mdRef = refData.GetReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { mdRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.Equal(SpecialType.System_Object, iap.Type.SpecialType); iam = ia.GetMember<MethodSymbol>("M"); Assert.Equal(SpecialType.System_Object, iam.ReturnType.SpecialType); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); compRef = refComp.ToMetadataReference(embedInteropTypes: true); comp = CreateCompilationWithMscorlib46("", new[] { compRef }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.ExternalReferences[1].Properties.EmbedInteropTypes); ia = comp.GetTypeByMetadataName("IA"); Assert.NotNull(ia); iap = ia.GetMember<PropertySymbol>("P"); Assert.Equal(SpecialType.System_Object, iap.Type.SpecialType); iam = ia.GetMember<MethodSymbol>("M"); Assert.Equal(SpecialType.System_Object, iam.ReturnType.SpecialType); iap2 = ia.GetMember<PropertySymbol>("P2"); Assert.Equal(SpecialType.System_String, iap2.Type.SpecialType); iam2 = ia.GetMember<MethodSymbol>("M2"); Assert.Equal(SpecialType.System_String, iam2.ReturnType.SpecialType); } private delegate void VerifyType(bool isWinMd, params string[] expectedMembers); /// <summary> /// When the output type is .winmdobj properties should emit put_Property methods instead /// of set_Property methods. /// </summary> [ClrOnlyFact] public void WinRtPropertySet() { const string libSrc = @"namespace Test { public sealed class C { public int a; public int A { get { return a; } set { a = value; } } } }"; Func<string[], Action<ModuleSymbol>> getValidator = expectedMembers => m => { var actualMembers = m.GlobalNamespace.GetMember<NamespaceSymbol>("Test"). GetMember<NamedTypeSymbol>("C").GetMembers().ToArray(); AssertEx.SetEqual(actualMembers.Select(s => s.Name), expectedMembers); }; VerifyType verify = (winmd, expected) => { var validator = getValidator(expected); // We should see the same members from both source and metadata var verifier = CompileAndVerify( libSrc, sourceSymbolValidator: validator, symbolValidator: validator, options: winmd ? TestOptions.ReleaseWinMD : TestOptions.ReleaseDll); verifier.VerifyDiagnostics(); }; // Test winmd verify(true, "a", "A", "get_A", "put_A", WellKnownMemberNames.InstanceConstructorName); // Test normal verify(false, "a", "A", "get_A", "set_A", WellKnownMemberNames.InstanceConstructorName); } /// <summary> /// Accessor type names that conflict should cause the appropriate diagnostic /// (i.e., set_ for dll, put_ for winmdobj) /// </summary> [Fact] public void WinRtPropertyAccessorNameConflict() { const string libSrc = @"namespace Test { public sealed class C { public int A { get; set; } public void put_A(int value) {} public void set_A(int value) {} } }"; var comp = CreateCompilation(libSrc, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (7,18): error CS0082: Type 'Test.C' already reserves a member called 'set_A' with the same parameter types // get; set; Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_A", "Test.C")); comp = CreateCompilation(libSrc, options: TestOptions.ReleaseWinMD); comp.VerifyDiagnostics( // (7,18): error CS0082: Type 'Test.C' already reserves a member called 'put_A' with the same parameter types // get; set; Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("put_A", "Test.C")); } [Fact] public void AutoPropertiesBeforeCSharp3() { var source = @" interface I { int P { get; set; } // Fine } abstract class A { public abstract int P { get; set; } // Fine } class C { public int P { get; set; } // Error } "; CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3)).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp2)).VerifyDiagnostics( // (14,16): error CS8023: Feature 'automatically implemented properties' is not available in C# 2. Please use language version 3 or greater. // public int P { get; set; } // Error Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion2, "P").WithArguments("automatically implemented properties", "3")); } [WorkItem(1073332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073332")] [ClrOnlyFact] public void Bug1073332_01() { var text = @" class Test { static int[] property { get; } = { 1, 2, 3 }; static void Main(string[] args) { foreach (var x in property) { System.Console.Write(x); } } } "; CompileAndVerify(text, expectedOutput: "123").VerifyDiagnostics(); } [WorkItem(1073332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073332")] [Fact] public void Bug1073332_02() { var text = @" unsafe class Test { int* property { get; } = stackalloc int[256]; static void Main(string[] args) { } } "; CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (4,30): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible. // int* property { get; } = stackalloc int[256]; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[256]").WithArguments("int", "int*").WithLocation(4, 30) ); } [Fact] public void RefPropertyWithoutGetter() { var source = @" class C { ref int P { set { } } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (4,17): error CS8080: Properties with by-reference returns must have a get accessor. // ref int P { set { } } Diagnostic(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void RefPropertyWithGetterAndSetter() { var source = @" class C { int field = 0; ref int P { get { return ref field; } set { } } } "; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,47): error CS8081: Properties with by-reference returns cannot have set accessors. // ref int P { get { return ref field; } set { } } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.P.set").WithLocation(5, 47)); } [Fact, WorkItem(4696, "https://github.com/dotnet/roslyn/issues/4696")] public void LangVersionAndReadonlyAutoProperty() { var source = @" public class Class1 { public Class1() { Prop1 = ""Test""; } public string Prop1 { get; } } abstract class Class2 { public abstract string Prop2 { get; } } interface I1 { string Prop3 { get; } } "; var comp = CreateCompilation(source, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); comp.GetDeclarationDiagnostics().Verify( // (9,19): error CS8026: Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater. // public string Prop1 { get; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "Prop1").WithArguments("readonly automatically implemented properties", "6").WithLocation(9, 19) ); } [Fact] public void StaticPropertyDoesNotRequireInstanceReceiver() { var source = @" class C { public static int P { get; } }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var property = compilation.GetMember<PropertySymbol>("C.P"); Assert.False(property.RequiresInstanceReceiver); } [Fact] public void InstancePropertyRequiresInstanceReceiver() { var source = @" class C { public int P { get; } }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var property = compilation.GetMember<PropertySymbol>("C.P"); Assert.True(property.RequiresInstanceReceiver); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/CodeFixes/FixAllOccurrences/IFixMultipleOccurrencesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeFixes { internal interface IFixMultipleOccurrencesService : IWorkspaceService { /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Document, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, CancellationToken cancellationToken); /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeFixes { internal interface IFixMultipleOccurrencesService : IWorkspaceService { /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Document, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, CancellationToken cancellationToken); /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../CodeFixesResources.resx"> <body> <trans-unit id="Add_blank_line_after_block"> <source>Add blank line after block</source> <target state="translated">在區塊後面新增空白行</target> <note /> </trans-unit> <trans-unit id="Add_both"> <source>Add both</source> <target state="translated">新增兩者</target> <note /> </trans-unit> <trans-unit id="Add_default_case"> <source>Add default case</source> <target state="translated">新增預設案例</target> <note /> </trans-unit> <trans-unit id="Add_file_header"> <source>Add file header</source> <target state="translated">新增檔案標頭</target> <note /> </trans-unit> <trans-unit id="Fix_Name_Violation_colon_0"> <source>Fix Name Violation: {0}</source> <target state="translated">修正名稱違規: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences_in"> <source>Fix all occurrences in</source> <target state="translated">修正所有出現之處於</target> <note /> </trans-unit> <trans-unit id="Remove_extra_blank_lines"> <source>Remove extra blank lines</source> <target state="translated">移除額外的空白行</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_assignment"> <source>Remove redundant assignment</source> <target state="translated">移除多餘的指派</target> <note /> </trans-unit> <trans-unit id="Suppress_or_Configure_issues"> <source>Suppress or Configure issues</source> <target state="translated">隱藏或設定問題</target> <note /> </trans-unit> <trans-unit id="Update_suppression_format"> <source>Update suppression format</source> <target state="translated">更新歸併格式</target> <note /> </trans-unit> <trans-unit id="Use_discard_underscore"> <source>Use discard '_'</source> <target state="translated">使用捨棄 '_’</target> <note /> </trans-unit> <trans-unit id="Use_discarded_local"> <source>Use discarded local</source> <target state="translated">使用捨棄的區域函式</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../CodeFixesResources.resx"> <body> <trans-unit id="Add_blank_line_after_block"> <source>Add blank line after block</source> <target state="translated">在區塊後面新增空白行</target> <note /> </trans-unit> <trans-unit id="Add_both"> <source>Add both</source> <target state="translated">新增兩者</target> <note /> </trans-unit> <trans-unit id="Add_default_case"> <source>Add default case</source> <target state="translated">新增預設案例</target> <note /> </trans-unit> <trans-unit id="Add_file_header"> <source>Add file header</source> <target state="translated">新增檔案標頭</target> <note /> </trans-unit> <trans-unit id="Fix_Name_Violation_colon_0"> <source>Fix Name Violation: {0}</source> <target state="translated">修正名稱違規: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences_in"> <source>Fix all occurrences in</source> <target state="translated">修正所有出現之處於</target> <note /> </trans-unit> <trans-unit id="Remove_extra_blank_lines"> <source>Remove extra blank lines</source> <target state="translated">移除額外的空白行</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_assignment"> <source>Remove redundant assignment</source> <target state="translated">移除多餘的指派</target> <note /> </trans-unit> <trans-unit id="Suppress_or_Configure_issues"> <source>Suppress or Configure issues</source> <target state="translated">隱藏或設定問題</target> <note /> </trans-unit> <trans-unit id="Update_suppression_format"> <source>Update suppression format</source> <target state="translated">更新歸併格式</target> <note /> </trans-unit> <trans-unit id="Use_discard_underscore"> <source>Use discard '_'</source> <target state="translated">使用捨棄 '_’</target> <note /> </trans-unit> <trans-unit id="Use_discarded_local"> <source>Use discarded local</source> <target state="translated">使用捨棄的區域函式</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameNodeSimplificationAnnotation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal class RenameNodeSimplificationAnnotation : RenameAnnotation { public TextSpan OriginalTextSpan { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal class RenameNodeSimplificationAnnotation : RenameAnnotation { public TextSpan OriginalTextSpan { get; set; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/Portable/Text/StringText.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Implementation of SourceText based on a <see cref="String"/> input /// </summary> internal sealed class StringText : SourceText { private readonly string _source; private readonly Encoding? _encodingOpt; internal StringText( string source, Encoding? encodingOpt, ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, ImmutableArray<byte> embeddedTextBlob = default(ImmutableArray<byte>)) : base(checksum, checksumAlgorithm, embeddedTextBlob) { RoslynDebug.Assert(source != null); _source = source; _encodingOpt = encodingOpt; } public override Encoding? Encoding => _encodingOpt; /// <summary> /// Underlying string which is the source of this <see cref="StringText"/>instance /// </summary> public string Source => _source; /// <summary> /// The length of the text represented by <see cref="StringText"/>. /// </summary> public override int Length => _source.Length; /// <summary> /// Returns a character at given position. /// </summary> /// <param name="position">The position to get the character from.</param> /// <returns>The character.</returns> /// <exception cref="ArgumentOutOfRangeException">When position is negative or /// greater than <see cref="Length"/>.</exception> public override char this[int position] { get { // NOTE: we are not validating position here as that would not // add any value to the range check that string accessor performs anyways. return _source[position]; } } /// <summary> /// Provides a string representation of the StringText located within given span. /// </summary> /// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception> public override string ToString(TextSpan span) { if (span.End > this.Source.Length) { throw new ArgumentOutOfRangeException(nameof(span)); } if (span.Start == 0 && span.Length == this.Length) { return this.Source; } return this.Source.Substring(span.Start, span.Length); } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { this.Source.CopyTo(sourceIndex, destination, destinationIndex, count); } public override void Write(TextWriter textWriter, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { if (span.Start == 0 && span.End == this.Length) { textWriter.Write(this.Source); } else { base.Write(textWriter, span, cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Implementation of SourceText based on a <see cref="String"/> input /// </summary> internal sealed class StringText : SourceText { private readonly string _source; private readonly Encoding? _encodingOpt; internal StringText( string source, Encoding? encodingOpt, ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, ImmutableArray<byte> embeddedTextBlob = default(ImmutableArray<byte>)) : base(checksum, checksumAlgorithm, embeddedTextBlob) { RoslynDebug.Assert(source != null); _source = source; _encodingOpt = encodingOpt; } public override Encoding? Encoding => _encodingOpt; /// <summary> /// Underlying string which is the source of this <see cref="StringText"/>instance /// </summary> public string Source => _source; /// <summary> /// The length of the text represented by <see cref="StringText"/>. /// </summary> public override int Length => _source.Length; /// <summary> /// Returns a character at given position. /// </summary> /// <param name="position">The position to get the character from.</param> /// <returns>The character.</returns> /// <exception cref="ArgumentOutOfRangeException">When position is negative or /// greater than <see cref="Length"/>.</exception> public override char this[int position] { get { // NOTE: we are not validating position here as that would not // add any value to the range check that string accessor performs anyways. return _source[position]; } } /// <summary> /// Provides a string representation of the StringText located within given span. /// </summary> /// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception> public override string ToString(TextSpan span) { if (span.End > this.Source.Length) { throw new ArgumentOutOfRangeException(nameof(span)); } if (span.Start == 0 && span.Length == this.Length) { return this.Source; } return this.Source.Substring(span.Start, span.Length); } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { this.Source.CopyTo(sourceIndex, destination, destinationIndex, count); } public override void Write(TextWriter textWriter, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { if (span.Start == 0 && span.End == this.Length) { textWriter.Write(this.Source); } else { base.Write(textWriter, span, cancellationToken); } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/Core/Portable/FileSystemExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public static class FileSystemExtensions { /// <summary> /// Emit the IL for the compilation into the specified stream. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="outputPath">Path of the file to which the compilation will be written.</param> /// <param name="pdbPath">Path of the file to which the compilation's debug info will be written. /// Also embedded in the output file. Null to forego PDB generation. /// </param> /// <param name="xmlDocPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="cancellationToken">To cancel the emit process.</param> /// <exception cref="ArgumentNullException">Compilation or path is null.</exception> /// <exception cref="ArgumentException">Path is empty or invalid.</exception> /// <exception cref="IOException">An error occurred while reading or writing a file.</exception> public static EmitResult Emit( this Compilation compilation, string outputPath, string? pdbPath = null, string? xmlDocPath = null, string? win32ResourcesPath = null, IEnumerable<ResourceDescription>? manifestResources = null, CancellationToken cancellationToken = default) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } using (var outputStream = FileUtilities.CreateFileStreamChecked(File.Create, outputPath, nameof(outputPath))) using (var pdbStream = (pdbPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, pdbPath, nameof(pdbPath)))) using (var xmlDocStream = (xmlDocPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, xmlDocPath, nameof(xmlDocPath)))) using (var win32ResourcesStream = (win32ResourcesPath == null ? null : FileUtilities.CreateFileStreamChecked(File.OpenRead, win32ResourcesPath, nameof(win32ResourcesPath)))) { return compilation.Emit( outputStream, pdbStream: pdbStream, xmlDocumentationStream: xmlDocStream, win32Resources: win32ResourcesStream, manifestResources: manifestResources, options: new EmitOptions(pdbFilePath: pdbPath), cancellationToken: cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public static class FileSystemExtensions { /// <summary> /// Emit the IL for the compilation into the specified stream. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="outputPath">Path of the file to which the compilation will be written.</param> /// <param name="pdbPath">Path of the file to which the compilation's debug info will be written. /// Also embedded in the output file. Null to forego PDB generation. /// </param> /// <param name="xmlDocPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="cancellationToken">To cancel the emit process.</param> /// <exception cref="ArgumentNullException">Compilation or path is null.</exception> /// <exception cref="ArgumentException">Path is empty or invalid.</exception> /// <exception cref="IOException">An error occurred while reading or writing a file.</exception> public static EmitResult Emit( this Compilation compilation, string outputPath, string? pdbPath = null, string? xmlDocPath = null, string? win32ResourcesPath = null, IEnumerable<ResourceDescription>? manifestResources = null, CancellationToken cancellationToken = default) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } using (var outputStream = FileUtilities.CreateFileStreamChecked(File.Create, outputPath, nameof(outputPath))) using (var pdbStream = (pdbPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, pdbPath, nameof(pdbPath)))) using (var xmlDocStream = (xmlDocPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, xmlDocPath, nameof(xmlDocPath)))) using (var win32ResourcesStream = (win32ResourcesPath == null ? null : FileUtilities.CreateFileStreamChecked(File.OpenRead, win32ResourcesPath, nameof(win32ResourcesPath)))) { return compilation.Emit( outputStream, pdbStream: pdbStream, xmlDocumentationStream: xmlDocStream, win32Resources: win32ResourcesStream, manifestResources: manifestResources, options: new EmitOptions(pdbFilePath: pdbPath), cancellationToken: cancellationToken); } } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeVariableTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeVariableTests Inherits AbstractCodeVariableTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint1() Dim code = <Code> Class C Dim i$$ As Integer End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=9, absoluteOffset:=17, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_Attribute() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim i$$ As Integer End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=49, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember() Dim code = <Code> Enum E A$$ End Enum </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember_Attribute() Dim code = <Code> Enum E &lt;System.CLSCompliant(True)&gt; A$$ End Enum </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint1() Dim code = <Code> Class C Dim i$$ As Integer End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=10, absoluteOffset:=18, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_Attribute() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim i$$ As Integer End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=50, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember() Dim code = <Code> Enum E A$$ End Enum </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember_Attribute() Dim code = <Code> Enum E &lt;System.CLSCompliant(True)&gt; A$$ End Enum </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> Class C Dim $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> Class C Private $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> Class C Protected $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> Class C Protected Friend $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> Class C Friend $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> Class C Public $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> Enum E $$Goo End Enum </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Comment tests" <WorkItem(638909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638909")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> Class C ' Goo Dim $$i As Integer End Class </Code> Dim result = " Goo" TestComment(code, result) End Sub #End Region #Region "ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind1() Dim code = <Code> Enum E $$Goo End Enum </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind2() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind3() Dim code = <Code> Class C Const $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind4() Dim code = <Code> Class C ReadOnly $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind5() Dim code = <Code> Class C ReadOnly Const $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub #End Region #Region "InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression1() Dim code = <Code> Class C Dim i$$ As Integer = 42 End Class </Code> TestInitExpression(code, "42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression2() Dim code = <Code> Class C Const $$i As Integer = 19 + 23 End Class </Code> TestInitExpression(code, "19 + 23") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression3() Dim code = <Code> Enum E $$i = 19 + 23 End Enum </Code> TestInitExpression(code, "19 + 23") End Sub #End Region #Region "IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant1() Dim code = <Code> Enum E $$Goo End Enum </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant2() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestIsConstant(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant3() Dim code = <Code> Class C Const $$x As Integer = 0 End Class </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant4() Dim code = <Code> Class C ReadOnly $$x As Integer = 0 End Class </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant5() Dim code = <Code> Class C WithEvents $$x As Integer End Class </Code> TestIsConstant(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> Class C Shared $$x As Integer End Class </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <WorkItem(638224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638224")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_EnumMember() Dim code = <Code> Enum SomeEnum A$$ End Enum </Code> TestName(code, "A") End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_UniqueSignature() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "F:N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName1() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName2() Dim code = <Code> Namespace N Class C(Of T) Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C(Of T).x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName3() Dim code = <Code> Namespace N Class C Public ReadOnly $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Public C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private C.x = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName1() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName2() Dim code = <Code> Namespace N Class C(Of T) Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C(Of T).x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private N.C.x = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName, "Private ") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName_InitExpression_Type() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private As Integer = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression_Type_ForAsNew() ' Amusingly, this will *crash* Dev10. Dim code = <Code> Namespace N Class C Dim $$x As New System.Text.StringBuilder End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As System.Text.StringBuilder") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Type() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As Integer") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> Class C Dim $$a As Integer End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Integer", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> Class C WithEvents $$a As Object End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Object", .AsFullName = "System.Object", .CodeTypeFullName = "System.Object", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType3() Dim code = <Code> Class C Private $$a As New Object End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Object", .AsFullName = "System.Object", .CodeTypeFullName = "System.Object", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject }) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Imports System Class C Dim $$goo As Integer End Class </Code> Dim expected = <Code><![CDATA[ Imports System Class C <Serializable()> Dim goo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code><![CDATA[ Imports System Class C <Serializable> Dim $$goo As Integer End Class ]]></Code> Dim expected = <Code><![CDATA[ Imports System Class C <Serializable> <CLSCompliant(True)> Dim goo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code><![CDATA[ Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; Dim $$goo As Integer End Class ]]></Code> Dim expected = <Code><![CDATA[ Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; <CLSCompliant(True)> Dim goo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"}) End Function #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess1() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess2() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess3() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Public i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> Class C Public $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> Class C Private $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> Class C Public $$i As Integer End Class </Code> Dim expected = <Code> Class C Protected Friend i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> Class C #Region "Goo" Dim x As Integer #End Region Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region Public i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> Class C #Region "Goo" Dim x As Integer #End Region Public $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region Protected Friend i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess8() As Task Dim code = <Code> Class C #Region "Goo" Dim x As Integer #End Region Public $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess9() As Task Dim code = <Code> Class C #Region "Goo" Dim $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Public x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess10() As Task Dim code = <Code> Class C #Region "Goo" Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess11() As Task Dim code = <Code> Class C #Region "Goo" Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Protected Friend x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess12() As Task Dim code = <Code><![CDATA[ Class C #Region "Goo" <Bar> Public $$x As Integer #End Region End Class ]]></Code> Dim expected = <Code><![CDATA[ Class C #Region "Goo" <Bar> Protected Friend x As Integer #End Region End Class ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess13() As Task Dim code = <Code> Class C #Region "Goo" ' Comment comment comment Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" ' Comment comment comment Protected Friend x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess14() As Task Dim code = <Code><![CDATA[ Class C #Region "Goo" ''' <summary> ''' Comment comment comment ''' </summary> Public $$x As Integer #End Region End Class ]]></Code> Dim expected = <Code><![CDATA[ Class C #Region "Goo" ''' <summary> ''' Comment comment comment ''' </summary> Protected Friend x As Integer #End Region End Class ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess15() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Private WithEvents x As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate Or EnvDTE.vsCMAccess.vsCMAccessWithEvents) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess16() As Task Dim code = <Code> Class C Private WithEvents $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function #End Region #Region "Set ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind1() As Task Dim code = <Code> Enum $$Goo End Enum </Code> Dim expected = <Code> Enum Goo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind2() As Task Dim code = <Code> Enum $$Goo End Enum </Code> Dim expected = <Code> Enum Goo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind3() As Task Dim code = <Code> Enum $$Goo End Enum </Code> Dim expected = <Code> Enum Goo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind4() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind5() As Task Dim code = <Code> Class C Shared $$x As Integer End Class </Code> Dim expected = <Code> Class C Shared x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind6() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Const x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind7() As Task Dim code = <Code> Class C Const $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind8() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C ReadOnly x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind9() As Task Dim code = <Code> Class C ReadOnly $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function #End Region #Region "Set InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression2() As Task Dim code = <Code> Class C Dim $$i As Integer, j As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer = 42, j As Integer End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression3() As Task Dim code = <Code> Class C Dim i As Integer, $$j As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer, j As Integer = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression4() As Task ' The result below is a bit silly, but that's what the legacy Code Model does. Dim code = <Code> Class C Dim $$o As New Object End Class </Code> Dim expected = <Code> Class C Dim o As New Object = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression5() As Task Dim code = <Code> Class C Const $$i As Integer = 0 End Class </Code> Dim expected = <Code> Class C Const i As Integer = 19 + 23 End Class </Code> Await TestSetInitExpression(code, expected, "19 + 23") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression6() As Task Dim code = <Code> Class C Const $$i As Integer = 0 End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetInitExpression(code, expected, "") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression7() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo = 42 End Enum </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression8() As Task Dim code = <Code> Enum E $$Goo = 0 End Enum </Code> Dim expected = <Code> Enum E Goo = 42 End Enum </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression9() As Task Dim code = <Code> Enum E $$Goo = 0 End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetInitExpression(code, expected, Nothing) End Function #End Region #Region "Set IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant2() As Task Dim code = <Code> Class C Const $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant3() As Task Dim code = <Code> Class C ReadOnly $$i As Integer End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant4() As Task Dim code = <Code> Class C ReadOnly $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant5() As Task Dim code = <Code> Module C Dim $$i As Integer End Module </Code> Dim expected = <Code> Module C Const i As Integer End Module </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant6() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetIsConstant(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant7() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetIsConstant(code, expected, False, ThrowsNotImplementedException(Of Boolean)) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Shared i As Integer End Class </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> Class C Shared $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsShared(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared3() As Task Dim code = <Code> Class C Private $$i As Integer End Class </Code> Dim expected = <Code> Class C Private Shared i As Integer End Class </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared4() As Task Dim code = <Code> Class C Private Shared $$i As Integer End Class </Code> Dim expected = <Code> Class C Private i As Integer End Class </Code> Await TestSetIsShared(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared5() As Task Dim code = <Code> Module C Dim $$i As Integer End Module </Code> Dim expected = <Code> Module C Dim i As Integer End Module </Code> Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared6() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> Class C Dim $$Goo As Integer End Class </Code> Dim expected = <Code> Class C Dim Bar As Integer End Class </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> Class C #Region "Goo" Dim $$Goo As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim Bar As Integer #End Region End Class </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> Class C Dim $$a As Integer End Class </Code> Dim expected = <Code> Class C Dim a As Double End Class </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> Class C Dim $$a, b As Integer End Class </Code> Dim expected = <Code> Class C Dim a, b As Double End Class </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType3() As Task Dim code = <Code> Class C Private $$a As New Object End Class </Code> Dim expected = <Code> Class C Private a As New String End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType4() As Task Dim code = <Code> Class C Private $$a As New Object, x As Integer = 0 End Class </Code> Dim expected = <Code> Class C Private a As New String, x As Integer = 0 End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType5() As Task Dim code = <Code> Class C Private a As New Object, x$$ As Integer = 0 End Class </Code> Dim expected = <Code> Class C Private a As New Object, x As String = 0 End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function #End Region Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeVariableTests Inherits AbstractCodeVariableTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint1() Dim code = <Code> Class C Dim i$$ As Integer End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=9, absoluteOffset:=17, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_Attribute() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim i$$ As Integer End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=49, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember() Dim code = <Code> Enum E A$$ End Enum </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember_Attribute() Dim code = <Code> Enum E &lt;System.CLSCompliant(True)&gt; A$$ End Enum </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint1() Dim code = <Code> Class C Dim i$$ As Integer End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=10, absoluteOffset:=18, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_Attribute() Dim code = <Code> Class C &lt;System.CLSCompliant(True)&gt; Dim i$$ As Integer End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=10, absoluteOffset:=50, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember() Dim code = <Code> Enum E A$$ End Enum </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember_Attribute() Dim code = <Code> Enum E &lt;System.CLSCompliant(True)&gt; A$$ End Enum </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> Class C Dim $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> Class C Private $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> Class C Protected $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> Class C Protected Friend $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> Class C Friend $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> Class C Public $$x as Integer End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> Enum E $$Goo End Enum </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Comment tests" <WorkItem(638909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638909")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> Class C ' Goo Dim $$i As Integer End Class </Code> Dim result = " Goo" TestComment(code, result) End Sub #End Region #Region "ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind1() Dim code = <Code> Enum E $$Goo End Enum </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind2() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind3() Dim code = <Code> Class C Const $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind4() Dim code = <Code> Class C ReadOnly $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind5() Dim code = <Code> Class C ReadOnly Const $$x As Integer End Class </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub #End Region #Region "InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression1() Dim code = <Code> Class C Dim i$$ As Integer = 42 End Class </Code> TestInitExpression(code, "42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression2() Dim code = <Code> Class C Const $$i As Integer = 19 + 23 End Class </Code> TestInitExpression(code, "19 + 23") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression3() Dim code = <Code> Enum E $$i = 19 + 23 End Enum </Code> TestInitExpression(code, "19 + 23") End Sub #End Region #Region "IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant1() Dim code = <Code> Enum E $$Goo End Enum </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant2() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestIsConstant(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant3() Dim code = <Code> Class C Const $$x As Integer = 0 End Class </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant4() Dim code = <Code> Class C ReadOnly $$x As Integer = 0 End Class </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant5() Dim code = <Code> Class C WithEvents $$x As Integer End Class </Code> TestIsConstant(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> Class C Dim $$x As Integer End Class </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> Class C Shared $$x As Integer End Class </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <WorkItem(638224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638224")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_EnumMember() Dim code = <Code> Enum SomeEnum A$$ End Enum </Code> TestName(code, "A") End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_UniqueSignature() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "F:N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName1() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName2() Dim code = <Code> Namespace N Class C(Of T) Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C(Of T).x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName3() Dim code = <Code> Namespace N Class C Public ReadOnly $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Public C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private C.x = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName1() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName2() Dim code = <Code> Namespace N Class C(Of T) Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C(Of T).x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private N.C.x = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName, "Private ") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName_InitExpression() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_NoName_InitExpression_Type() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private As Integer = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression_Type_ForAsNew() ' Amusingly, this will *crash* Dev10. Dim code = <Code> Namespace N Class C Dim $$x As New System.Text.StringBuilder End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As System.Text.StringBuilder") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Type() Dim code = <Code> Namespace N Class C Dim $$x As Integer = 42 End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As Integer") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> Class C Dim $$a As Integer End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Integer", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> Class C WithEvents $$a As Object End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Object", .AsFullName = "System.Object", .CodeTypeFullName = "System.Object", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType3() Dim code = <Code> Class C Private $$a As New Object End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Object", .AsFullName = "System.Object", .CodeTypeFullName = "System.Object", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject }) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Imports System Class C Dim $$goo As Integer End Class </Code> Dim expected = <Code><![CDATA[ Imports System Class C <Serializable()> Dim goo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code><![CDATA[ Imports System Class C <Serializable> Dim $$goo As Integer End Class ]]></Code> Dim expected = <Code><![CDATA[ Imports System Class C <Serializable> <CLSCompliant(True)> Dim goo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code><![CDATA[ Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; Dim $$goo As Integer End Class ]]></Code> Dim expected = <Code><![CDATA[ Imports System Class C ''' &lt;summary&gt;&lt;/summary&gt; <CLSCompliant(True)> Dim goo As Integer End Class ]]></Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"}) End Function #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess1() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess2() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess3() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Public i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> Class C Public $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> Class C Private $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> Class C Public $$i As Integer End Class </Code> Dim expected = <Code> Class C Protected Friend i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> Class C #Region "Goo" Dim x As Integer #End Region Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region Public i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> Class C #Region "Goo" Dim x As Integer #End Region Public $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region Protected Friend i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess8() As Task Dim code = <Code> Class C #Region "Goo" Dim x As Integer #End Region Public $$i As Integer End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region Dim i As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess9() As Task Dim code = <Code> Class C #Region "Goo" Dim $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Public x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess10() As Task Dim code = <Code> Class C #Region "Goo" Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess11() As Task Dim code = <Code> Class C #Region "Goo" Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Protected Friend x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess12() As Task Dim code = <Code><![CDATA[ Class C #Region "Goo" <Bar> Public $$x As Integer #End Region End Class ]]></Code> Dim expected = <Code><![CDATA[ Class C #Region "Goo" <Bar> Protected Friend x As Integer #End Region End Class ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess13() As Task Dim code = <Code> Class C #Region "Goo" ' Comment comment comment Public $$x As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" ' Comment comment comment Protected Friend x As Integer #End Region End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess14() As Task Dim code = <Code><![CDATA[ Class C #Region "Goo" ''' <summary> ''' Comment comment comment ''' </summary> Public $$x As Integer #End Region End Class ]]></Code> Dim expected = <Code><![CDATA[ Class C #Region "Goo" ''' <summary> ''' Comment comment comment ''' </summary> Protected Friend x As Integer #End Region End Class ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess15() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Private WithEvents x As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate Or EnvDTE.vsCMAccess.vsCMAccessWithEvents) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess16() As Task Dim code = <Code> Class C Private WithEvents $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function #End Region #Region "Set ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind1() As Task Dim code = <Code> Enum $$Goo End Enum </Code> Dim expected = <Code> Enum Goo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind2() As Task Dim code = <Code> Enum $$Goo End Enum </Code> Dim expected = <Code> Enum Goo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind3() As Task Dim code = <Code> Enum $$Goo End Enum </Code> Dim expected = <Code> Enum Goo End Enum </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind4() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind5() As Task Dim code = <Code> Class C Shared $$x As Integer End Class </Code> Dim expected = <Code> Class C Shared x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind6() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C Const x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind7() As Task Dim code = <Code> Class C Const $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind8() As Task Dim code = <Code> Class C Dim $$x As Integer End Class </Code> Dim expected = <Code> Class C ReadOnly x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind9() As Task Dim code = <Code> Class C ReadOnly $$x As Integer End Class </Code> Dim expected = <Code> Class C Dim x As Integer End Class </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function #End Region #Region "Set InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression2() As Task Dim code = <Code> Class C Dim $$i As Integer, j As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer = 42, j As Integer End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression3() As Task Dim code = <Code> Class C Dim i As Integer, $$j As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer, j As Integer = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression4() As Task ' The result below is a bit silly, but that's what the legacy Code Model does. Dim code = <Code> Class C Dim $$o As New Object End Class </Code> Dim expected = <Code> Class C Dim o As New Object = 42 End Class </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression5() As Task Dim code = <Code> Class C Const $$i As Integer = 0 End Class </Code> Dim expected = <Code> Class C Const i As Integer = 19 + 23 End Class </Code> Await TestSetInitExpression(code, expected, "19 + 23") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression6() As Task Dim code = <Code> Class C Const $$i As Integer = 0 End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetInitExpression(code, expected, "") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression7() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo = 42 End Enum </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression8() As Task Dim code = <Code> Enum E $$Goo = 0 End Enum </Code> Dim expected = <Code> Enum E Goo = 42 End Enum </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression9() As Task Dim code = <Code> Enum E $$Goo = 0 End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetInitExpression(code, expected, Nothing) End Function #End Region #Region "Set IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant2() As Task Dim code = <Code> Class C Const $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant3() As Task Dim code = <Code> Class C ReadOnly $$i As Integer End Class </Code> Dim expected = <Code> Class C Const i As Integer End Class </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant4() As Task Dim code = <Code> Class C ReadOnly $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant5() As Task Dim code = <Code> Module C Dim $$i As Integer End Module </Code> Dim expected = <Code> Module C Const i As Integer End Module </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant6() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetIsConstant(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant7() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetIsConstant(code, expected, False, ThrowsNotImplementedException(Of Boolean)) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> Class C Dim $$i As Integer End Class </Code> Dim expected = <Code> Class C Shared i As Integer End Class </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> Class C Shared $$i As Integer End Class </Code> Dim expected = <Code> Class C Dim i As Integer End Class </Code> Await TestSetIsShared(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared3() As Task Dim code = <Code> Class C Private $$i As Integer End Class </Code> Dim expected = <Code> Class C Private Shared i As Integer End Class </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared4() As Task Dim code = <Code> Class C Private Shared $$i As Integer End Class </Code> Dim expected = <Code> Class C Private i As Integer End Class </Code> Await TestSetIsShared(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared5() As Task Dim code = <Code> Module C Dim $$i As Integer End Module </Code> Dim expected = <Code> Module C Dim i As Integer End Module </Code> Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared6() As Task Dim code = <Code> Enum E $$Goo End Enum </Code> Dim expected = <Code> Enum E Goo End Enum </Code> Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean)) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> Class C Dim $$Goo As Integer End Class </Code> Dim expected = <Code> Class C Dim Bar As Integer End Class </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> Class C #Region "Goo" Dim $$Goo As Integer #End Region End Class </Code> Dim expected = <Code> Class C #Region "Goo" Dim Bar As Integer #End Region End Class </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> Class C Dim $$a As Integer End Class </Code> Dim expected = <Code> Class C Dim a As Double End Class </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> Class C Dim $$a, b As Integer End Class </Code> Dim expected = <Code> Class C Dim a, b As Double End Class </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType3() As Task Dim code = <Code> Class C Private $$a As New Object End Class </Code> Dim expected = <Code> Class C Private a As New String End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType4() As Task Dim code = <Code> Class C Private $$a As New Object, x As Integer = 0 End Class </Code> Dim expected = <Code> Class C Private a As New String, x As Integer = 0 End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType5() As Task Dim code = <Code> Class C Private a As New Object, x$$ As Integer = 0 End Class </Code> Dim expected = <Code> Class C Private a As New Object, x As String = 0 End Class </Code> Await TestSetTypeProp(code, expected, "String") End Function #End Region Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/EditorFeatures/VisualBasicTest/UnsealClass/UnsealClassTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.UnsealClass Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UnsealClass <Trait(Traits.Feature, Traits.Features.CodeActionsUnsealClass)> Public NotInheritable Class UnsealClassTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicUnsealClassCodeFixProvider()) End Function <Fact> Public Async Function RemovedFromSealedClass() As Task Await TestInRegularAndScriptAsync(" notinheritable class C end class class D inherits [|C|] end class", " class C end class class D inherits C end class") End Function <Fact> Public Async Function RemovedFromSealedClassWithOtherModifiersPreserved() As Task Await TestInRegularAndScriptAsync(" public notinheritable class C end class class D inherits [|C|] end class", " public class C end class class D inherits C end class") End Function <Fact> Public Async Function RemovedFromSealedClassWithConstructedGeneric() As Task Await TestInRegularAndScriptAsync(" notinheritable class C(of T) end class class D inherits [|C(of integer)|] end class", " class C(of T) end class class D inherits C(of integer) end class") End Function <Fact> Public Async Function NotOfferedForNonSealedClass() As Task Await TestMissingInRegularAndScriptAsync(" class C end class class D inherits [|C|] end class") End Function <Fact> Public Async Function NotOfferedForModule() As Task Await TestMissingInRegularAndScriptAsync(" module C end module class D inherits [|C|] end class") End Function <Fact> Public Async Function NotOfferedForStruct() As Task Await TestMissingInRegularAndScriptAsync(" structure S end structure class D inherits [|S|] end class") End Function <Fact> Public Async Function NotOfferedForDelegate() As Task Await TestMissingInRegularAndScriptAsync(" delegate sub F() class D inherits [|F|] end class") End Function <Fact> Public Async Function NotOfferedForSealedClassFromMetadata1() As Task Await TestMissingInRegularAndScriptAsync(" class D inherits [|string|] end class") End Function <Fact> Public Async Function NotOfferedForSealedClassFromMetadata2() As Task Await TestMissingInRegularAndScriptAsync(" class D inherits [|System.ApplicationId|] end class") End Function <Fact> Public Async Function RemovedFromAllPartialClassDeclarationsInSameFile() As Task Await TestInRegularAndScriptAsync(" partial public notinheritable class C end class partial class C end class partial notinheritable class C end class class D inherits [|C|] end class", " partial public class C end class partial class C end class partial class C end class class D inherits [|C|] end class") End Function <Fact> Public Async Function RemovedFromAllPartialClassDeclarationsAcrossFiles() As Task Await TestInRegularAndScriptAsync( <Workspace> <Project Language="Visual Basic"> <Document> partial public notinheritable class C end class </Document> <Document> partial class C end class partial notinheritable class C end class </Document> <Document> class D inherits [|C|] end class </Document> </Project> </Workspace>.ToString(), <Workspace> <Project Language="Visual Basic"> <Document> partial public class C end class </Document> <Document> partial class C end class partial class C end class </Document> <Document> class D inherits C end class </Document> </Project> </Workspace>.ToString()) End Function <Fact> Public Async Function RemovedFromClassInCSharpProject() As Task Await TestInRegularAndScriptAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="Project1"> <ProjectReference>Project2</ProjectReference> <Document> class D inherits [|C|] end class </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Project2"> <Document> public sealed class C { } </Document> </Project> </Workspace>.ToString(), <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="Project1"> <ProjectReference>Project2</ProjectReference> <Document> class D inherits C end class </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Project2"> <Document> public class C { } </Document> </Project> </Workspace>.ToString()) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.UnsealClass Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UnsealClass <Trait(Traits.Feature, Traits.Features.CodeActionsUnsealClass)> Public NotInheritable Class UnsealClassTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicUnsealClassCodeFixProvider()) End Function <Fact> Public Async Function RemovedFromSealedClass() As Task Await TestInRegularAndScriptAsync(" notinheritable class C end class class D inherits [|C|] end class", " class C end class class D inherits C end class") End Function <Fact> Public Async Function RemovedFromSealedClassWithOtherModifiersPreserved() As Task Await TestInRegularAndScriptAsync(" public notinheritable class C end class class D inherits [|C|] end class", " public class C end class class D inherits C end class") End Function <Fact> Public Async Function RemovedFromSealedClassWithConstructedGeneric() As Task Await TestInRegularAndScriptAsync(" notinheritable class C(of T) end class class D inherits [|C(of integer)|] end class", " class C(of T) end class class D inherits C(of integer) end class") End Function <Fact> Public Async Function NotOfferedForNonSealedClass() As Task Await TestMissingInRegularAndScriptAsync(" class C end class class D inherits [|C|] end class") End Function <Fact> Public Async Function NotOfferedForModule() As Task Await TestMissingInRegularAndScriptAsync(" module C end module class D inherits [|C|] end class") End Function <Fact> Public Async Function NotOfferedForStruct() As Task Await TestMissingInRegularAndScriptAsync(" structure S end structure class D inherits [|S|] end class") End Function <Fact> Public Async Function NotOfferedForDelegate() As Task Await TestMissingInRegularAndScriptAsync(" delegate sub F() class D inherits [|F|] end class") End Function <Fact> Public Async Function NotOfferedForSealedClassFromMetadata1() As Task Await TestMissingInRegularAndScriptAsync(" class D inherits [|string|] end class") End Function <Fact> Public Async Function NotOfferedForSealedClassFromMetadata2() As Task Await TestMissingInRegularAndScriptAsync(" class D inherits [|System.ApplicationId|] end class") End Function <Fact> Public Async Function RemovedFromAllPartialClassDeclarationsInSameFile() As Task Await TestInRegularAndScriptAsync(" partial public notinheritable class C end class partial class C end class partial notinheritable class C end class class D inherits [|C|] end class", " partial public class C end class partial class C end class partial class C end class class D inherits [|C|] end class") End Function <Fact> Public Async Function RemovedFromAllPartialClassDeclarationsAcrossFiles() As Task Await TestInRegularAndScriptAsync( <Workspace> <Project Language="Visual Basic"> <Document> partial public notinheritable class C end class </Document> <Document> partial class C end class partial notinheritable class C end class </Document> <Document> class D inherits [|C|] end class </Document> </Project> </Workspace>.ToString(), <Workspace> <Project Language="Visual Basic"> <Document> partial public class C end class </Document> <Document> partial class C end class partial class C end class </Document> <Document> class D inherits C end class </Document> </Project> </Workspace>.ToString()) End Function <Fact> Public Async Function RemovedFromClassInCSharpProject() As Task Await TestInRegularAndScriptAsync( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="Project1"> <ProjectReference>Project2</ProjectReference> <Document> class D inherits [|C|] end class </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Project2"> <Document> public sealed class C { } </Document> </Project> </Workspace>.ToString(), <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="Project1"> <ProjectReference>Project2</ProjectReference> <Document> class D inherits C end class </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Project2"> <Document> public class C { } </Document> </Project> </Workspace>.ToString()) End Function End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Analyzers/VisualBasic/CodeFixes/RemoveUnusedMembers/VisualBasicRemoveUnusedMembersCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnusedMembers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedMembers <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnusedMembers), [Shared]> Friend Class VisualBasicRemoveUnusedMembersCodeFixProvider Inherits AbstractRemoveUnusedMembersCodeFixProvider(Of FieldDeclarationSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub ''' <summary> ''' This method adjusts the <paramref name="declarators"/> to remove based on whether or not all variable declarators ''' within a field declaration should be removed, ''' i.e. if all the fields declared within a field declaration are unused, ''' we can remove the entire field declaration instead of individual variable declarators. ''' </summary> Protected Overrides Sub AdjustAndAddAppropriateDeclaratorsToRemove(fieldDeclarators As HashSet(Of FieldDeclarationSyntax), declarators As HashSet(Of SyntaxNode)) For Each variableDeclarator In fieldDeclarators.SelectMany(Function(f) f.Declarators) AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=variableDeclarator, childDeclarators:=variableDeclarator.Names, declarators:=declarators) Next For Each fieldDeclarator In fieldDeclarators AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=fieldDeclarator, childDeclarators:=fieldDeclarator.Declarators, declarators:=declarators) Next End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnusedMembers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedMembers <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnusedMembers), [Shared]> Friend Class VisualBasicRemoveUnusedMembersCodeFixProvider Inherits AbstractRemoveUnusedMembersCodeFixProvider(Of FieldDeclarationSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub ''' <summary> ''' This method adjusts the <paramref name="declarators"/> to remove based on whether or not all variable declarators ''' within a field declaration should be removed, ''' i.e. if all the fields declared within a field declaration are unused, ''' we can remove the entire field declaration instead of individual variable declarators. ''' </summary> Protected Overrides Sub AdjustAndAddAppropriateDeclaratorsToRemove(fieldDeclarators As HashSet(Of FieldDeclarationSyntax), declarators As HashSet(Of SyntaxNode)) For Each variableDeclarator In fieldDeclarators.SelectMany(Function(f) f.Declarators) AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=variableDeclarator, childDeclarators:=variableDeclarator.Names, declarators:=declarators) Next For Each fieldDeclarator In fieldDeclarators AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=fieldDeclarator, childDeclarators:=fieldDeclarator.Declarators, declarators:=declarators) Next End Sub End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/ArrayStatements/ReDimKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.ArrayStatements ''' <summary> ''' Recommends the "ReDim" statement. ''' </summary> Friend Class ReDimKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("ReDim", VBFeaturesResources.Reallocates_storage_space_for_an_array_variable)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.ArrayStatements ''' <summary> ''' Recommends the "ReDim" statement. ''' </summary> Friend Class ReDimKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("ReDim", VBFeaturesResources.Reallocates_storage_space_for_an_array_variable)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Core/Portable/Completion/ExportCompletionProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Use this attribute to export a <see cref="CompletionProvider"/> so that it will /// be found and used by the per language associated <see cref="CompletionService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public sealed class ExportCompletionProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public string[] Roles { get; set; } public ExportCompletionProviderAttribute(string name, string language) : base(typeof(CompletionProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Use this attribute to export a <see cref="CompletionProvider"/> so that it will /// be found and used by the per language associated <see cref="CompletionService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public sealed class ExportCompletionProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public string[] Roles { get; set; } public ExportCompletionProviderAttribute(string name, string language) : base(typeof(CompletionProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/CSharp/Portable/Symbols/PublicModel/Symbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal abstract class Symbol : ISymbol { internal abstract CSharp.Symbol UnderlyingSymbol { get; } protected static ImmutableArray<TypeWithAnnotations> ConstructTypeArguments(ITypeSymbol[] typeArguments) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArguments.Length); foreach (var typeArg in typeArguments) { var type = typeArg.EnsureCSharpSymbolOrNull(nameof(typeArguments)); builder.Add(TypeWithAnnotations.Create(type, (typeArg?.NullableAnnotation.ToInternalAnnotation() ?? NullableAnnotation.NotAnnotated))); } return builder.ToImmutableAndFree(); } protected static ImmutableArray<TypeWithAnnotations> ConstructTypeArguments(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations) { if (typeArguments.IsDefault) { throw new ArgumentException(nameof(typeArguments)); } int n = typeArguments.Length; if (!typeArgumentNullableAnnotations.IsDefault && typeArgumentNullableAnnotations.Length != n) { throw new ArgumentException(nameof(typeArgumentNullableAnnotations)); } var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); for (int i = 0; i < n; i++) { var type = typeArguments[i].EnsureCSharpSymbolOrNull(nameof(typeArguments)); var annotation = typeArgumentNullableAnnotations.IsDefault ? NullableAnnotation.Oblivious : typeArgumentNullableAnnotations[i].ToInternalAnnotation(); builder.Add(TypeWithAnnotations.Create(type, annotation)); } return builder.ToImmutableAndFree(); } ISymbol ISymbol.OriginalDefinition { get { return UnderlyingSymbol.OriginalDefinition.GetPublicSymbol(); } } ISymbol ISymbol.ContainingSymbol { get { return UnderlyingSymbol.ContainingSymbol.GetPublicSymbol(); } } INamedTypeSymbol ISymbol.ContainingType { get { return UnderlyingSymbol.ContainingType.GetPublicSymbol(); } } public sealed override int GetHashCode() { return UnderlyingSymbol.GetHashCode(); } public sealed override bool Equals(object obj) { return this.Equals(obj as Symbol, CodeAnalysis.SymbolEqualityComparer.Default); } bool IEquatable<ISymbol>.Equals(ISymbol other) { return this.Equals(other as Symbol, CodeAnalysis.SymbolEqualityComparer.Default); } bool ISymbol.Equals(ISymbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return this.Equals(other as Symbol, equalityComparer); } protected bool Equals(Symbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return other is object && UnderlyingSymbol.Equals(other.UnderlyingSymbol, equalityComparer.CompareKind); } ImmutableArray<Location> ISymbol.Locations { get { return UnderlyingSymbol.Locations; } } ImmutableArray<SyntaxReference> ISymbol.DeclaringSyntaxReferences { get { return UnderlyingSymbol.DeclaringSyntaxReferences; } } ImmutableArray<AttributeData> ISymbol.GetAttributes() { return StaticCast<AttributeData>.From(UnderlyingSymbol.GetAttributes()); } Accessibility ISymbol.DeclaredAccessibility { get { return UnderlyingSymbol.DeclaredAccessibility; } } void ISymbol.Accept(SymbolVisitor visitor) { Accept(visitor); } protected abstract void Accept(SymbolVisitor visitor); TResult ISymbol.Accept<TResult>(SymbolVisitor<TResult> visitor) { return Accept(visitor); } protected abstract TResult Accept<TResult>(SymbolVisitor<TResult> visitor); string ISymbol.GetDocumentationCommentId() { return UnderlyingSymbol.GetDocumentationCommentId(); } string ISymbol.GetDocumentationCommentXml(CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) { return UnderlyingSymbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } string ISymbol.ToDisplayString(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayString(this, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToDisplayParts(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayParts(this, format); } string ISymbol.ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayString(this, GetCSharpSemanticModel(semanticModel), position, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayParts(this, GetCSharpSemanticModel(semanticModel), position, format); } internal static CSharpSemanticModel GetCSharpSemanticModel(SemanticModel semanticModel) { var csharpModel = semanticModel as CSharpSemanticModel; if (csharpModel == null) { throw new ArgumentException(CSharpResources.WrongSemanticModelType, LanguageNames.CSharp); } return csharpModel; } SymbolKind ISymbol.Kind => UnderlyingSymbol.Kind; string ISymbol.Language => LanguageNames.CSharp; string ISymbol.Name => UnderlyingSymbol.Name; string ISymbol.MetadataName => UnderlyingSymbol.MetadataName; IAssemblySymbol ISymbol.ContainingAssembly => UnderlyingSymbol.ContainingAssembly.GetPublicSymbol(); IModuleSymbol ISymbol.ContainingModule => UnderlyingSymbol.ContainingModule.GetPublicSymbol(); INamespaceSymbol ISymbol.ContainingNamespace => UnderlyingSymbol.ContainingNamespace.GetPublicSymbol(); bool ISymbol.IsDefinition => UnderlyingSymbol.IsDefinition; bool ISymbol.IsStatic { get { return UnderlyingSymbol.IsStatic; } } bool ISymbol.IsVirtual { get { return UnderlyingSymbol.IsVirtual; } } bool ISymbol.IsOverride { get { return UnderlyingSymbol.IsOverride; } } bool ISymbol.IsAbstract { get { return UnderlyingSymbol.IsAbstract; } } bool ISymbol.IsSealed { get { return UnderlyingSymbol.IsSealed; } } bool ISymbol.IsExtern => UnderlyingSymbol.IsExtern; bool ISymbol.IsImplicitlyDeclared => UnderlyingSymbol.IsImplicitlyDeclared; bool ISymbol.CanBeReferencedByName => UnderlyingSymbol.CanBeReferencedByName; bool ISymbol.HasUnsupportedMetadata => UnderlyingSymbol.HasUnsupportedMetadata; public sealed override string ToString() { return SymbolDisplay.ToDisplayString(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal abstract class Symbol : ISymbol { internal abstract CSharp.Symbol UnderlyingSymbol { get; } protected static ImmutableArray<TypeWithAnnotations> ConstructTypeArguments(ITypeSymbol[] typeArguments) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArguments.Length); foreach (var typeArg in typeArguments) { var type = typeArg.EnsureCSharpSymbolOrNull(nameof(typeArguments)); builder.Add(TypeWithAnnotations.Create(type, (typeArg?.NullableAnnotation.ToInternalAnnotation() ?? NullableAnnotation.NotAnnotated))); } return builder.ToImmutableAndFree(); } protected static ImmutableArray<TypeWithAnnotations> ConstructTypeArguments(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations) { if (typeArguments.IsDefault) { throw new ArgumentException(nameof(typeArguments)); } int n = typeArguments.Length; if (!typeArgumentNullableAnnotations.IsDefault && typeArgumentNullableAnnotations.Length != n) { throw new ArgumentException(nameof(typeArgumentNullableAnnotations)); } var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); for (int i = 0; i < n; i++) { var type = typeArguments[i].EnsureCSharpSymbolOrNull(nameof(typeArguments)); var annotation = typeArgumentNullableAnnotations.IsDefault ? NullableAnnotation.Oblivious : typeArgumentNullableAnnotations[i].ToInternalAnnotation(); builder.Add(TypeWithAnnotations.Create(type, annotation)); } return builder.ToImmutableAndFree(); } ISymbol ISymbol.OriginalDefinition { get { return UnderlyingSymbol.OriginalDefinition.GetPublicSymbol(); } } ISymbol ISymbol.ContainingSymbol { get { return UnderlyingSymbol.ContainingSymbol.GetPublicSymbol(); } } INamedTypeSymbol ISymbol.ContainingType { get { return UnderlyingSymbol.ContainingType.GetPublicSymbol(); } } public sealed override int GetHashCode() { return UnderlyingSymbol.GetHashCode(); } public sealed override bool Equals(object obj) { return this.Equals(obj as Symbol, CodeAnalysis.SymbolEqualityComparer.Default); } bool IEquatable<ISymbol>.Equals(ISymbol other) { return this.Equals(other as Symbol, CodeAnalysis.SymbolEqualityComparer.Default); } bool ISymbol.Equals(ISymbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return this.Equals(other as Symbol, equalityComparer); } protected bool Equals(Symbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return other is object && UnderlyingSymbol.Equals(other.UnderlyingSymbol, equalityComparer.CompareKind); } ImmutableArray<Location> ISymbol.Locations { get { return UnderlyingSymbol.Locations; } } ImmutableArray<SyntaxReference> ISymbol.DeclaringSyntaxReferences { get { return UnderlyingSymbol.DeclaringSyntaxReferences; } } ImmutableArray<AttributeData> ISymbol.GetAttributes() { return StaticCast<AttributeData>.From(UnderlyingSymbol.GetAttributes()); } Accessibility ISymbol.DeclaredAccessibility { get { return UnderlyingSymbol.DeclaredAccessibility; } } void ISymbol.Accept(SymbolVisitor visitor) { Accept(visitor); } protected abstract void Accept(SymbolVisitor visitor); TResult ISymbol.Accept<TResult>(SymbolVisitor<TResult> visitor) { return Accept(visitor); } protected abstract TResult Accept<TResult>(SymbolVisitor<TResult> visitor); string ISymbol.GetDocumentationCommentId() { return UnderlyingSymbol.GetDocumentationCommentId(); } string ISymbol.GetDocumentationCommentXml(CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) { return UnderlyingSymbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } string ISymbol.ToDisplayString(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayString(this, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToDisplayParts(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayParts(this, format); } string ISymbol.ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayString(this, GetCSharpSemanticModel(semanticModel), position, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayParts(this, GetCSharpSemanticModel(semanticModel), position, format); } internal static CSharpSemanticModel GetCSharpSemanticModel(SemanticModel semanticModel) { var csharpModel = semanticModel as CSharpSemanticModel; if (csharpModel == null) { throw new ArgumentException(CSharpResources.WrongSemanticModelType, LanguageNames.CSharp); } return csharpModel; } SymbolKind ISymbol.Kind => UnderlyingSymbol.Kind; string ISymbol.Language => LanguageNames.CSharp; string ISymbol.Name => UnderlyingSymbol.Name; string ISymbol.MetadataName => UnderlyingSymbol.MetadataName; IAssemblySymbol ISymbol.ContainingAssembly => UnderlyingSymbol.ContainingAssembly.GetPublicSymbol(); IModuleSymbol ISymbol.ContainingModule => UnderlyingSymbol.ContainingModule.GetPublicSymbol(); INamespaceSymbol ISymbol.ContainingNamespace => UnderlyingSymbol.ContainingNamespace.GetPublicSymbol(); bool ISymbol.IsDefinition => UnderlyingSymbol.IsDefinition; bool ISymbol.IsStatic { get { return UnderlyingSymbol.IsStatic; } } bool ISymbol.IsVirtual { get { return UnderlyingSymbol.IsVirtual; } } bool ISymbol.IsOverride { get { return UnderlyingSymbol.IsOverride; } } bool ISymbol.IsAbstract { get { return UnderlyingSymbol.IsAbstract; } } bool ISymbol.IsSealed { get { return UnderlyingSymbol.IsSealed; } } bool ISymbol.IsExtern => UnderlyingSymbol.IsExtern; bool ISymbol.IsImplicitlyDeclared => UnderlyingSymbol.IsImplicitlyDeclared; bool ISymbol.CanBeReferencedByName => UnderlyingSymbol.CanBeReferencedByName; bool ISymbol.HasUnsupportedMetadata => UnderlyingSymbol.HasUnsupportedMetadata; public sealed override string ToString() { return SymbolDisplay.ToDisplayString(this); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../VBResources.resx"> <body> <trans-unit id="ERR_AssignmentInitOnly"> <source>Init-only property '{0}' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor.</source> <target state="translated">Init only 属性 "{0}" 只能由对象成员初始值设定项分配,或在实例构造函数中的 "Me"、"MyClass" 或 "MyBase" 上分配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadSwitchValue"> <source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source> <target state="translated">命令行语法错误:“{0}”不是“{1}”选项的有效值。值的格式必须为 "{2}"。</target> <note /> </trans-unit> <trans-unit id="ERR_CommentsAfterLineContinuationNotAvailable1"> <source>Please use language version {0} or greater to use comments after line continuation character.</source> <target state="translated">请使用语言版本 {0} 或更高版本,以在行继续符后使用注释。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">无法嵌入类型“{0}”,因为它有非抽象成员。请考虑将“嵌入互操作类型”属性设置为 false。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir"> <source>Multiple analyzer config files cannot be in the same directory ('{0}').</source> <target state="translated">多个分析器配置文件不能位于同一目录({0})中。</target> <note /> </trans-unit> <trans-unit id="ERR_OverridingInitOnlyProperty"> <source>'{0}' cannot override init-only '{1}'.</source> <target state="translated">"{0}" 无法重写 init-only "{1}"。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyDoesntImplementInitOnly"> <source>Init-only '{0}' cannot be implemented.</source> <target state="translated">无法实现 init-only "{0}"。</target> <note /> </trans-unit> <trans-unit id="ERR_ReAbstractionInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">无法嵌入类型“{0}”,因为它有基本接口成员的重新抽象。请考虑将“嵌入互操作类型”属性设置为 false。</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation"> <source>Target runtime doesn't support default interface implementation.</source> <target state="translated">目标运行时不支持默认接口实现。</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember"> <source>Target runtime doesn't support 'Protected', 'Protected Friend', or 'Private Protected' accessibility for a member of an interface.</source> <target state="translated">目标运行时不支持对接口的成员使用 "Protected"、"Protected Friend" 或 "Private Protected" 辅助功能。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedEventNeedsHandlerInTheSameType"> <source>Events of shared WithEvents variables cannot be handled by methods in a different type.</source> <target state="translated">共享 WithEvents 变量的事件不能由其他类型的方法处理。</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyNotSupported"> <source>'UnmanagedCallersOnly' attribute is not supported.</source> <target state="translated">不支持 "UnmanagedCallersOnly" 属性。</target> <note /> </trans-unit> <trans-unit id="FEATURE_CallerArgumentExpression"> <source>caller argument expression</source> <target state="new">caller argument expression</target> <note /> </trans-unit> <trans-unit id="FEATURE_CommentsAfterLineContinuation"> <source>comments after line continuation</source> <target state="translated">行继续符之后的注释</target> <note /> </trans-unit> <trans-unit id="FEATURE_InitOnlySettersUsage"> <source>assigning to or passing 'ByRef' properties with init-only setters</source> <target state="translated">通过 init-only 资源库分配或传递 "ByRef" 属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_UnconstrainedTypeParameterInConditional"> <source>unconstrained type parameters in binary conditional expressions</source> <target state="translated">二进制条件表达式中的无约束类型参数</target> <note /> </trans-unit> <trans-unit id="IDS_VBCHelp"> <source> Visual Basic Compiler Options - OUTPUT FILE - -out:&lt;file&gt; Specifies the output file name. -target:exe Create a console application (default). (Short form: -t) -target:winexe Create a Windows application. -target:library Create a library assembly. -target:module Create a module that can be added to an assembly. -target:appcontainerexe Create a Windows application that runs in AppContainer. -target:winmdobj Create a Windows Metadata intermediate file -doc[+|-] Generates XML documentation file. -doc:&lt;file&gt; Generates XML documentation file to &lt;file&gt;. -refout:&lt;file&gt; Reference assembly output to generate - INPUT FILES - -addmodule:&lt;file_list&gt; Reference metadata from the specified modules -link:&lt;file_list&gt; Embed metadata from the specified interop assembly. (Short form: -l) -recurse:&lt;wildcard&gt; Include all files in the current directory and subdirectories according to the wildcard specifications. -reference:&lt;file_list&gt; Reference metadata from the specified assembly. (Short form: -r) -analyzer:&lt;file_list&gt; Run the analyzers from this assembly (Short form: -a) -additionalfile:&lt;file list&gt; Additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings. - RESOURCES - -linkresource:&lt;resinfo&gt; Links the specified file as an external assembly resource. resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (Short form: -linkres) -nowin32manifest The default manifest should not be embedded in the manifest section of the output PE. -resource:&lt;resinfo&gt; Adds the specified file as an embedded assembly resource. resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (Short form: -res) -win32icon:&lt;file&gt; Specifies a Win32 icon file (.ico) for the default Win32 resources. -win32manifest:&lt;file&gt; The provided file is embedded in the manifest section of the output PE. -win32resource:&lt;file&gt; Specifies a Win32 resource file (.res). - CODE GENERATION - -optimize[+|-] Enable optimizations. -removeintchecks[+|-] Remove integer checks. Default off. -debug[+|-] Emit debugging information. -debug:full Emit full debugging information (default). -debug:pdbonly Emit full debugging information. -debug:portable Emit cross-platform debugging information. -debug:embedded Emit cross-platform debugging information into the target .dll or .exe. -deterministic Produce a deterministic assembly (including module version GUID and timestamp) -refonly Produce a reference assembly in place of the main output -instrument:TestCoverage Produce an assembly instrumented to collect coverage information -sourcelink:&lt;file&gt; Source link info to embed into PDB. - ERRORS AND WARNINGS - -nowarn Disable all warnings. -nowarn:&lt;number_list&gt; Disable a list of individual warnings. -warnaserror[+|-] Treat all warnings as errors. -warnaserror[+|-]:&lt;number_list&gt; Treat a list of warnings as errors. -ruleset:&lt;file&gt; Specify a ruleset file that disables specific diagnostics. -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] Specify a file to log all compiler and analyzer diagnostics in SARIF format. sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 both mean SARIF version 2.1.0. -reportanalyzer Report additional analyzer information, such as execution time. -skipanalyzers[+|-] Skip execution of diagnostic analyzers. - LANGUAGE - -define:&lt;symbol_list&gt; Declare global conditional compilation symbol(s). symbol_list:name=value,... (Short form: -d) -imports:&lt;import_list&gt; Declare global Imports for namespaces in referenced metadata files. import_list:namespace,... -langversion:? Display the allowed values for language version -langversion:&lt;string&gt; Specify language version such as `default` (latest major version), or `latest` (latest version, including minor versions), or specific versions like `14` or `15.3` -optionexplicit[+|-] Require explicit declaration of variables. -optioninfer[+|-] Allow type inference of variables. -rootnamespace:&lt;string&gt; Specifies the root Namespace for all type declarations. -optionstrict[+|-] Enforce strict language semantics. -optionstrict:custom Warn when strict language semantics are not respected. -optioncompare:binary Specifies binary-style string comparisons. This is the default. -optioncompare:text Specifies text-style string comparisons. - MISCELLANEOUS - -help Display this usage message. (Short form: -?) -noconfig Do not auto-include VBC.RSP file. -nologo Do not display compiler copyright banner. -quiet Quiet output mode. -verbose Display verbose messages. -parallel[+|-] Concurrent build. -version Display the compiler version number and exit. - ADVANCED - -baseaddress:&lt;number&gt; The base address for a library or module (hex). -checksumalgorithm:&lt;alg&gt; Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default). -codepage:&lt;number&gt; Specifies the codepage to use when opening source files. -delaysign[+|-] Delay-sign the assembly using only the public portion of the strong name key. -publicsign[+|-] Public-sign the assembly using only the public portion of the strong name key. -errorreport:&lt;string&gt; Specifies how to handle internal compiler errors; must be prompt, send, none, or queue (default). -filealign:&lt;number&gt; Specify the alignment used for output file sections. -highentropyva[+|-] Enable high-entropy ASLR. -keycontainer:&lt;string&gt; Specifies a strong name key container. -keyfile:&lt;file&gt; Specifies a strong name key file. -libpath:&lt;path_list&gt; List of directories to search for metadata references. (Semi-colon delimited.) -main:&lt;class&gt; Specifies the Class or Module that contains Sub Main. It can also be a Class that inherits from System.Windows.Forms.Form. (Short form: -m) -moduleassemblyname:&lt;string&gt; Name of the assembly which this module will be a part of. -netcf Target the .NET Compact Framework. -nostdlib Do not reference standard libraries (system.dll and VBC.RSP file). -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... Specify a mapping for source path names output by the compiler. -platform:&lt;string&gt; Limit which platforms this code can run on; must be x86, x64, Itanium, arm, arm64 AnyCPU32BitPreferred or anycpu (default). -preferreduilang Specify the preferred output language name. -nosdkpath Disable searching the default SDK path for standard library assemblies. -sdkpath:&lt;path&gt; Location of the .NET Framework SDK directory (mscorlib.dll). -subsystemversion:&lt;version&gt; Specify subsystem version of the output PE. version:&lt;number&gt;[.&lt;number&gt;] -utf8output[+|-] Emit compiler output in UTF8 character encoding. @&lt;file&gt; Insert command-line settings from a text file -vbruntime[+|-|*] Compile with/without the default Visual Basic runtime. -vbruntime:&lt;file&gt; Compile with the alternate Visual Basic runtime in &lt;file&gt;. </source> <target state="translated"> Visual Basic 编译器选项 - 输出文件 - -out:&lt;file&gt; 指定输出文件名称。 -target:exe 创建控制台应用程序(默认)。 (缩写: -t) -target:winexe 创建 Windows 应用程序。 -target:library 创建库程序集。 -target:module 创建可添加到程序集的 模块。 -target:appcontainerexe 创建在 AppContainer 中运行的 Windows 应用程序。 -target:winmdobj 创建 Windows 元数据中间文件 -doc[+|-] 生成 XML 文档文件。 -doc:&lt;file&gt; 将 XML 文档文件生成到 &lt;file&gt; -refout:&lt;file&gt; 引用要生成的引用程序集 - 输入文件 - -addmodule:&lt;file_list&gt; 从指定模块中引用元数据 -link:&lt;file_list&gt; 嵌入指定互操作程序集中的 元数据。(缩写: -l) -recurse:&lt;wildcard&gt; 根据通配符规范包括 当前目录和子目录中 的所有文件。 -reference:&lt;file_list&gt; 从指定程序集中引用 元数据。(缩写: -r) -analyzer:&lt;file_list&gt; 运行此程序集的分析器 (缩写: -a) -additionalfile:&lt;file list&gt; 不直接影响代码 生成但可能被分析器用于生成 错误或警告的其他文件。 - 资源 - -linkresource:&lt;resinfo&gt; 将指定文件作为外部 程序集资源进行链接。 resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (缩写: -linkres) -nowin32manifest 默认清单不应嵌入 输出 PE 的清单部分。 -resource:&lt;resinfo&gt; 将指定文件作为嵌入式 程序集资源进行添加。 resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (缩写: -res) -win32icon:&lt;file&gt; 为默认的 Win32 资源 指定 Win32 图标文件(.ico)。 -win32manifest:&lt;file&gt; 提供的文件嵌入在 输出 PE 的清单部分。 -win32resource:&lt;file&gt; 指定 Win32 资源文件(.res)。 - 代码生成 - -optimize[+|-] 启用优化。 -removeintchecks[+|-] 删除整数检查。默认为“关”。 -debug[+|-] 发出调试信息。 -debug:full 发出完全调试信息(默认)。 -debug:pdbonly 发出完全调试信息。 -debug:portable 发出跨平台调试信息。 -debug:embedded 发出跨平台调试信息到 目标 .dll 或 .exe. -deterministic 生成确定性程序集 (包括模块版本 GUID 和时间戳) -refonly 生成引用程序集来替代主要输出 -instrument:TestCoverage 生成对其检测以收集覆盖率信息的t 程序集 -sourcelink:&lt;file&gt; 要嵌入到 PDB 中的源链接信息。 - 错误和警告 - -nowarn 禁用所有警告。 -nowarn:&lt;number_list&gt; 禁用个人警告列表。 -warnaserror[+|-] 将所有警告视为错误。 -warnaserror[+|-]:&lt;number_list&gt; 将警告列表视为错误。 -ruleset:&lt;file&gt; 指定禁用特定诊断的 规则集文件。 -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] 指定用于以 SARIF 格式记录所有编译器和分析器诊断的 文件。 sarif_version:{1|2|2.1} 默认为 1. 2 和 2.1 两者均表示 SARIF 版本 2.1.0。 -reportanalyzer 报告其他分析器信息,如 执行时间。 -skipanalyzers[+|-] 跳过诊断分析器的执行。 - 语言 - -define:&lt;symbol_list&gt; 声明全局条件编译 符号。symbol_list:name=value,... (缩写: -d) -imports:&lt;import_list&gt; 为引用的元数据文件中的命名空间声明 全局导入。 import_list:namespace,... -langversion:? 显示允许的语言版本值 -langversion:&lt;string&gt; 指定语言版本,如 “default” (最新主要版本)、 “latest” (最新版本,包括次要版本) 或 “14”、”15.3”等特定版本 -optionexplicit[+|-] 需要显示声明变量。 -optioninfer[+|-] 允许变量的类型推理。 -rootnamespace:&lt;string&gt; 指定所有类型声明的根 命名空间。 -optionstrict[+|-] 强制严格语言语义。 -optionstrict:custom 不遵从严格语言语义时 发出警告。 -optioncompare:binary 指定二进制样式的字符串比较。 这是默认设置。 -optioncompare:text 指定文本样式字符串比较。 - 杂项 - -help 显示此用法消息。(缩写: -?) -noconfig 不自动包括 VBC.RSP 文件。 -nologo 不显示编译器版权横幅。 -quiet 安静输出模式。 -verbose 显示详细消息。 -parallel[+|-] 并发生成。 -version 显示编译器版本号并退出。 - 高级 - -baseaddress:&lt;number&gt; 库或模块的基址 (十六进制)。 -checksumalgorithm:&lt;alg&gt; 指定计算存储在 PDB 中的源文件校验和 的算法。支持的值是: SHA1 或 SHA256 (默认)。 -codepage:&lt;number&gt; 指定打开源文件时要使用的 代码页。 -delaysign[+|-] 仅使用强名称密钥的公共部分 对程序集进行延迟签名。 -publicsign[+|-] 仅使用强名称密钥的公共部分 对程序集进行公共签名 -errorreport:&lt;string&gt; 指定处理内部编译器错误的方式; 必须是 prompt、send、none 或 queue (默认)。 -filealign:&lt;number&gt; 指定用于输出文件节的对齐 方式。 -highentropyva[+|-] 启用高平均信息量的 ASLR。 -keycontainer:&lt;string&gt; 指定强名称密钥容器。 -keyfile:&lt;file&gt; 指定强名称密钥文件。 -libpath:&lt;path_list&gt; 搜索元数据引用的目录 列表。(分号分隔。) -main:&lt;class&gt; 指定包含 Sub Main 的类 或模块。也可为从 System.Windows.Forms.Form 继承的类。 (缩写: -m) -moduleassemblyname:&lt;string&gt; 此模块所属程序集 的名称。 -netcf 以 .NET Compact Framework 为目标。 -nostdlib 不引用标准库 (system.dll 和 VBC.RSP 文件)。 -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... 按编译器指定源路径名称输出的 映射。 -platform:&lt;string&gt; 限制此代码可以在其上运行的平台; 必须是 x86、x64、Itanium、arm、arm64、 AnyCPU32BitPreferred 或 anycpu (默认)。 -preferreduilang 指定首选输出语言名称。 -nosdkpath 禁用搜索标准库程序集的默认 SDK 路径 -sdkpath:&lt;path&gt; .NET Framework SDK 目录的位置 (mscorlib.dll). -subsystemversion:&lt;version&gt; 指定输出 PE 的子系统版本。 version:&lt;number&gt;[.&lt;number&gt;] -utf8output[+|-] 以 UTF8 字符编码格式 发出编译器输出。 @&lt;file&gt; 从文本文件插入命令行设置 -vbruntime[+|-|*] 用/不用默认的 Visual Basic 运行时进行编译。 -vbruntime:&lt;file&gt; 使用 &lt;file&gt; 中的备用 Visual Basic 运行时 进行编译。 </target> <note /> </trans-unit> <trans-unit id="ThereAreNoFunctionPointerTypesInVB"> <source>There are no function pointer types in VB.</source> <target state="translated">VB 中没有任何函数指针类型。</target> <note /> </trans-unit> <trans-unit id="ThereAreNoNativeIntegerTypesInVB"> <source>There are no native integer types in VB.</source> <target state="translated">VB 中没有任何本机整数类型。</target> <note /> </trans-unit> <trans-unit id="Trees0"> <source>trees({0})</source> <target state="translated">树({0})</target> <note /> </trans-unit> <trans-unit id="TreesMustHaveRootNode"> <source>trees({0}) must have root node with SyntaxKind.CompilationUnit.</source> <target state="translated">树({0}) 必须具有带 SyntaxKind.CompilationUnit 的根节点。</target> <note /> </trans-unit> <trans-unit id="CannotAddCompilerSpecialTree"> <source>Cannot add compiler special tree</source> <target state="translated">无法添加特定于编译器的树</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeAlreadyPresent"> <source>Syntax tree already present</source> <target state="translated">语法树已存在</target> <note /> </trans-unit> <trans-unit id="SubmissionCanHaveAtMostOneSyntaxTree"> <source>Submission can have at most one syntax tree.</source> <target state="translated">提交最多可以具有一个语法树。</target> <note /> </trans-unit> <trans-unit id="CannotRemoveCompilerSpecialTree"> <source>Cannot remove compiler special tree</source> <target state="translated">无法移除特定于编译器的树</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeNotFoundToRemove"> <source>SyntaxTree '{0}' not found to remove</source> <target state="translated">未找到要删除的 SyntaxTree“{0}”</target> <note /> </trans-unit> <trans-unit id="TreeMustHaveARootNodeWithCompilationUnit"> <source>Tree must have a root node with SyntaxKind.CompilationUnit</source> <target state="translated">树必须具有带 SyntaxKind.CompilationUnit 的根节点</target> <note /> </trans-unit> <trans-unit id="CompilationVisualBasic"> <source>Compilation (Visual Basic): </source> <target state="translated">编译(Visual Basic):</target> <note /> </trans-unit> <trans-unit id="NodeIsNotWithinSyntaxTree"> <source>Node is not within syntax tree</source> <target state="translated">节点不在语法树中</target> <note /> </trans-unit> <trans-unit id="CantReferenceCompilationFromTypes"> <source>Can't reference compilation of type '{0}' from {1} compilation.</source> <target state="translated">无法从 {1} 编译引用类型为“{0}”的编译。</target> <note /> </trans-unit> <trans-unit id="PositionOfTypeParameterTooLarge"> <source>position of type parameter too large</source> <target state="translated">类型参数的位置太大</target> <note /> </trans-unit> <trans-unit id="AssociatedTypeDoesNotHaveTypeParameters"> <source>Associated type does not have type parameters</source> <target state="translated">关联类型没有类型参数</target> <note /> </trans-unit> <trans-unit id="IDS_FunctionReturnType"> <source>function return type</source> <target state="translated">函数返回类型</target> <note /> </trans-unit> <trans-unit id="TypeArgumentCannotBeNothing"> <source>Type argument cannot be Nothing</source> <target state="translated">类型参数不能是任何内容</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework"> <source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source> <target state="translated">包含类型“{1}”的程序集“{0}”引用了 .NET Framework,而此操作不受支持。</target> <note>{1} is the type that was loaded, {0} is the containing assembly.</note> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework_Title"> <source>The loaded assembly references .NET Framework, which is not supported.</source> <target state="translated">加载的程序集引用了 .NET Framework,而此操作不受支持。</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title"> <source>The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title"> <source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration"> <source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">生成器“{0}”未能生成源。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}”</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">生成器引发以下异常: “{0}”。</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Title"> <source>Generator failed to generate source.</source> <target state="translated">生成器无法生成源。</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization"> <source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">生成器“{0}”未能初始化。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}”</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">生成器引发以下异常: “{0}”。</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Title"> <source>Generator failed to initialize.</source> <target state="translated">生成器初始化失败。</target> <note /> </trans-unit> <trans-unit id="WrongNumberOfTypeArguments"> <source>Wrong number of type arguments</source> <target state="translated">类型参数的数目不正确</target> <note /> </trans-unit> <trans-unit id="ERR_FileNotFound"> <source>file '{0}' could not be found</source> <target state="translated">找不到文件“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_NoResponseFile"> <source>unable to open response file '{0}'</source> <target state="translated">无法打开响应文件“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentRequired"> <source>option '{0}' requires '{1}'</source> <target state="translated">选项“{0}”需要“{1}”</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchNeedsBool"> <source>option '{0}' can be followed only by '+' or '-'</source> <target state="translated">选项“{0}”后面只能跟“+”或“-”</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSwitchValue"> <source>the value '{1}' is invalid for option '{0}'</source> <target state="translated">值“{1}”对选项“{0}”无效</target> <note /> </trans-unit> <trans-unit id="ERR_MutuallyExclusiveOptions"> <source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source> <target state="translated">无法同时指定编译选项“{0}”和“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang"> <source>The language name '{0}' is invalid.</source> <target state="translated">语言名“{0}”无效。</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang_Title"> <source>The language name for /preferreduilang is invalid</source> <target state="translated">/preferreduilang 的语言名称无效</target> <note /> </trans-unit> <trans-unit id="ERR_VBCoreNetModuleConflict"> <source>The options /vbruntime* and /target:module cannot be combined.</source> <target state="translated">/vbruntime* 选项不能与 /target:module 选项组合。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFormatForGuidForOption"> <source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source> <target state="translated">命令行语法错误: Guid 格式“{0}”对于选项“{1}”无效</target> <note /> </trans-unit> <trans-unit id="ERR_MissingGuidForOption"> <source>Command-line syntax error: Missing Guid for option '{1}'</source> <target state="translated">命令行语法错误: 选项“{1}”缺少 Guid</target> <note /> </trans-unit> <trans-unit id="ERR_BadChecksumAlgorithm"> <source>Algorithm '{0}' is not supported</source> <target state="translated">不支持算法“{0}”</target> <note /> </trans-unit> <trans-unit id="WRN_BadSwitch"> <source>unrecognized option '{0}'; ignored</source> <target state="translated">无法识别的选项“{0}”;已忽略</target> <note /> </trans-unit> <trans-unit id="WRN_BadSwitch_Title"> <source>Unrecognized command-line option</source> <target state="translated">无法识别的命令行选项</target> <note /> </trans-unit> <trans-unit id="ERR_NoSources"> <source>no input sources specified</source> <target state="translated">未指定输入源</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded"> <source>source file '{0}' specified multiple times</source> <target state="translated">源文件“{0}”指定了多次</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded_Title"> <source>Source file specified multiple times</source> <target state="translated">多次指定源文件</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenFileWrite"> <source>can't open '{0}' for writing: {1}</source> <target state="translated">无法打开“{0}”进行写入: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadCodepage"> <source>code page '{0}' is invalid or not installed</source> <target state="translated">代码页“{0}”无效或未安装</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryFile"> <source>the file '{0}' is not a text file</source> <target state="translated">文件“{0}”不是文本文件</target> <note /> </trans-unit> <trans-unit id="ERR_LibNotFound"> <source>could not find library '{0}'</source> <target state="translated">找不到库“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataReferencesNotSupported"> <source>Metadata references not supported.</source> <target state="translated">不支持元数据引用。</target> <note /> </trans-unit> <trans-unit id="ERR_IconFileAndWin32ResFile"> <source>cannot specify both /win32icon and /win32resource</source> <target state="translated">不能同时指定 /win32icon 和 /win32resource</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigInResponseFile"> <source>ignoring /noconfig option because it was specified in a response file</source> <target state="translated">/noconfig 选项是在响应文件中指定的,因此被忽略</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigInResponseFile_Title"> <source>Ignoring /noconfig option because it was specified in a response file</source> <target state="translated">/noconfig 选项是在响应文件中指定的,因此被忽略</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidWarningId"> <source>warning number '{0}' for the option '{1}' is either not configurable or not valid</source> <target state="translated">选项“{1}”的警告编号“{0}”不可配置或无效</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidWarningId_Title"> <source>Warning number is either not configurable or not valid</source> <target state="translated">警告编号不可配置或无效</target> <note /> </trans-unit> <trans-unit id="ERR_NoSourcesOut"> <source>cannot infer an output file name from resource only input files; provide the '/out' option</source> <target state="translated">无法从仅资源输入文件推理出输出文件名;提供“/out”选项</target> <note /> </trans-unit> <trans-unit id="ERR_NeedModule"> <source>the /moduleassemblyname option may only be specified when building a target of type 'module'</source> <target state="translated">只有在生成“module”类型的目标时才能指定 /moduleassemblyname 选项</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyName"> <source>'{0}' is not a valid value for /moduleassemblyname</source> <target state="translated">“{0}”不是 /moduleassemblyname 的有效值</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingManifestSwitches"> <source>Error embedding Win32 manifest: Option /win32manifest conflicts with /nowin32manifest.</source> <target state="translated">嵌入 Win32 清单时出错: 选项 /win32manifest 与 /nowin32manifest 冲突。</target> <note /> </trans-unit> <trans-unit id="WRN_IgnoreModuleManifest"> <source>Option /win32manifest ignored. It can be specified only when the target is an assembly.</source> <target state="translated">已忽略选项 /win32manifest。只有在目标是程序集时才能指定该选项。</target> <note /> </trans-unit> <trans-unit id="WRN_IgnoreModuleManifest_Title"> <source>Option /win32manifest ignored</source> <target state="translated">/win32manifest 选项已忽略</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInNamespace"> <source>Statement is not valid in a namespace.</source> <target state="translated">语句在命名空间中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_UndefinedType1"> <source>Type '{0}' is not defined.</source> <target state="translated">未定义类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingNext"> <source>'Next' expected.</source> <target state="translated">'应为 "Next"。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalCharConstant"> <source>Character constant must contain exactly one character.</source> <target state="translated">字符常量必须正好包含一个字符。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedAssemblyEvent3"> <source>Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project.</source> <target state="translated">需要对程序集“{0}”(包含事件“{1}”的定义)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedModuleEvent3"> <source>Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project.</source> <target state="translated">需要对模块“{0}”(包含事件“{1}”的定义)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_LbExpectedEndIf"> <source>'#If' block must end with a matching '#End If'.</source> <target state="translated">'"#If" 块必须以匹配的 "#End If" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_LbNoMatchingIf"> <source>'#ElseIf', '#Else', or '#End If' must be preceded by a matching '#If'.</source> <target state="translated">'"#ElseIf"、"#Else" 或 "#End If" 前面必须是匹配的 "#If"。</target> <note /> </trans-unit> <trans-unit id="ERR_LbBadElseif"> <source>'#ElseIf' must be preceded by a matching '#If' or '#ElseIf'.</source> <target state="translated">'"#ElseIf" 前面必须是匹配的 "#If" 或 "#ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromRestrictedType1"> <source>Inheriting from '{0}' is not valid.</source> <target state="translated">从“{0}”继承无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvOutsideProc"> <source>Labels are not valid outside methods.</source> <target state="translated">标签在方法外部无效。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateCantImplement"> <source>Delegates cannot implement interface methods.</source> <target state="translated">委托无法实现接口方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateCantHandleEvents"> <source>Delegates cannot handle events.</source> <target state="translated">委托无法处理事件。</target> <note /> </trans-unit> <trans-unit id="ERR_IsOperatorRequiresReferenceTypes1"> <source>'Is' operator does not accept operands of type '{0}'. Operands must be reference or nullable types.</source> <target state="translated">'“Is”运算符不接受类型为“{0}”的操作数。操作数必须是引用类型或可以为 null 的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOfRequiresReferenceType1"> <source>'TypeOf ... Is' requires its left operand to have a reference type, but this operand has the value type '{0}'.</source> <target state="translated">'“TypeOf ... Is”要求它的左操作数具有引用类型,但此操作数具有值类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyHasSet"> <source>Properties declared 'ReadOnly' cannot have a 'Set'.</source> <target state="translated">声明为 "ReadOnly" 的属性不能有 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_WriteOnlyHasGet"> <source>Properties declared 'WriteOnly' cannot have a 'Get'.</source> <target state="translated">声明为 "WriteOnly" 的属性不能有 "Get"。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideProc"> <source>Statement is not valid inside a method.</source> <target state="translated">语句在方法内部无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideBlock"> <source>Statement is not valid inside '{0}' block.</source> <target state="translated">语句在“{0}”块内部无效。</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedExpressionStatement"> <source>Expression statement is only allowed at the end of an interactive submission.</source> <target state="translated">只允许在交互提交结尾处使用表达式语句。</target> <note /> </trans-unit> <trans-unit id="ERR_EndProp"> <source>Property missing 'End Property'.</source> <target state="translated">Property 缺少 "End Property"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndSubExpected"> <source>'End Sub' expected.</source> <target state="translated">'应为 "End Sub"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndFunctionExpected"> <source>'End Function' expected.</source> <target state="translated">'应为 "End Function"。</target> <note /> </trans-unit> <trans-unit id="ERR_LbElseNoMatchingIf"> <source>'#Else' must be preceded by a matching '#If' or '#ElseIf'.</source> <target state="translated">'"#Else" 前面必须是匹配的 "#If" 或 "#ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_CantRaiseBaseEvent"> <source>Derived classes cannot raise base class events.</source> <target state="translated">派生类不能引发基类事件。</target> <note /> </trans-unit> <trans-unit id="ERR_TryWithoutCatchOrFinally"> <source>Try must have at least one 'Catch' or a 'Finally'.</source> <target state="translated">Try 必须至少有一个 "Catch" 或 "Finally"。</target> <note /> </trans-unit> <trans-unit id="ERR_EventsCantBeFunctions"> <source>Events cannot have a return type.</source> <target state="translated">事件不能有返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndBrack"> <source>Bracketed identifier is missing closing ']'.</source> <target state="translated">用括号标识的标识符缺少右边的 "]"。</target> <note /> </trans-unit> <trans-unit id="ERR_Syntax"> <source>Syntax error.</source> <target state="translated">语法错误。</target> <note /> </trans-unit> <trans-unit id="ERR_Overflow"> <source>Overflow.</source> <target state="translated">溢出。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalChar"> <source>Character is not valid.</source> <target state="translated">字符无效。</target> <note /> </trans-unit> <trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected"> <source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source> <target state="translated">已指定 stdin 参数 "-",但尚未从标准输入流重定向输入。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsObjectOperand1"> <source>Option Strict On prohibits operands of type Object for operator '{0}'.</source> <target state="translated">Option Strict On 禁止将 Object 类型的操作数用于运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_LoopControlMustNotBeProperty"> <source>Loop control variable cannot be a property or a late-bound indexed array.</source> <target state="translated">循环控制变量不能是属性或后期绑定索引数组。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodBodyNotAtLineStart"> <source>First statement of a method body cannot be on the same line as the method declaration.</source> <target state="translated">方法主体的第一条语句和方法声明不能位于同一行。</target> <note /> </trans-unit> <trans-unit id="ERR_MaximumNumberOfErrors"> <source>Maximum number of errors has been exceeded.</source> <target state="translated">已超出最大错误数。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfKeywordNotInInstanceMethod1"> <source>'{0}' is valid only within an instance method.</source> <target state="translated">“{0}”仅在实例方法中有效。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfKeywordFromStructure1"> <source>'{0}' is not valid within a structure.</source> <target state="translated">“{0}”在结构中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeConstructor1"> <source>Attribute constructor has a parameter of type '{0}', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types.</source> <target state="translated">特性构造函数具有“{0}”类型的参数,此参数不是整型、浮点型或枚举类型,也不是 Object、Char、String、Boolean、System.Type 之一或这些类型的一维数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayWithOptArgs"> <source>Method cannot have both a ParamArray and Optional parameters.</source> <target state="translated">方法不能同时具有 ParamArray 和 Optional 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedArray1"> <source>'{0}' statement requires an array.</source> <target state="translated">“{0}”语句需要数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayNotArray"> <source>ParamArray parameter must be an array.</source> <target state="translated">ParamArray 参数必须是一个数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayRank"> <source>ParamArray parameter must be a one-dimensional array.</source> <target state="translated">ParamArray 参数必须是一维数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayRankLimit"> <source>Array exceeds the limit of 32 dimensions.</source> <target state="translated">数组超过了 32 维数限制。</target> <note /> </trans-unit> <trans-unit id="ERR_AsNewArray"> <source>Arrays cannot be declared with 'New'.</source> <target state="translated">不能用 "New" 声明数组。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyArgs1"> <source>Too many arguments to '{0}'.</source> <target state="translated">“{0}”的参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedCase"> <source>Statements and labels are not valid between 'Select Case' and first 'Case'.</source> <target state="translated">位于 "Select Case" 与第一个 "Case" 之间的语句和标签无效。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredConstExpr"> <source>Constant expression is required.</source> <target state="translated">要求常量表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredConstConversion2"> <source>Conversion from '{0}' to '{1}' cannot occur in a constant expression.</source> <target state="translated">常量表达式中不能发生从“{0}”到“{1}”的转换。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMe"> <source>'Me' cannot be the target of an assignment.</source> <target state="translated">'"Me" 不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyAssignment"> <source>'ReadOnly' variable cannot be the target of an assignment.</source> <target state="translated">'"ReadOnly" 变量不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitSubOfFunc"> <source>'Exit Sub' is not valid in a Function or Property.</source> <target state="translated">'"Exit Sub" 在函数或属性中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitPropNot"> <source>'Exit Property' is not valid in a Function or Sub.</source> <target state="translated">'“Exit Property”在函数或 Sub 中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitFuncOfSub"> <source>'Exit Function' is not valid in a Sub or Property.</source> <target state="translated">'"Exit Function" 在 Sub 或属性中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_LValueRequired"> <source>Expression is a value and therefore cannot be the target of an assignment.</source> <target state="translated">表达式是一个值,因此不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ForIndexInUse1"> <source>For loop control variable '{0}' already in use by an enclosing For loop.</source> <target state="translated">For 循环控制变量“{0}”已由封闭 For 循环使用。</target> <note /> </trans-unit> <trans-unit id="ERR_NextForMismatch1"> <source>Next control variable does not match For loop control variable '{0}'.</source> <target state="translated">Next 控制变量与 For 循环控制变量“{0}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_CaseElseNoSelect"> <source>'Case Else' can only appear inside a 'Select Case' statement.</source> <target state="translated">'“Case Else”只能出现在“Select Case”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_CaseNoSelect"> <source>'Case' can only appear inside a 'Select Case' statement.</source> <target state="translated">'“Case”只能出现在“Select Case”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_CantAssignToConst"> <source>Constant cannot be the target of an assignment.</source> <target state="translated">常量不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedSubscript"> <source>Named arguments are not valid as array subscripts.</source> <target state="translated">命名参数作为数组下标无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndIf"> <source>'If' must end with a matching 'End If'.</source> <target state="translated">'“If”必须以匹配的“End If”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndWhile"> <source>'While' must end with a matching 'End While'.</source> <target state="translated">'“While”必须以匹配的“End While”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLoop"> <source>'Do' must end with a matching 'Loop'.</source> <target state="translated">'"Do" 必须以匹配的 "Loop" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedNext"> <source>'For' must end with a matching 'Next'.</source> <target state="translated">'"For" 必须以匹配的 "Next" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndWith"> <source>'With' must end with a matching 'End With'.</source> <target state="translated">'“With”必须以匹配的“End With”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ElseNoMatchingIf"> <source>'Else' must be preceded by a matching 'If' or 'ElseIf'.</source> <target state="translated">'"Else" 前面必须是匹配的 "If" 或 "ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndIfNoMatchingIf"> <source>'End If' must be preceded by a matching 'If'.</source> <target state="translated">'"End If" 前面必须是匹配的 "If"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndSelectNoSelect"> <source>'End Select' must be preceded by a matching 'Select Case'.</source> <target state="translated">'"End Select" 前面必须是匹配的 "Select Case"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitDoNotWithinDo"> <source>'Exit Do' can only appear inside a 'Do' statement.</source> <target state="translated">'"Exit Do" 只能出现在 "Do" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_EndWhileNoWhile"> <source>'End While' must be preceded by a matching 'While'.</source> <target state="translated">'“End While”前面必须是匹配的“While”。</target> <note /> </trans-unit> <trans-unit id="ERR_LoopNoMatchingDo"> <source>'Loop' must be preceded by a matching 'Do'.</source> <target state="translated">'"Loop" 前面必须是匹配的 "Do"。</target> <note /> </trans-unit> <trans-unit id="ERR_NextNoMatchingFor"> <source>'Next' must be preceded by a matching 'For'.</source> <target state="translated">'"Next" 前面必须是匹配的 "For"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndWithWithoutWith"> <source>'End With' must be preceded by a matching 'With'.</source> <target state="translated">'“End With”前面必须是匹配的“With”。</target> <note /> </trans-unit> <trans-unit id="ERR_MultiplyDefined1"> <source>Label '{0}' is already defined in the current method.</source> <target state="translated">当前方法中已定义了标签“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndSelect"> <source>'Select Case' must end with a matching 'End Select'.</source> <target state="translated">'“Select Case”必须以匹配的“End Select”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitForNotWithinFor"> <source>'Exit For' can only appear inside a 'For' statement.</source> <target state="translated">'"Exit For" 只能出现在 "For" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitWhileNotWithinWhile"> <source>'Exit While' can only appear inside a 'While' statement.</source> <target state="translated">'"Exit While" 只能出现在 "While" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyProperty1"> <source>'ReadOnly' property '{0}' cannot be the target of an assignment.</source> <target state="translated">'“ReadOnly”属性“{0}”不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitSelectNotWithinSelect"> <source>'Exit Select' can only appear inside a 'Select' statement.</source> <target state="translated">'"Exit Select" 只能出现在 "Select" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_BranchOutOfFinally"> <source>Branching out of a 'Finally' is not valid.</source> <target state="translated">从“Finally”中分支无效。</target> <note /> </trans-unit> <trans-unit id="ERR_QualNotObjectRecord1"> <source>'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'.</source> <target state="translated">'“!”要求其左操作数具有类型参数、类或接口类型,但此操作数的类型为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TooFewIndices"> <source>Number of indices is less than the number of dimensions of the indexed array.</source> <target state="translated">索引数少于索引数组的维数。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyIndices"> <source>Number of indices exceeds the number of dimensions of the indexed array.</source> <target state="translated">索引数超过索引数组的维数。</target> <note /> </trans-unit> <trans-unit id="ERR_EnumNotExpression1"> <source>'{0}' is an Enum type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个枚举类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeNotExpression1"> <source>'{0}' is a type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassNotExpression1"> <source>'{0}' is a class type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个类类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_StructureNotExpression1"> <source>'{0}' is a structure type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个结构类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceNotExpression1"> <source>'{0}' is an interface type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个接口类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotExpression1"> <source>'{0}' is a namespace and cannot be used as an expression.</source> <target state="translated">“{0}”是一个命名空间,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamespaceName1"> <source>'{0}' is not a valid name and cannot be used as the root namespace name.</source> <target state="translated">“{0}”不是有效名称,不能用作根命名空间名称。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlPrefixNotExpression"> <source>'{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object.</source> <target state="translated">“{0}”是 XML 前缀,不能用作表达式。请使用 GetXmlNamespace 运算符创建命名空间对象。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleExtends"> <source>'Inherits' can appear only once within a 'Class' statement and can only specify one class.</source> <target state="translated">'"Inherits" 只能在 "Class" 语句中出现一次,并且只能指定一个类。</target> <note /> </trans-unit> <trans-unit id="ERR_PropMustHaveGetSet"> <source>Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.</source> <target state="translated">不带 "ReadOnly" 或 "WriteOnly" 说明符的属性必须同时提供 "Get" 和 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_WriteOnlyHasNoWrite"> <source>'WriteOnly' property must provide a 'Set'.</source> <target state="translated">'"WriteOnly" 属性必须提供 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyHasNoGet"> <source>'ReadOnly' property must provide a 'Get'.</source> <target state="translated">'"ReadOnly" 属性必须提供 "Get"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttribute1"> <source>Attribute '{0}' is not valid: Incorrect argument value.</source> <target state="translated">特性“{0}”无效: 参数值不正确。</target> <note /> </trans-unit> <trans-unit id="ERR_LabelNotDefined1"> <source>Label '{0}' is not defined.</source> <target state="translated">未定义标签“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorCreatingWin32ResourceFile"> <source>Error creating Win32 resources: {0}</source> <target state="translated">创建 Win32 资源时出错: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_UnableToCreateTempFile"> <source>Cannot create temporary file: {0}</source> <target state="translated">无法创建临时文件: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNewCall2"> <source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">“{1}”的基类“{0}”没有不使用参数就可以调用的可访问“Sub New”,因此该“Sub New”的第一个语句必须是对“MyBase.New”或“MyClass.New”的调用。</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedMember3"> <source>{0} '{1}' must implement '{2}' for interface '{3}'.</source> <target state="translated">{0}“{1}”必须为接口“{3}”实现“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadWithRef"> <source>Leading '.' or '!' can only appear inside a 'With' statement.</source> <target state="translated">前导“.”或“!”只能出现在“With”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAccessCategoryUsed"> <source>Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.</source> <target state="translated">只能指定 "Public"、"Private"、"Protected"、"Friend"、"Protected Friend" 或 "Private Protected" 中的一个。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateModifierCategoryUsed"> <source>Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.</source> <target state="translated">只能指定 "NotOverridable"、"MustOverride" 或 "Overridable" 中的一个。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateSpecifier"> <source>Specifier is duplicated.</source> <target state="translated">说明符重复。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeConflict6"> <source>{0} '{1}' and {2} '{3}' conflict in {4} '{5}'.</source> <target state="translated">{0}“{1}”和 {2}“{3}”在 {4}“{5}”中冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedTypeKeyword"> <source>Keyword does not name a type.</source> <target state="translated">关键字没有指定类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtraSpecifiers"> <source>Specifiers valid only at the beginning of a declaration.</source> <target state="translated">说明符仅在声明的开始处有效。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedType"> <source>Type expected.</source> <target state="translated">应为类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidUseOfKeyword"> <source>Keyword is not valid as an identifier.</source> <target state="translated">关键字作为标识符无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndEnum"> <source>'End Enum' must be preceded by a matching 'Enum'.</source> <target state="translated">'“End Enum”前面必须是匹配的“Enum”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndEnum"> <source>'Enum' must end with a matching 'End Enum'.</source> <target state="translated">'"Enum" 必须以匹配的 "End Enum" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDeclaration"> <source>Declaration expected.</source> <target state="translated">应为声明。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayMustBeLast"> <source>End of parameter list expected. Cannot define parameters after a paramarray parameter.</source> <target state="translated">应为参数列表的结尾。不能在 Paramarray 参数后定义参数。</target> <note /> </trans-unit> <trans-unit id="ERR_SpecifiersInvalidOnInheritsImplOpt"> <source>Specifiers and attributes are not valid on this statement.</source> <target state="translated">说明符和特性在此语句上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSpecifier"> <source>Expected one of 'Dim', 'Const', 'Public', 'Private', 'Protected', 'Friend', 'Shadows', 'ReadOnly' or 'Shared'.</source> <target state="translated">应为“Dim”、“Const”、“Public”、“Private”、“Protected”、“Friend”、“Shadows”、“ReadOnly”或“Shared”中的一个。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedComma"> <source>Comma expected.</source> <target state="translated">应为逗号。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAs"> <source>'As' expected.</source> <target state="translated">'应为 "As"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedRparen"> <source>')' expected.</source> <target state="translated">'应为 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLparen"> <source>'(' expected.</source> <target state="translated">'应为“(”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNewInType"> <source>'New' is not valid in this context.</source> <target state="translated">'"New" 在此上下文中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedExpression"> <source>Expression expected.</source> <target state="translated">应为表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedOptional"> <source>'Optional' expected.</source> <target state="translated">'应为 "Optional"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIdentifier"> <source>Identifier expected.</source> <target state="translated">应为标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIntLiteral"> <source>Integer constant expected.</source> <target state="translated">应为整数常量。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEOS"> <source>End of statement expected.</source> <target state="translated">应为语句结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedForOptionStmt"> <source>'Option' must be followed by 'Compare', 'Explicit', 'Infer', or 'Strict'.</source> <target state="translated">'“Option”的后面必须跟有“Compare”、“Explicit”、“Infer”或“Strict”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionCompare"> <source>'Option Compare' must be followed by 'Text' or 'Binary'.</source> <target state="translated">'"Option Compare" 的后面必须跟有 "Text" 或 "Binary"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedOptionCompare"> <source>'Compare' expected.</source> <target state="translated">'应为 "Compare"。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowImplicitObject"> <source>Option Strict On requires all variable declarations to have an 'As' clause.</source> <target state="translated">Option Strict On 要求所有变量声明都有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsImplicitProc"> <source>Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.</source> <target state="translated">Option Strict On 要求所有函数、属性和运算符声明都有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsImplicitArgs"> <source>Option Strict On requires that all method parameters have an 'As' clause.</source> <target state="translated">Option Strict On 要求所有方法参数都有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidParameterSyntax"> <source>Comma or ')' expected.</source> <target state="translated">应为逗号或 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSubFunction"> <source>'Sub' or 'Function' expected.</source> <target state="translated">'应为“Sub”或“Function”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedStringLiteral"> <source>String constant expected.</source> <target state="translated">应为字符串常量。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingLibInDeclare"> <source>'Lib' expected.</source> <target state="translated">'应为 "Lib"。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateNoInvoke1"> <source>Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call.</source> <target state="translated">委托类“{0}”没有 Invoke 方法,所以此类型的表达式不能作为方法调用的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingIsInTypeOf"> <source>'Is' expected.</source> <target state="translated">'应为 "Is"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateOption1"> <source>'Option {0}' statement can only appear once per file.</source> <target state="translated">'每个文件中只能出现一次“Option {0}”语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantInherit"> <source>'Inherits' not valid in Modules.</source> <target state="translated">'"Inherits" 在模块中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantImplement"> <source>'Implements' not valid in Modules.</source> <target state="translated">'"Implements" 在模块中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadImplementsType"> <source>Implemented type must be an interface.</source> <target state="translated">已实现的类型必须是接口。</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstFlags1"> <source>'{0}' is not valid on a constant declaration.</source> <target state="translated">“{0}”在常量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadWithEventsFlags1"> <source>'{0}' is not valid on a WithEvents declaration.</source> <target state="translated">“{0}”在 WithEvents 声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadDimFlags1"> <source>'{0}' is not valid on a member variable declaration.</source> <target state="translated">“{0}”在成员变量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateParamName1"> <source>Parameter already declared with name '{0}'.</source> <target state="translated">已用名称“{0}”声明了参数。</target> <note /> </trans-unit> <trans-unit id="ERR_LoopDoubleCondition"> <source>'Loop' cannot have a condition if matching 'Do' has one.</source> <target state="translated">'"Loop" 和匹配的 "Do" 不能同时具有条件。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedRelational"> <source>Relational operator expected.</source> <target state="translated">应为关系运算符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedExitKind"> <source>'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'.</source> <target state="translated">'“Exit”的后面必须跟有“Sub”、“Function”、“Property”、“Do”、“For”、“While”、“Select”或“Try”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedNamedArgumentInAttributeList"> <source>Named argument expected.</source> <target state="translated">应为命名参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation"> <source>Named argument specifications must appear after all fixed arguments have been specified in a late bound invocation.</source> <target state="translated">命名参数规范必须出现在已在后期绑定调用中指定的所有固定参数之后。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedNamedArgument"> <source>Named argument expected. Please use language version {0} or greater to use non-trailing named arguments.</source> <target state="translated">需要命名参数。请使用语言版本 {0} 或更高版本,以使用非尾随命名参数。</target> <note /> </trans-unit> <trans-unit id="ERR_BadMethodFlags1"> <source>'{0}' is not valid on a method declaration.</source> <target state="translated">“{0}”在方法声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadEventFlags1"> <source>'{0}' is not valid on an event declaration.</source> <target state="translated">“{0}”在事件声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadDeclareFlags1"> <source>'{0}' is not valid on a Declare.</source> <target state="translated">“{0}”在 Declare 中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadLocalConstFlags1"> <source>'{0}' is not valid on a local constant declaration.</source> <target state="translated">“{0}”在局部常量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadLocalDimFlags1"> <source>'{0}' is not valid on a local variable declaration.</source> <target state="translated">“{0}”在局部变量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedConditionalDirective"> <source>'If', 'ElseIf', 'Else', 'Const', 'Region', 'ExternalSource', 'ExternalChecksum', 'Enable', 'Disable', 'End' or 'R' expected.</source> <target state="translated">'应为“If”、“ElseIf”、“Else”、“Const”、“Region”、“ExternalSource”、“ExternalChecksum”、“Enable”、“Disable”、“End”或“R”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEQ"> <source>'=' expected.</source> <target state="translated">'应为 "="。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorNotFound1"> <source>Type '{0}' has no constructors.</source> <target state="translated">类型“{0}”没有构造函数。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndInterface"> <source>'End Interface' must be preceded by a matching 'Interface'.</source> <target state="translated">'“End Interface”前面必须是匹配的“Interface”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndInterface"> <source>'Interface' must end with a matching 'End Interface'.</source> <target state="translated">'"Interface" 必须以匹配的 "End Interface" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFrom2"> <source> '{0}' inherits from '{1}'.</source> <target state="translated"> “{0}”从“{1}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNestedIn2"> <source> '{0}' is nested in '{1}'.</source> <target state="translated"> “{0}”嵌套在“{1}”中。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceCycle1"> <source>Class '{0}' cannot inherit from itself: {1}</source> <target state="translated">类“{0}”不能从自身继承: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromNonClass"> <source>Classes can inherit only from other classes.</source> <target state="translated">类只能从其他类继承。</target> <note /> </trans-unit> <trans-unit id="ERR_MultiplyDefinedType3"> <source>'{0}' is already declared as '{1}' in this {2}.</source> <target state="translated">“{0}”已在此 {2} 中声明为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadOverrideAccess2"> <source>'{0}' cannot override '{1}' because they have different access levels.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们具有不同的访问级别。</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNotOverridable2"> <source>'{0}' cannot override '{1}' because it is declared 'NotOverridable'.</source> <target state="translated">“{0}”无法重写“{1}”,因为后者已声明为“NotOverridable”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateProcDef1"> <source>'{0}' has multiple definitions with identical signatures.</source> <target state="translated">“{0}”具有多个带相同签名的定义。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateProcDefWithDifferentTupleNames2"> <source>'{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'.</source> <target state="translated">“{0}”具有多个带不同元组元素名称却有相同签名的定义,包括“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceMethodFlags1"> <source>'{0}' is not valid on an interface method declaration.</source> <target state="translated">“{0}”在接口方法声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamNotFound2"> <source>'{0}' is not a parameter of '{1}'.</source> <target state="translated">“{0}”不是“{1}”的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfacePropertyFlags1"> <source>'{0}' is not valid on an interface property declaration.</source> <target state="translated">“{0}”在接口属性声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgUsedTwice2"> <source>Parameter '{0}' of '{1}' already has a matching argument.</source> <target state="translated">“{1}”的参数“{0}”已有匹配的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceCantUseEventSpecifier1"> <source>'{0}' is not valid on an interface event declaration.</source> <target state="translated">“{0}”在接口事件声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_TypecharNoMatch2"> <source>Type character '{0}' does not match declared data type '{1}'.</source> <target state="translated">类型字符“{0}”与声明的数据类型“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSubOrFunction"> <source>'Sub' or 'Function' expected after 'Delegate'.</source> <target state="translated">'“Delegate”后面应为“Sub”或“Function”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmptyEnum1"> <source>Enum '{0}' must contain at least one member.</source> <target state="translated">枚举“{0}”必须至少包含一个成员。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidConstructorCall"> <source>Constructor call is valid only as the first statement in an instance constructor.</source> <target state="translated">构造函数调用仅作为实例构造函数中的第一条语句有效。</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideConstructor"> <source>'Sub New' cannot be declared 'Overrides'.</source> <target state="translated">'“Sub New”不能声明为“Overrides”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorCannotBeDeclaredPartial"> <source>'Sub New' cannot be declared 'Partial'.</source> <target state="translated">'“Sub New”不能声明为“Partial”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleEmitFailure"> <source>Failed to emit module '{0}': {1}</source> <target state="translated">未能发出模块“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_EncUpdateFailedMissingAttribute"> <source>Cannot update '{0}'; attribute '{1}' is missing.</source> <target state="translated">无法更新“{0}”;特性“{1}”缺失。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideNotNeeded3"> <source>{0} '{1}' cannot be declared 'Overrides' because it does not override a {0} in a base class.</source> <target state="translated">{0}“{1}”不能声明为“Overrides”,因为它不重写基类中的 {0}。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDot"> <source>'.' expected.</source> <target state="translated">'应为“.”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLocals1"> <source>Local variable '{0}' is already declared in the current block.</source> <target state="translated">当前块中已声明了局部变量“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsProc"> <source>Statement cannot appear within a method body. End of method assumed.</source> <target state="translated">语句不能出现在方法主体内。假定为方法末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalSameAsFunc"> <source>Local variable cannot have the same name as the function containing it.</source> <target state="translated">局部变量不能与包含它的函数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_RecordEmbeds2"> <source> '{0}' contains '{1}' (variable '{2}').</source> <target state="translated"> “{0}”包含“{1}”(变量“{2}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_RecordCycle2"> <source>Structure '{0}' cannot contain an instance of itself: {1}</source> <target state="translated">结构“{0}”不能包含自身的实例: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceCycle1"> <source>Interface '{0}' cannot inherit from itself: {1}</source> <target state="translated">接口“{0}”不能从自身继承: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_SubNewCycle2"> <source> '{0}' calls '{1}'.</source> <target state="translated"> “{0}”调用“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SubNewCycle1"> <source>Constructor '{0}' cannot call itself: {1}</source> <target state="translated">构造函数“{0}”不能调用自身: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromCantInherit3"> <source>'{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'.</source> <target state="translated">“{1}”已声明为“NotInheritable”,因此“{0}”无法从 {2}“{1}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithOptional2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by optional parameters.</source> <target state="translated">“{0}” 和“{1}”的差异仅在于可选参数,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithReturnType2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by return types.</source> <target state="translated">“{0}”和“{1}”的差异仅在于返回类型,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharWithType1"> <source>Type character '{0}' cannot be used in a declaration with an explicit type.</source> <target state="translated">在具有显式类型的声明中不能使用类型字符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharOnSub"> <source>Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.</source> <target state="translated">"Sub" 不返回值,因此在 "Sub" 声明中不能使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithDefault2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters.</source> <target state="translated">“{0}”和“{1}”的差异仅在于可选参数的默认值,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingSubscript"> <source>Array subscript expression missing.</source> <target state="translated">缺少数组下标表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithDefault2"> <source>'{0}' cannot override '{1}' because they differ by the default values of optional parameters.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在可选参数的默认值上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithOptional2"> <source>'{0}' cannot override '{1}' because they differ by optional parameters.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在可选参数上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_FieldOfValueFieldOfMarshalByRef3"> <source>Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class.</source> <target state="translated">“{0}”,是使用“System.MarshalByRefObject”作为基类的类“{2}”的值类型字段“{1}”的成员,无法引用。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeMismatch2"> <source>Value of type '{0}' cannot be converted to '{1}'.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_CaseAfterCaseElse"> <source>'Case' cannot follow a 'Case Else' in the same 'Select' statement.</source> <target state="translated">'在同一“Select”语句中,“Case”不能位于“Case Else”之后。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertArrayMismatch4"> <source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”,因为“{2}”不是从“{3}”派生的。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertObjectArrayMismatch3"> <source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”,因为“{2}”不是引用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ForLoopType1"> <source>'For' loop control variable cannot be of type '{0}' because the type does not support the required operators.</source> <target state="translated">'“For”循环控制变量的类型不能是“{0}”,因为该类型不支持所需的运算符。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithByref2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.</source> <target state="translated">“{0}”和“{1}”的差异仅在于声明为“ByRef”或“ByVal”的参数,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromNonInterface"> <source>Interface can inherit only from another interface.</source> <target state="translated">接口只能从其他接口继承。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceOrderOnInherits"> <source>'Inherits' statements must precede all declarations in an interface.</source> <target state="translated">'“Inherits”语句必须位于接口中的所有声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateDefaultProps1"> <source>'Default' can be applied to only one property name in a {0}.</source> <target state="translated">'“Default”只可应用于“{0}”中的一个属性名称。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultMissingFromProperty2"> <source>'{0}' and '{1}' cannot overload each other because only one is declared 'Default'.</source> <target state="translated">“{0}”和“{1}”中只有一个声明为“Default”,因此它们无法相互重载。</target> <note /> </trans-unit> <trans-unit id="ERR_OverridingPropertyKind2"> <source>'{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在是“ReadOnly”还是“WriteOnly”上不同。</target> <note /> </trans-unit> <trans-unit id="ERR_NewInInterface"> <source>'Sub New' cannot be declared in an interface.</source> <target state="translated">'"Sub New" 不能在接口中声明。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnNew1"> <source>'Sub New' cannot be declared '{0}'.</source> <target state="translated">'“Sub New”不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadingPropertyKind2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.</source> <target state="translated">“{0}” 和“{1}”的差异仅在于“ReadOnly”和“WriteOnly”,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_NoDefaultNotExtend1"> <source>Class '{0}' cannot be indexed because it has no default property.</source> <target state="translated">无法为类“{0}”编制索引,因为它没有默认属性。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithArrayVsParamArray2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'.</source> <target state="translated">“{0}”和“{1}”的差异仅在于声明为 "ParamArray" 的参数,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInstanceMemberAccess"> <source>Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.</source> <target state="translated">没有类的显式实例,就无法从共享方法或共享成员初始值设定项中引用该类的实例成员。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedRbrace"> <source>'}' expected.</source> <target state="translated">'应为 "}"。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleAsType1"> <source>Module '{0}' cannot be used as a type.</source> <target state="translated">模块“{0}”不能用作类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NewIfNullOnNonClass"> <source>'New' cannot be used on an interface.</source> <target state="translated">'"New"不能在接口上使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchAfterFinally"> <source>'Catch' cannot appear after 'Finally' within a 'Try' statement.</source> <target state="translated">'在“Try”语句中,“Catch”不能出现在“Finally”之后。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchNoMatchingTry"> <source>'Catch' cannot appear outside a 'Try' statement.</source> <target state="translated">'“Catch”不能出现在“Try”语句之外。</target> <note /> </trans-unit> <trans-unit id="ERR_FinallyAfterFinally"> <source>'Finally' can only appear once in a 'Try' statement.</source> <target state="translated">'“Finally”只能在“Try”语句中出现一次。</target> <note /> </trans-unit> <trans-unit id="ERR_FinallyNoMatchingTry"> <source>'Finally' cannot appear outside a 'Try' statement.</source> <target state="translated">'“Finally”不能出现在“Try”语句之外。</target> <note /> </trans-unit> <trans-unit id="ERR_EndTryNoTry"> <source>'End Try' must be preceded by a matching 'Try'.</source> <target state="translated">'“End Try”前面必须是匹配的“Try”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndTry"> <source>'Try' must end with a matching 'End Try'.</source> <target state="translated">'“Try”必须以匹配的“End Try”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelegateFlags1"> <source>'{0}' is not valid on a Delegate declaration.</source> <target state="translated">“{0}”在委托声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NoConstructorOnBase2"> <source>Class '{0}' must declare a 'Sub New' because its base class '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,原因是它的基类“{1}”没有不使用参数就可以调用的可访问“Sub New”。</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleSymbol2"> <source>'{0}' is not accessible in this context because it is '{1}'.</source> <target state="translated">“{0}”是“{1}”,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleMember3"> <source>'{0}.{1}' is not accessible in this context because it is '{2}'.</source> <target state="translated">“{0}.{1}”是“{2}” ,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchNotException1"> <source>'Catch' cannot catch type '{0}' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.</source> <target state="translated">'“Catch”无法捕捉类型“{0}”,因为该类型既不是“System.Exception”也不是从“System.Exception”继承的类。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitTryNotWithinTry"> <source>'Exit Try' can only appear inside a 'Try' statement.</source> <target state="translated">'"Exit Try" 只能出现在 "Try" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_BadRecordFlags1"> <source>'{0}' is not valid on a Structure declaration.</source> <target state="translated">“{0}”在结构声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadEnumFlags1"> <source>'{0}' is not valid on an Enum declaration.</source> <target state="translated">“{0}”在枚举声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceFlags1"> <source>'{0}' is not valid on an Interface declaration.</source> <target state="translated">“{0}”在接口声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithByref2"> <source>'{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在某个参数上存在差异,一个被标记为“ByRef”,而另一个被标记为“ByVal”。</target> <note /> </trans-unit> <trans-unit id="ERR_MyBaseAbstractCall1"> <source>'MyBase' cannot be used with method '{0}' because it is declared 'MustOverride'.</source> <target state="translated">'“MyBase”不能用和方法“{0}”一起使用,因为它被声明为“MustOverride”。</target> <note /> </trans-unit> <trans-unit id="ERR_IdentNotMemberOfInterface4"> <source>'{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'.</source> <target state="translated">“{0}”无法实现“{1}”,因为接口“{3}”上不存在匹配的 {2}。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementingInterfaceWithDifferentTupleNames5"> <source>'{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'.</source> <target state="translated">“{0}”不能在接口“{3}”上实现{1}“{2}”,因为“{4}”中的元组元素名称与“{5}”中的名称不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_WithEventsRequiresClass"> <source>'WithEvents' variables must have an 'As' clause.</source> <target state="translated">'"WithEvents" 变量必须有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_WithEventsAsStruct"> <source>'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.</source> <target state="translated">'"WithEvents" 变量只能类型化为具有类约束的类、接口或类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertArrayRankMismatch2"> <source>Value of type '{0}' cannot be converted to '{1}' because the array types have different numbers of dimensions.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”,原因是数组类型的维数不同。</target> <note /> </trans-unit> <trans-unit id="ERR_RedimRankMismatch"> <source>'ReDim' cannot change the number of dimensions of an array.</source> <target state="translated">'"ReDim" 无法更改数组的维数。</target> <note /> </trans-unit> <trans-unit id="ERR_StartupCodeNotFound1"> <source>'Sub Main' was not found in '{0}'.</source> <target state="translated">“{0}”中找不到“Sub Main”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstAsNonConstant"> <source>Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.</source> <target state="translated">常量必须是内部类型或者枚举类型,不能是类、结构、类型参数或数组类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndSub"> <source>'End Sub' must be preceded by a matching 'Sub'.</source> <target state="translated">'“End Sub”前面必须是匹配的“Sub”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndFunction"> <source>'End Function' must be preceded by a matching 'Function'.</source> <target state="translated">'“End Function”前面必须是匹配的“Function”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndProperty"> <source>'End Property' must be preceded by a matching 'Property'.</source> <target state="translated">'“End Property”前面必须是匹配的“Property”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseMethodSpecifier1"> <source>Methods in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的方法不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseEventSpecifier1"> <source>Events in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的事件不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StructCantUseVarSpecifier1"> <source>Members in a Structure cannot be declared '{0}'.</source> <target state="translated">结构中的成员不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOverrideDueToReturn2"> <source>'{0}' cannot override '{1}' because they differ by their return types.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们的返回类型不同。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidOverrideDueToTupleNames2"> <source>'{0}' cannot override '{1}' because they differ by their tuple element names.</source> <target state="translated">“{0}”不能替代“{1}”,因为它们的元组元素名称不同。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidOverrideDueToTupleNames2_Title"> <source>Member cannot override because it differs by its tuple element names.</source> <target state="translated">成员不能替代,因为它的元组元素名称不同。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantWithNoValue"> <source>Constants must have a value.</source> <target state="translated">常量必须具有值。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionOverflow1"> <source>Constant expression not representable in type '{0}'.</source> <target state="translated">常量表达式无法在类型“{0}”中表示。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertyGet"> <source>'Get' is already declared.</source> <target state="translated">'已声明 "Get"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertySet"> <source>'Set' is already declared.</source> <target state="translated">'已声明 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotDeclared1"> <source>'{0}' is not declared. It may be inaccessible due to its protection level.</source> <target state="translated">'未声明“{0}”。由于其保护级别,它可能无法访问。</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryOperands3"> <source>Operator '{0}' is not defined for types '{1}' and '{2}'.</source> <target state="translated">没有为类型“{1}”和“{2}”定义运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedProcedure"> <source>Expression is not a method.</source> <target state="translated">表达式不是方法。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedArgument2"> <source>Argument not specified for parameter '{0}' of '{1}'.</source> <target state="translated">没有为“{1}”的形参“{0}”指定实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotMember2"> <source>'{0}' is not a member of '{1}'.</source> <target state="translated">“{0}”不是“{1}”的成员。</target> <note /> </trans-unit> <trans-unit id="ERR_EndClassNoClass"> <source>'End Class' must be preceded by a matching 'Class'.</source> <target state="translated">'"End Class" 前面必须是匹配的 "Class"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadClassFlags1"> <source>Classes cannot be declared '{0}'.</source> <target state="translated">类不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ImportsMustBeFirst"> <source>'Imports' statements must precede any declarations.</source> <target state="translated">'“Imports”语句前面必须是声明。</target> <note /> </trans-unit> <trans-unit id="ERR_NonNamespaceOrClassOnImport2"> <source>'{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module.</source> <target state="translated">'Imports “{0}”的“{1}”不引用命名空间、类、结构、枚举或模块。</target> <note /> </trans-unit> <trans-unit id="ERR_TypecharNotallowed"> <source>Type declaration characters are not valid in this context.</source> <target state="translated">类型声明字符在此上下文中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectReferenceNotSupplied"> <source>Reference to a non-shared member requires an object reference.</source> <target state="translated">对非共享成员的引用要求对象引用。</target> <note /> </trans-unit> <trans-unit id="ERR_MyClassNotInClass"> <source>'MyClass' cannot be used outside of a class.</source> <target state="translated">'"MyClass" 不能在类的外部使用。</target> <note /> </trans-unit> <trans-unit id="ERR_IndexedNotArrayOrProc"> <source>Expression is not an array or a method, and cannot have an argument list.</source> <target state="translated">表达式不是数组或方法,不能具有参数列表。</target> <note /> </trans-unit> <trans-unit id="ERR_EventSourceIsArray"> <source>'WithEvents' variables cannot be typed as arrays.</source> <target state="translated">'“WithEvents”变量不能类型化为数组。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedConstructorWithParams"> <source>Shared 'Sub New' cannot have any parameters.</source> <target state="translated">共享的 "Sub New" 不能具有任何参数。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedConstructorIllegalSpec1"> <source>Shared 'Sub New' cannot be declared '{0}'.</source> <target state="translated">共享的“Sub New”不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndClass"> <source>'Class' statement must end with a matching 'End Class'.</source> <target state="translated">'“Class”语句必须以匹配的“End Class”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_UnaryOperand2"> <source>Operator '{0}' is not defined for type '{1}'.</source> <target state="translated">没有为类型“{1}”定义运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsWithDefault1"> <source>'Default' cannot be combined with '{0}'.</source> <target state="translated">'“Default”不能与“{0}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_VoidValue"> <source>Expression does not produce a value.</source> <target state="translated">表达式不产生值。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorFunction"> <source>Constructor must be declared as a Sub, not as a Function.</source> <target state="translated">构造函数必须声明为 Sub,而不是 Function。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidLiteralExponent"> <source>Exponent is not valid.</source> <target state="translated">指数无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NewCannotHandleEvents"> <source>'Sub New' cannot handle events.</source> <target state="translated">'"Sub New" 无法处理事件。</target> <note /> </trans-unit> <trans-unit id="ERR_CircularEvaluation1"> <source>Constant '{0}' cannot depend on its own value.</source> <target state="translated">常量“{0}”不能依赖自身的值。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnSharedMeth1"> <source>'Shared' cannot be combined with '{0}' on a method declaration.</source> <target state="translated">'“Shared”不能与方法声明上的“{0}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnSharedProperty1"> <source>'Shared' cannot be combined with '{0}' on a property declaration.</source> <target state="translated">'“Shared”不能与属性声明上的“{0}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnStdModuleProperty1"> <source>Properties in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的属性不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedOnProcThatImpl"> <source>Methods or events that implement interface members cannot be declared 'Shared'.</source> <target state="translated">实现接口成员的方法或事件不能声明为 "Shared"。</target> <note /> </trans-unit> <trans-unit id="ERR_NoWithEventsVarOnHandlesList"> <source>Handles clause requires a WithEvents variable defined in the containing type or one of its base types.</source> <target state="translated">Handles 子句要求一个在包含类型或它的某个基类型中定义的 WithEvents 变量。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceAccessMismatch5"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'.</source> <target state="translated">“{0}”将对基 {1} 的访问扩展到 {3}“{4}”,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_NarrowingConversionDisallowed2"> <source>Option Strict On disallows implicit conversions from '{0}' to '{1}'.</source> <target state="translated">Option Strict On 不允许从“{0}”到“{1}”的隐式转换。</target> <note /> </trans-unit> <trans-unit id="ERR_NoArgumentCountOverloadCandidates1"> <source>Overload resolution failed because no accessible '{0}' accepts this number of arguments.</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”接受此数目的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NoViableOverloadCandidates1"> <source>Overload resolution failed because no '{0}' is accessible.</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoCallableOverloadCandidates2"> <source>Overload resolution failed because no accessible '{0}' can be called with these arguments:{1}</source> <target state="translated">重载决策失败,因为没有可使用这些参数调用的可访问“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadOverloadCandidates2"> <source>Overload resolution failed because no accessible '{0}' can be called:{1}</source> <target state="translated">重载决策失败,原因是没有可访问的“{0}”可以进行调用:{1}</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonNarrowingOverloadCandidates2"> <source>Overload resolution failed because no accessible '{0}' can be called without a narrowing conversion:{1}</source> <target state="translated">重载决策失败,因为没有不使用收缩转换即可调用的可访问重载“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentNarrowing3"> <source>Argument matching parameter '{0}' narrows from '{1}' to '{2}'.</source> <target state="translated">与形参“{0}”匹配的实参从“{1}”收缩到“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoMostSpecificOverload2"> <source>Overload resolution failed because no accessible '{0}' is most specific for these arguments:{1}</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”最适合这些参数: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_NotMostSpecificOverload"> <source>Not most specific.</source> <target state="translated">不是最适合。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadCandidate2"> <source> '{0}': {1}</source> <target state="translated"> “{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_NoGetProperty1"> <source>Property '{0}' is 'WriteOnly'.</source> <target state="translated">属性“{0}”为“WriteOnly”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoSetProperty1"> <source>Property '{0}' is 'ReadOnly'.</source> <target state="translated">属性“{0}”为“ReadOnly”。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamTypingInconsistency"> <source>All parameters must be explicitly typed if any of them are explicitly typed.</source> <target state="translated">如果任何一个参数已显式类型化,则所有参数都必须显式类型化。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamNameFunctionNameCollision"> <source>Parameter cannot have the same name as its defining function.</source> <target state="translated">参数不能与它的定义函数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_DateToDoubleConversion"> <source>Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method.</source> <target state="translated">从“Date”到“Double”的转换需要调用“Date.ToOADate”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DoubleToDateConversion"> <source>Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method.</source> <target state="translated">从 "Double" 到 "Date" 的转换需要调用 "Date.FromOADate" 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ZeroDivide"> <source>Division by zero occurred while evaluating this expression.</source> <target state="translated">计算此表达式时出现被零除的情况。</target> <note /> </trans-unit> <trans-unit id="ERR_TryAndOnErrorDoNotMix"> <source>Method cannot contain both a 'Try' statement and an 'On Error' or 'Resume' statement.</source> <target state="translated">方法不能既包含 "Try" 语句,又包含 "On Error" 或 "Resume" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyAccessIgnored"> <source>Property access must assign to the property or use its value.</source> <target state="translated">属性访问必须分配给属性或使用属性值。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceNoDefault1"> <source>'{0}' cannot be indexed because it has no default property.</source> <target state="translated">'无法为“{0}”编制索引,因为它没有默认属性。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyAttribute1"> <source>Attribute '{0}' cannot be applied to an assembly.</source> <target state="translated">属性“{0}”不能应用于程序集。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidModuleAttribute1"> <source>Attribute '{0}' cannot be applied to a module.</source> <target state="translated">属性“{0}”不能应用于模块。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInUnnamedNamespace1"> <source>'{0}' is ambiguous.</source> <target state="translated">“{0}”不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultMemberNotProperty1"> <source>Default member of '{0}' is not a property.</source> <target state="translated">“{0}”的默认成员不是属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInNamespace2"> <source>'{0}' is ambiguous in the namespace '{1}'.</source> <target state="translated">“{1}”在命名空间中“{0}”不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInImports2"> <source>'{0}' is ambiguous, imported from the namespaces or types '{1}'.</source> <target state="translated">“{0}”不明确,从命名空间或类型“{1}”导入。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInModules2"> <source>'{0}' is ambiguous between declarations in Modules '{1}'.</source> <target state="translated">“{0}”在模块“{1}”中的声明之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInNamespaces2"> <source>'{0}' is ambiguous between declarations in namespaces '{1}'.</source> <target state="translated">“{0}”在命名空间“{1}”中的声明之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerTooFewDimensions"> <source>Array initializer has too few dimensions.</source> <target state="translated">数组初始值设定项的维数太少。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerTooManyDimensions"> <source>Array initializer has too many dimensions.</source> <target state="translated">数组初始值设定项的维数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerTooFewElements1"> <source>Array initializer is missing {0} elements.</source> <target state="translated">数组初始值设定项缺少 {0} 个元素。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerTooManyElements1"> <source>Array initializer has {0} too many elements.</source> <target state="translated">数组初始值设定项拥有的元素太多({0}个)。</target> <note /> </trans-unit> <trans-unit id="ERR_NewOnAbstractClass"> <source>'New' cannot be used on a class that is declared 'MustInherit'.</source> <target state="translated">'"New" 不能在声明为 "MustInherit" 的类上使用。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNamedImportAlias1"> <source>Alias '{0}' is already declared.</source> <target state="translated">已声明别名“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePrefix"> <source>XML namespace prefix '{0}' is already declared.</source> <target state="translated">已声明 XML 命名空间前缀“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsLateBinding"> <source>Option Strict On disallows late binding.</source> <target state="translated">Option Strict On 不允许后期绑定。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfOperandNotMethod"> <source>'AddressOf' operand must be the name of a method (without parentheses).</source> <target state="translated">'“AddressOf”操作数必须是某个方法的名称(不带圆括号)。</target> <note /> </trans-unit> <trans-unit id="ERR_EndExternalSource"> <source>'#End ExternalSource' must be preceded by a matching '#ExternalSource'.</source> <target state="translated">'"#End ExternalSource" 前面必须是匹配的 "#ExternalSource"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndExternalSource"> <source>'#ExternalSource' statement must end with a matching '#End ExternalSource'.</source> <target state="translated">'“#ExternalSource”语句必须以匹配的“#End ExternalSource”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedExternalSource"> <source>'#ExternalSource' directives cannot be nested.</source> <target state="translated">'"#ExternalSource" 指令不能嵌套。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfNotDelegate1"> <source>'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source> <target state="translated">'“AddressOf”表达式无法转换为“{0} ”,因为“{0}”不是委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_SyncLockRequiresReferenceType1"> <source>'SyncLock' operand cannot be of type '{0}' because '{0}' is not a reference type.</source> <target state="translated">'"SyncLock" 操作数不能是“{0}”类型,因为“{0}”不是引用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodAlreadyImplemented2"> <source>'{0}.{1}' cannot be implemented more than once.</source> <target state="translated">“{0}.{1}”不能多次实现。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInInherits1"> <source>'{0}' cannot be inherited more than once.</source> <target state="translated">“{0}”不能被继承多次。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamArrayArgument"> <source>Named argument cannot match a ParamArray parameter.</source> <target state="translated">命名实参不能匹配 ParamArray 形参。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedParamArrayArgument"> <source>Omitted argument cannot match a ParamArray parameter.</source> <target state="translated">省略的实参不能匹配 ParamArray 形参。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayArgumentMismatch"> <source>Argument cannot match a ParamArray parameter.</source> <target state="translated">参数不能匹配 ParamArray 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_EventNotFound1"> <source>Event '{0}' cannot be found.</source> <target state="translated">找不到事件“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseVariableSpecifier1"> <source>Variables in Modules cannot be declared '{0}'.</source> <target state="translated">模块中的变量不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedEventNeedsSharedHandler"> <source>Events of shared WithEvents variables cannot be handled by non-shared methods.</source> <target state="translated">共享 WithEvents 变量的事件不能由非共享方法处理。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedMinus"> <source>'-' expected.</source> <target state="translated">'应为“-”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceMemberSyntax"> <source>Interface members must be methods, properties, events, or type definitions.</source> <target state="translated">接口成员必须是方法、属性、事件或类型定义。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideInterface"> <source>Statement cannot appear within an interface body.</source> <target state="translated">语句不能出现在接口体内。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsInterface"> <source>Statement cannot appear within an interface body. End of interface assumed.</source> <target state="translated">语句不能出现在接口体内。假定为接口末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsInNotInheritableClass1"> <source>'NotInheritable' classes cannot have members declared '{0}'.</source> <target state="translated">'“NotInheritable”类不能有声明为“{0}”的成员。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseOnlyClassesMustBeExplicit2"> <source>Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}.</source> <target state="translated">类“{0}”必须声明为“MustInherit”或重写以下继承的“MustOverride”成员: {1}。</target> <note /> </trans-unit> <trans-unit id="ERR_MustInheritEventNotOverridden"> <source>'{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit.</source> <target state="translated">“{0}”是基类“{1}” 中的 MustOverride 事件。Visual Basic 不支持事件替代。必须提供基类中事件的实现或让类“{2}“成为 MustInherit。</target> <note /> </trans-unit> <trans-unit id="ERR_NegativeArraySize"> <source>Array dimensions cannot have a negative size.</source> <target state="translated">数组维数的大小不能为负。</target> <note /> </trans-unit> <trans-unit id="ERR_MyClassAbstractCall1"> <source>'MustOverride' method '{0}' cannot be called with 'MyClass'.</source> <target state="translated">'无法用“MyClass”调用“MustOverride”方法“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_EndDisallowedInDllProjects"> <source>'End' statement cannot be used in class library projects.</source> <target state="translated">'在类库项目中不能使用 "End" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_BlockLocalShadowing1"> <source>Variable '{0}' hides a variable in an enclosing block.</source> <target state="translated">变量“{0}”在封闭块中隐藏变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleNotAtNamespace"> <source>'Module' statements can occur only at file or namespace level.</source> <target state="translated">'"Module" 语句只能出现在文件级或命名空间级。</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotAtNamespace"> <source>'Namespace' statements can occur only at file or namespace level.</source> <target state="translated">'"Namespace" 语句只能出现在文件级或命名空间级。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEnum"> <source>Statement cannot appear within an Enum body.</source> <target state="translated">语句不能出现在枚举体内。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsEnum"> <source>Statement cannot appear within an Enum body. End of Enum assumed.</source> <target state="translated">语句不能出现在枚举体内。假定已到达枚举末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionStrict"> <source>'Option Strict' can be followed only by 'On' or 'Off'.</source> <target state="translated">'"Option Strict" 的后面只能跟 "On" 或 "Off"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndStructureNoStructure"> <source>'End Structure' must be preceded by a matching 'Structure'.</source> <target state="translated">'"End Structure" 前面必须是匹配的 "Structure"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndModuleNoModule"> <source>'End Module' must be preceded by a matching 'Module'.</source> <target state="translated">'"End Module" 前面必须是匹配的 "Module"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndNamespaceNoNamespace"> <source>'End Namespace' must be preceded by a matching 'Namespace'.</source> <target state="translated">'"End Namespace" 前面必须是匹配的 "Namespace"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndStructure"> <source>'Structure' statement must end with a matching 'End Structure'.</source> <target state="translated">'“Structure”语句必须以匹配的“End Structure”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndModule"> <source>'Module' statement must end with a matching 'End Module'.</source> <target state="translated">'“Module”语句必须以匹配的“End Module”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndNamespace"> <source>'Namespace' statement must end with a matching 'End Namespace'.</source> <target state="translated">'“Namespace”语句必须以匹配的“End Namespace”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_OptionStmtWrongOrder"> <source>'Option' statements must precede any declarations or 'Imports' statements.</source> <target state="translated">'"Option" 语句必须位于任何声明或 "Imports" 语句之前。</target> <note /> </trans-unit> <trans-unit id="ERR_StructCantInherit"> <source>Structures cannot have 'Inherits' statements.</source> <target state="translated">结构不能有 "Inherits" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_NewInStruct"> <source>Structures cannot declare a non-shared 'Sub New' with no parameters.</source> <target state="translated">结构不能声明没有参数的非共享 "Sub New"。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndGet"> <source>'End Get' must be preceded by a matching 'Get'.</source> <target state="translated">'“End Get”前面必须是匹配的“Get”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndGet"> <source>'Get' statement must end with a matching 'End Get'.</source> <target state="translated">'"Get" 语句必须以匹配的 "End Get" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndSet"> <source>'End Set' must be preceded by a matching 'Set'.</source> <target state="translated">'“End Set”前面必须是匹配的“Set”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndSet"> <source>'Set' statement must end with a matching 'End Set'.</source> <target state="translated">'"Set" 语句必须以匹配的 "End Set" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsProperty"> <source>Statement cannot appear within a property body. End of property assumed.</source> <target state="translated">语句不能出现在属性体内。假定为属性末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateWriteabilityCategoryUsed"> <source>'ReadOnly' and 'WriteOnly' cannot be combined.</source> <target state="translated">'"ReadOnly" 不能与 "WriteOnly" 组合。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedGreater"> <source>'&gt;' expected.</source> <target state="translated">'应为“&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeStmtWrongOrder"> <source>Assembly or Module attribute statements must precede any declarations in a file.</source> <target state="translated">Assembly 或 Module 特性语句必须位于文件中的任何声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_NoExplicitArraySizes"> <source>Array bounds cannot appear in type specifiers.</source> <target state="translated">数组界限不能出现在类型说明符中。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyFlags1"> <source>Properties cannot be declared '{0}'.</source> <target state="translated">属性不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionExplicit"> <source>'Option Explicit' can be followed only by 'On' or 'Off'.</source> <target state="translated">'"Option Explicit" 的后面只能跟 "On" 或 "Off"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleParameterSpecifiers"> <source>'ByVal' and 'ByRef' cannot be combined.</source> <target state="translated">'“ByVal”不能与“ByRef”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleOptionalParameterSpecifiers"> <source>'Optional' and 'ParamArray' cannot be combined.</source> <target state="translated">"Optional" 不能与 "ParamArray" 组合。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedProperty1"> <source>Property '{0}' is of an unsupported type.</source> <target state="translated">属性“{0}”的类型不受支持。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionalParameterUsage1"> <source>Attribute '{0}' cannot be applied to a method with optional parameters.</source> <target state="translated">属性“{0}”不能应用于具有可选参数的方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnFromNonFunction"> <source>'Return' statement in a Sub or a Set cannot return a value.</source> <target state="translated">'Sub 或 Set 中的 "Return" 语句不能返回值。</target> <note /> </trans-unit> <trans-unit id="ERR_UnterminatedStringLiteral"> <source>String constants must end with a double quote.</source> <target state="translated">字符串常量必须以双引号结束。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedType1"> <source>'{0}' is an unsupported type.</source> <target state="translated">“{0}”是不受支持的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEnumBase"> <source>Enums must be declared as an integral type.</source> <target state="translated">枚举必须声明为整型。</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefIllegal1"> <source>{0} parameters cannot be declared 'ByRef'.</source> <target state="translated">{0} 参数不能声明为“ByRef”。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedAssembly3"> <source>Reference required to assembly '{0}' containing the type '{1}'. Add one to your project.</source> <target state="translated">需要对程序集“{0}”(包含类型“{1}”)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedModule3"> <source>Reference required to module '{0}' containing the type '{1}'. Add one to your project.</source> <target state="translated">需要对模块“{0}”(包含类型“{1}”)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnWithoutValue"> <source>'Return' statement in a Function, Get, or Operator must return a value.</source> <target state="translated">'Function、Get 或 Operator 中的 "Return" 语句必须返回值。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedField1"> <source>Field '{0}' is of an unsupported type.</source> <target state="translated">字段“{0}”的类型不受支持。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedMethod1"> <source>'{0}' has a return type that is not supported or parameter types that are not supported.</source> <target state="translated">“{0}”有不受支持的返回类型或不受支持的参数类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonIndexProperty1"> <source>Property '{0}' with no parameters cannot be found.</source> <target state="translated">无法找到不带参数的属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributePropertyType1"> <source>Property or field '{0}' does not have a valid attribute type.</source> <target state="translated">属性或字段“{0}”没有有效的特性类型。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalsCannotHaveAttributes"> <source>Attributes cannot be applied to local variables.</source> <target state="translated">特性不能应用于局部变量。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyOrFieldNotDefined1"> <source>Field or property '{0}' is not found.</source> <target state="translated">找不到字段或属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeUsage2"> <source>Attribute '{0}' cannot be applied to '{1}' because the attribute is not valid on this declaration type.</source> <target state="translated">属性“{0}”不能应用于“{1}”,因为该属性在此声明类型中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeUsageOnAccessor"> <source>Attribute '{0}' cannot be applied to '{1}' of '{2}' because the attribute is not valid on this declaration type.</source> <target state="translated">属性“{0}”不能应用于“{2}”的“{1}”,因为该属性在此声明类型中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedTypeInInheritsClause2"> <source>Class '{0}' cannot reference its nested type '{1}' in Inherits clause.</source> <target state="translated">类“{0}”无法在 Inherits 子句中引用其嵌套类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInItsInheritsClause1"> <source>Class '{0}' cannot reference itself in Inherits clause.</source> <target state="translated">类“{0}”不能在 Inherits 子句中引用自己。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseTypeReferences2"> <source> Base type of '{0}' needs '{1}' to be resolved.</source> <target state="translated"> “{0}”基类型需要解析“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalBaseTypeReferences3"> <source>Inherits clause of {0} '{1}' causes cyclic dependency: {2}</source> <target state="translated">{0}“{1}”的继承子句会导致循环依赖: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMultipleAttributeUsage1"> <source>Attribute '{0}' cannot be applied multiple times.</source> <target state="translated">属性“{0}”不能应用多次。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMultipleAttributeUsageInNetModule2"> <source>Attribute '{0}' in '{1}' cannot be applied multiple times.</source> <target state="translated">“{1}”中的属性“{0}”不能应用多次。</target> <note /> </trans-unit> <trans-unit id="ERR_CantThrowNonException"> <source>'Throw' operand must derive from 'System.Exception'.</source> <target state="translated">'“Throw”操作数必须从“System.Exception”派生。</target> <note /> </trans-unit> <trans-unit id="ERR_MustBeInCatchToRethrow"> <source>'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.</source> <target state="translated">'"Throw" 语句在 "Catch" 语句外或 "Finally" 语句内不能省略操作数。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayMustBeByVal"> <source>ParamArray parameters must be declared 'ByVal'.</source> <target state="translated">ParamArray 参数必须声明为 "ByVal"。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoleteSymbol2"> <source>'{0}' is obsolete: '{1}'.</source> <target state="translated">“{0}”已过时:“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_RedimNoSizes"> <source>'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.</source> <target state="translated">"ReDim" 语句需要一个带圆括号的列表,该列表列出数组每个维度的新界限。</target> <note /> </trans-unit> <trans-unit id="ERR_InitWithMultipleDeclarators"> <source>Explicit initialization is not permitted with multiple variables declared with a single type specifier.</source> <target state="translated">不允许通过用单个类型说明符声明多个变量来进行显式初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_InitWithExplicitArraySizes"> <source>Explicit initialization is not permitted for arrays declared with explicit bounds.</source> <target state="translated">对于用显式界限声明的数组不允许进行显式初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_EndSyncLockNoSyncLock"> <source>'End SyncLock' must be preceded by a matching 'SyncLock'.</source> <target state="translated">'“End SyncLock”前面必须是匹配的“SyncLock”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndSyncLock"> <source>'SyncLock' statement must end with a matching 'End SyncLock'.</source> <target state="translated">'“SyncLock”语句必须以匹配的“End SyncLock”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotEvent2"> <source>'{0}' is not an event of '{1}'.</source> <target state="translated">“{0}”不是“{1}”的事件。</target> <note /> </trans-unit> <trans-unit id="ERR_AddOrRemoveHandlerEvent"> <source>'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.</source> <target state="translated">'“AddHandler”或“RemoveHandler”语句事件操作数必须是以点限定的表达式或者是简单的名称。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedEnd"> <source>'End' statement not valid.</source> <target state="translated">'"End" 语句无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitForNonArray2"> <source>Array initializers are valid only for arrays, but the type of '{0}' is '{1}'.</source> <target state="translated">数组初始值设定项仅对数组有效,但“{0}”的类型是“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_EndRegionNoRegion"> <source>'#End Region' must be preceded by a matching '#Region'.</source> <target state="translated">'"#End Region" 前面必须是匹配的 "#Region"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndRegion"> <source>'#Region' statement must end with a matching '#End Region'.</source> <target state="translated">'"#Region" 语句必须以匹配的 "#End Region" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsStmtWrongOrder"> <source>'Inherits' statement must precede all declarations in a class.</source> <target state="translated">'“Inherits”语句必须位于类中的所有声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousAcrossInterfaces3"> <source>'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'.</source> <target state="translated">“{0}”在继承接口“{1}”和“{2}”之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultPropertyAmbiguousAcrossInterfaces4"> <source>Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'.</source> <target state="translated">默认属性访问在接口“{1}”的继承接口成员“{0}”和接口“{3}”的继承接口成员“{2}”之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceEventCantUse1"> <source>Events in interfaces cannot be declared '{0}'.</source> <target state="translated">接口中的事件无法声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExecutableAsDeclaration"> <source>Statement cannot appear outside of a method body.</source> <target state="translated">语句不能出现在方法主体外。</target> <note /> </trans-unit> <trans-unit id="ERR_StructureNoDefault1"> <source>Structure '{0}' cannot be indexed because it has no default property.</source> <target state="translated">无法为结构“{0}”编制索引,因为它没有默认属性。</target> <note /> </trans-unit> <trans-unit id="ERR_MustShadow2"> <source>{0} '{1}' must be declared 'Shadows' because another member with this name is declared 'Shadows'.</source> <target state="translated">{0}“{1}”必须声明为“Shadows”,因为具有此名称的另一个成员被声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithOptionalTypes2"> <source>'{0}' cannot override '{1}' because they differ by the types of optional parameters.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在可选参数类型上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndOfExpression"> <source>End of expression expected.</source> <target state="translated">应为表达式结尾。</target> <note /> </trans-unit> <trans-unit id="ERR_StructsCannotHandleEvents"> <source>Methods declared in structures cannot have 'Handles' clauses.</source> <target state="translated">结构中声明的方法不能有 "Handles" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_OverridesImpliesOverridable"> <source>Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.</source> <target state="translated">声明为 "Overrides" 的方法是隐式可重写的,因此它们不能声明为 "Overridable"。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalNamedSameAsParam1"> <source>'{0}' is already declared as a parameter of this method.</source> <target state="translated">“{0}”已声明为此方法的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalNamedSameAsParamInLambda1"> <source>Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression.</source> <target state="translated">变量“{0}”已声明为此 lambda 表达式或某个封闭 lambda 表达式的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseTypeSpecifier1"> <source>Type in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的类型不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InValidSubMainsFound1"> <source>No accessible 'Main' method with an appropriate signature was found in '{0}'.</source> <target state="translated">“{0}”中找不到带有适当签名的可访问“Main”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_MoreThanOneValidMainWasFound2"> <source>'Sub Main' is declared more than once in '{0}': {1}</source> <target state="translated">'在“{0}”中多次声明了“Sub Main”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_CannotConvertValue2"> <source>Value '{0}' cannot be converted to '{1}'.</source> <target state="translated">值“{0}”无法转换为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OnErrorInSyncLock"> <source>'On Error' statements are not valid within 'SyncLock' statements.</source> <target state="translated">'"On Error" 语句在 "SyncLock" 语句内无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NarrowingConversionCollection2"> <source>Option Strict On disallows implicit conversions from '{0}' to '{1}'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type.</source> <target state="translated">Option Strict On 不允许从“{0}”到“{1}”的隐式转换;Visual Basic 6.0 集合类型与 .NET Framework 集合类型不兼容。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoTryHandler"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”语句无效,因为“{0}”位于不包含此语句的“Try”、“Catch”或“Finally”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoSyncLock"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'SyncLock' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“SyncLock”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoWith"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'With' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“With”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoFor"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'For' or 'For Each' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“For”或“For Each”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicConstructor"> <source>Attribute cannot be used because it does not have a Public constructor.</source> <target state="translated">特性没有 Public 构造函数,因此不能使用。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultEventNotFound1"> <source>Event '{0}' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.</source> <target state="translated">由“DefaultEvent”属性指定的事件“{0}”不是该类的公共可访问事件。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNonSerializedUsage"> <source>'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.</source> <target state="translated">'"NonSerialized" 特性对此成员无效,因为它的包含类不作为 "Serializable" 公开。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContinueKind"> <source>'Continue' must be followed by 'Do', 'For' or 'While'.</source> <target state="translated">'“Continue”的后面必须跟有“Do”、“For”或“While”。</target> <note /> </trans-unit> <trans-unit id="ERR_ContinueDoNotWithinDo"> <source>'Continue Do' can only appear inside a 'Do' statement.</source> <target state="translated">'“Continue Do”只能出现在“Do”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ContinueForNotWithinFor"> <source>'Continue For' can only appear inside a 'For' statement.</source> <target state="translated">'“Continue For”只能出现在“For”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ContinueWhileNotWithinWhile"> <source>'Continue While' can only appear inside a 'While' statement.</source> <target state="translated">'“Continue While”只能出现在“While”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateParameterSpecifier"> <source>Parameter specifier is duplicated.</source> <target state="translated">参数说明符重复。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseDLLDeclareSpecifier1"> <source>'Declare' statements in a Module cannot be declared '{0}'.</source> <target state="translated">'模块中的“Declare”语句不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StructCantUseDLLDeclareSpecifier1"> <source>'Declare' statements in a structure cannot be declared '{0}'.</source> <target state="translated">'结构中的“Declare”语句不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TryCastOfValueType1"> <source>'TryCast' operand must be reference type, but '{0}' is a value type.</source> <target state="translated">'“TryCast”操作数必须是引用类型,但“{0}”是值类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TryCastOfUnconstrainedTypeParam1"> <source>'TryCast' operands must be class-constrained type parameter, but '{0}' has no class constraint.</source> <target state="translated">'“TryCast”操作数必须是类约束类型参数,但“{0}”没有类约束。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousDelegateBinding2"> <source>No accessible '{0}' is most specific: {1}</source> <target state="translated">没有非常明确的可访问“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_SharedStructMemberCannotSpecifyNew"> <source>Non-shared members in a Structure cannot be declared 'New'.</source> <target state="translated">Structure 中的非共享成员不能声明为 "New"。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericSubMainsFound1"> <source>None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types.</source> <target state="translated">在“{0}”中找到的带有适当签名的可访问“Main”方法要么都是泛型方法,要么嵌套在泛型类型中,因此均不能用作启动方法。</target> <note /> </trans-unit> <trans-unit id="ERR_GeneralProjectImportsError3"> <source>Error in project-level import '{0}' at '{1}' : {2}</source> <target state="translated">项目级 import“{0}”中的“{1}”位置出错: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidTypeForAliasesImport2"> <source>'{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.</source> <target state="translated">“{0}”的 Imports 别名的“{1}”不引用命名空间、类、结构、接口、枚举或模块。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedConstant2"> <source>Field '{0}.{1}' has an invalid constant value.</source> <target state="translated">字段“{0}.{1}”具有无效常量值。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteArgumentsNeedParens"> <source>Method arguments must be enclosed in parentheses.</source> <target state="translated">方法参数必须括在括号中。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteLineNumbersAreLabels"> <source>Labels that are numbers must be followed by colons.</source> <target state="translated">数字标签后面必须跟冒号。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteStructureNotType"> <source>'Type' statements are no longer supported; use 'Structure' statements instead.</source> <target state="translated">'不再支持 "Type" 语句;请改用 "Structure" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteObjectNotVariant"> <source>'Variant' is no longer a supported type; use the 'Object' type instead.</source> <target state="translated">'"Variant" 不再是受支持的类型;请改用 "Object" 类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteLetSetNotNeeded"> <source>'Let' and 'Set' assignment statements are no longer supported.</source> <target state="translated">'不再支持 "Let" 和 "Set" 赋值语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoletePropertyGetLetSet"> <source>Property Get/Let/Set are no longer supported; use the new Property declaration syntax.</source> <target state="translated">不再支持 Property Get/Let/Set;请使用新的 Property 声明语法。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteWhileWend"> <source>'Wend' statements are no longer supported; use 'End While' statements instead.</source> <target state="translated">'不再支持 "Wend" 语句;请改用 "End While" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteRedimAs"> <source>'ReDim' statements can no longer be used to declare array variables.</source> <target state="translated">'"ReDim" 语句不能再用于声明数组变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteOptionalWithoutValue"> <source>Optional parameters must specify a default value.</source> <target state="translated">可选参数必须指定默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteGosub"> <source>'GoSub' statements are no longer supported.</source> <target state="translated">'不再支持 "GoSub" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteOnGotoGosub"> <source>'On GoTo' and 'On GoSub' statements are no longer supported.</source> <target state="translated">'不再支持 "On GoTo" 和 "On GoSub" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteEndIf"> <source>'EndIf' statements are no longer supported; use 'End If' instead.</source> <target state="translated">'不再支持 "EndIf" 语句;请改用 "End If"。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteExponent"> <source>'D' can no longer be used to indicate an exponent, use 'E' instead.</source> <target state="translated">'"D" 不能再用来表示指数;请改用 "E"。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteAsAny"> <source>'As Any' is not supported in 'Declare' statements.</source> <target state="translated">'"Declare" 语句中不支持 "As Any"。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteGetStatement"> <source>'Get' statements are no longer supported. File I/O functionality is available in the 'Microsoft.VisualBasic' namespace.</source> <target state="translated">'不再支持 "Get" 语句。"Microsoft.VisualBasic" 命名空间中有文件 I/O 功能。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithArrayVsParamArray2"> <source>'{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在声明为 "ParamArray" 的参数上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_CircularBaseDependencies4"> <source>This inheritance causes circular dependencies between {0} '{1}' and its nested or base type '{2}'.</source> <target state="translated">此继承将导致在 {0}“{1}”及其嵌套类型或基类型“{2}”之间产生循环依赖项。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedBase2"> <source>{0} '{1}' cannot inherit from a type nested within it.</source> <target state="translated">{0}“{1}”不能从嵌套在它里面的类型继承。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatchOutsideAssembly4"> <source>'{0}' cannot expose type '{1}' outside the project through {2} '{3}'.</source> <target state="translated">“{0}”不能通过 {2}“{3}”在项目外部公开类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceAccessMismatchOutside3"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly.</source> <target state="translated">“{0}”将对基 {1} 的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoletePropertyAccessor3"> <source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source> <target state="translated">“{1}”的“{0}”访问器已过时:“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoletePropertyAccessor2"> <source>'{0}' accessor of '{1}' is obsolete.</source> <target state="translated">“{1}”的“{0}”访问器已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatchImplementedEvent6"> <source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'.</source> <target state="translated">“{0}”不能通过 {4}“{5}”向 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatchImplementedEvent4"> <source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'.</source> <target state="translated">“{0}”不能通过 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceCycleInImportedType1"> <source>Type '{0}' is not supported because it either directly or indirectly inherits from itself.</source> <target state="translated">类型“{0}”直接或者间接从自身继承,因此不受支持。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonObsoleteConstructorOnBase3"> <source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,因为它的基类“{2}”中的“{1}”被标记为已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonObsoleteConstructorOnBase4"> <source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,因为它的基类“{2}”中的“{1}”被标记为已过时:“{3}”。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNonObsoleteNewCall3"> <source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source> <target state="translated">此“Sub New”的第一条语句必须是对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标为已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNonObsoleteNewCall4"> <source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'.</source> <target state="translated">此“Sub New”的第一条语句必须是对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标为已过时:“{3}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsTypeArgAccessMismatch7"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'.</source> <target state="translated">“{0}”将对类型“{3}”的访问扩展到{4}“{5}”,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsTypeArgAccessMismatchOutside5"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly.</source> <target state="translated">“{0}”将对类型“{3}”的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeAccessMismatch3"> <source>Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types.</source> <target state="translated">“{1}”的指定访问“{0}”与它的一个其他分部类型上指定的访问“{2}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeBadMustInherit1"> <source>'MustInherit' cannot be specified for partial type '{0}' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.</source> <target state="translated">'“MustInherit”不能为分部类型“{0}”指定,因为它不能与为该类型的某个其他分部类型指定的“NotInheritable”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_MustOverOnNotInheritPartClsMem1"> <source>'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.</source> <target state="translated">'不能在此成员上指定“MustOverride”,因为它所在的分部类型在另一个分部定义中被声明为“NotInheritable”。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseMismatchForPartialClass3"> <source>Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types.</source> <target state="translated">为类“{1}”指定的基类“{0}”不能与它的其他分部类型之一的基类“{2}”不同。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeTypeParamNameMismatch3"> <source>Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'.</source> <target state="translated">类型参数名“{0}”与在“{2}”的某个其他分部类型上定义的相应类型参数的名称“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeConstraintMismatch1"> <source>Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'.</source> <target state="translated">此类型参数的约束与在“{0}”的某个其他分部类型上定义的相应类型参数的约束不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_LateBoundOverloadInterfaceCall1"> <source>Late bound overload resolution cannot be applied to '{0}' because the accessing instance is an interface type.</source> <target state="translated">后期绑定重载决策不能应用于“{0}”,因为访问实例是一个接口类型。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredAttributeConstConversion2"> <source>Conversion from '{0}' to '{1}' cannot occur in a constant expression used as an argument to an attribute.</source> <target state="translated">在用作属性参数的常量表达式中不能发生从“{0}”到“{1}”的转换。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousOverrides3"> <source>Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2}</source> <target state="translated">无法重写与此签名匹配的成员“{0}”,因为类“{1}”包含多个具有此相同名称和签名的成员: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_OverriddenCandidate1"> <source> '{0}'</source> <target state="translated"> “{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousImplements3"> <source>Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature: '{3}' '{4}'</source> <target state="translated">无法实现与此签名匹配的成员“{0}.{1}”,因为接口“{2}”包含多个具有此相同名称和签名的成员: '{3}' '{4}'</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfNotCreatableDelegate1"> <source>'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source> <target state="translated">'“AddressOf”表达式无法转换为“{0}”,因为类型“{0}”已声明为“MustInherit”,无法创建。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassGenericMethod"> <source>Generic methods cannot be exposed to COM.</source> <target state="translated">泛型方法不能向 COM 公开。</target> <note /> </trans-unit> <trans-unit id="ERR_SyntaxInCastOp"> <source>Syntax error in cast operator; two arguments separated by comma are required.</source> <target state="translated">强制转换运算符中有语法错误;需要两个用逗号分隔的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerForNonConstDim"> <source>Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'.</source> <target state="translated">无法为不定维度指定数组初始值设定项;请使用空初始值设定项“{}”。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingFailure3"> <source>No accessible method '{0}' has a signature compatible with delegate '{1}':{2}</source> <target state="translated">没有任何可访问的方法“{0}”具有与委托“{1}”兼容的签名: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_StructLayoutAttributeNotAllowed"> <source>Attribute 'StructLayout' cannot be applied to a generic type.</source> <target state="translated">特性 "StructLayout" 不能应用于泛型类型。</target> <note /> </trans-unit> <trans-unit id="ERR_IterationVariableShadowLocal1"> <source>Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression.</source> <target state="translated">范围变量“{0}”隐藏封闭块中的某个变量或以前在查询表达式中定义的某个范围变量。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionInfer"> <source>'Option Infer' can be followed only by 'On' or 'Off'.</source> <target state="translated">'"Option Infer" 后面只能跟 "On" 或 "Off"。</target> <note /> </trans-unit> <trans-unit id="ERR_CircularInference1"> <source>Type of '{0}' cannot be inferred from an expression containing '{0}'.</source> <target state="translated">无法从包含“{0}”的表达式中推断“{0}”的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InAccessibleOverridingMethod5"> <source>'{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible.</source> <target state="translated">'类“{1}”中的“{0}”不能重写类“{3}”中的“{2}”,因为中间类“{4}”重写了类“{3}”中的“{2}”,但不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuitableWidestType1"> <source>Type of '{0}' cannot be inferred because the loop bounds and the step clause do not convert to the same type.</source> <target state="translated">无法推断“{0}”的类型,因为循环边界和 step 子句不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousWidestType3"> <source>Type of '{0}' is ambiguous because the loop bounds and the step clause do not convert to the same type.</source> <target state="translated">“{0}”的类型不明确,因为循环边界和 step 子句不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAssignmentOperatorInInit"> <source>'=' expected (object initializer).</source> <target state="translated">'应为 "="(对象初始值设定项)。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedQualifiedNameInInit"> <source>Name of field or property being initialized in an object initializer must start with '.'.</source> <target state="translated">正在对象初始值设定项中初始化的字段或属性的名称必须以 "."开头。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLbrace"> <source>'{' expected.</source> <target state="translated">'应为 "{"。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedTypeOrWith"> <source>Type or 'With' expected.</source> <target state="translated">应为类型或 "With"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAggrMemberInit1"> <source>Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression.</source> <target state="translated">多次初始化“{0}”的。字段和属性只能在对象初始值设定项表达式中初始化一次。</target> <note /> </trans-unit> <trans-unit id="ERR_NonFieldPropertyAggrMemberInit1"> <source>Member '{0}' cannot be initialized in an object initializer expression because it is not a field or property.</source> <target state="translated">无法在对象初始值设定项表达式中初始化成员“{0}”,因为它不是一个字段或属性。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedMemberAggrMemberInit1"> <source>Member '{0}' cannot be initialized in an object initializer expression because it is shared.</source> <target state="translated">无法在对象初始值设定项表达式中初始化成员“{0}”,因为它是共享的。</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterizedPropertyInAggrInit1"> <source>Property '{0}' cannot be initialized in an object initializer expression because it requires arguments.</source> <target state="translated">无法在对象初始值设定项表达式中初始化属性“{0}”,因为它需要参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NoZeroCountArgumentInitCandidates1"> <source>Property '{0}' cannot be initialized in an object initializer expression because all accessible overloads require arguments.</source> <target state="translated">无法在对象初始值设定项表达式中初始化属性“{0}”,因为所有可访问的重载都需要参数。</target> <note /> </trans-unit> <trans-unit id="ERR_AggrInitInvalidForObject"> <source>Object initializer syntax cannot be used to initialize an instance of 'System.Object'.</source> <target state="translated">不能使用对象初始值设定项语法初始化“System.Object”的实例。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerExpected"> <source>Initializer expected.</source> <target state="translated">应为初始值设定项。</target> <note /> </trans-unit> <trans-unit id="ERR_LineContWithCommentOrNoPrecSpace"> <source>The line continuation character '_' must be preceded by at least one white space and it must be followed by a comment or the '_' must be the last character on the line.</source> <target state="translated">行继续符 "_" 前面必须至少有一个空格,且其后必须有注释或 "_" 必须是该行的最后一个字符。</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleFile1"> <source>Unable to load module file '{0}': {1}</source> <target state="translated">无法加载模块文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadRefLib1"> <source>Unable to load referenced library '{0}': {1}</source> <target state="translated">无法加载引用的库“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_EventHandlerSignatureIncompatible2"> <source>Method '{0}' cannot handle event '{1}' because they do not have a compatible signature.</source> <target state="translated">方法“{0}”无法处理事件“{1}”,因为它们的签名不兼容。</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalCompilationConstantNotValid"> <source>Conditional compilation constant '{1}' is not valid: {0}</source> <target state="translated">条件编译常数“{1}”无效: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwice1"> <source>Interface '{0}' can be implemented only once by this type.</source> <target state="translated">接口“{0}”只能由此类型实现一次。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames2"> <source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'.</source> <target state="translated">接口“{0}”只能通过此类型实现一次,但已显示有不同的元组元素名称,如“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames3"> <source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}').</source> <target state="translated">接口“{0}”只能通过此类型实现一次,但已显示有不同的元组元素名称,如“{1}”(通过“{2}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3"> <source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'.</source> <target state="translated">接口“{0}”只能通过此类型实现一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames4"> <source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}').</source> <target state="translated">接口“{0}”只能通过此类型实现一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”(通过“{3}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames2"> <source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'.</source> <target state="translated">接口“{0}”只能通过此接口继承一次,但已显示有不同的元组元素名称,如“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames3"> <source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}').</source> <target state="translated">接口“{0}”只能通过此接口继承一次,但已显示有不同的元组元素名称,如“{1}”(通过“{2}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3"> <source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'.</source> <target state="translated">接口“{0}”只能通过此接口继承一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames4"> <source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}').</source> <target state="translated">接口“{0}”只能通过此接口继承一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”(通过“{3}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceNotImplemented1"> <source>Interface '{0}' is not implemented by this class.</source> <target state="translated">接口“{0}”不是由此类实现的。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousImplementsMember3"> <source>'{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface.</source> <target state="translated">“{0}”存在于多个基接口中。请使用在“Implements”子句中声明“{0}”的接口的名称,而不要使用派生接口的名称。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsOnNew"> <source>'Sub New' cannot implement interface members.</source> <target state="translated">'“Sub New”无法实现接口成员。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitInStruct"> <source>Arrays declared as structure members cannot be declared with an initial size.</source> <target state="translated">声明为结构成员的数组不能用初始大小声明。</target> <note /> </trans-unit> <trans-unit id="ERR_EventTypeNotDelegate"> <source>Events declared with an 'As' clause must have a delegate type.</source> <target state="translated">用 "As" 子句声明的事件必须有委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ProtectedTypeOutsideClass"> <source>Protected types can only be declared inside of a class.</source> <target state="translated">受保护的类型只能在类内部声明。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultPropertyWithNoParams"> <source>Properties with no required parameters cannot be declared 'Default'.</source> <target state="translated">不带必选参数的属性不能声明为“Default”。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerInStruct"> <source>Initializers on structure members are valid only for 'Shared' members and constants.</source> <target state="translated">结构成员上的初始值设定项仅对“Shared”成员和常量有效。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateImport1"> <source>Namespace or type '{0}' has already been imported.</source> <target state="translated">已导入命名空间或类型呢“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleFlags1"> <source>Modules cannot be declared '{0}'.</source> <target state="translated">模块不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsStmtWrongOrder"> <source>'Implements' statements must follow any 'Inherits' statement and precede all declarations in a class.</source> <target state="translated">'“Implements”语句在类中必须位于任何“Inherits”语句之后,所有声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_SynthMemberClashesWithSynth7"> <source>{0} '{1}' implicitly defines '{2}', which conflicts with a member implicitly declared for {3} '{4}' in {5} '{6}'.</source> <target state="translated">{0}“{1}”隐式定义的“{2}”与为 {5}“{6}”中的 {3}“{4}”隐式声明的成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_SynthMemberClashesWithMember5"> <source>{0} '{1}' implicitly defines '{2}', which conflicts with a member of the same name in {3} '{4}'.</source> <target state="translated">{0}“{1}”隐式定义的“{2}”与 {3}“{4}”中的同名成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_MemberClashesWithSynth6"> <source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in {4} '{5}'.</source> <target state="translated">{0}“{1}”与为 {4}“{5}”中的 {2}“{3}”隐式声明的成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeClashesWithVbCoreType4"> <source>{0} '{1}' conflicts with a Visual Basic Runtime {2} '{3}'.</source> <target state="translated">{0}“{1}”与 Visual Basic 运行时 {2}“{3}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeMissingAction"> <source>First argument to a security attribute must be a valid SecurityAction.</source> <target state="translated">安全属性的第一个参数必须是有效的 SecurityAction。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidAction"> <source>Security attribute '{0}' has an invalid SecurityAction value '{1}'.</source> <target state="translated">安全属性“{0}”具有无效的 SecurityAction 值“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionAssembly"> <source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly.</source> <target state="translated">SecurityAction 值“{0}”对应用于程序集的安全属性无效。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod"> <source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method.</source> <target state="translated">SecurityAction 值“{0}”对应用于类型或方法的安全属性无效。</target> <note /> </trans-unit> <trans-unit id="ERR_PrincipalPermissionInvalidAction"> <source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute.</source> <target state="translated">SecurityAction 值“{0}”对 PrincipalPermission 属性无效。</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeInvalidFile"> <source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute.</source> <target state="translated">无法解析为 PermissionSet 属性的命名参数“{1}”指定的文件路径“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeFileReadError"> <source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'.</source> <target state="translated">读取为 PermissionSet 属性的命名参数“{1}”指定的文件“'{0}' ”时出错:“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SetHasOnlyOneParam"> <source>'Set' method cannot have more than one parameter.</source> <target state="translated">'"Set" 方法不能有一个以上的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_SetValueNotPropertyType"> <source>'Set' parameter must have the same type as the containing property.</source> <target state="translated">'"Set" 参数必须与包含属性的类型相同。</target> <note /> </trans-unit> <trans-unit id="ERR_SetHasToBeByVal1"> <source>'Set' parameter cannot be declared '{0}'.</source> <target state="translated">'“Set”参数不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StructureCantUseProtected"> <source>Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.</source> <target state="translated">结构中的方法不能声明为 "Protected"、"Protected Friend" 或 "Private Protected"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceDelegateSpecifier1"> <source>Delegate in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的委托不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceEnumSpecifier1"> <source>Enum in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的枚举不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceClassSpecifier1"> <source>Class in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的类不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceStructSpecifier1"> <source>Structure in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的结构不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceInterfaceSpecifier1"> <source>Interface in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的接口不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoleteSymbolNoMessage1"> <source>'{0}' is obsolete.</source> <target state="translated">“{0}”已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_MetaDataIsNotAssembly"> <source>'{0}' is a module and cannot be referenced as an assembly.</source> <target state="translated">“{0}”是一个模块,不能作为程序集引用。</target> <note /> </trans-unit> <trans-unit id="ERR_MetaDataIsNotModule"> <source>'{0}' is an assembly and cannot be referenced as a module.</source> <target state="translated">“{0}”是一个程序集,不能作为模块引用。</target> <note /> </trans-unit> <trans-unit id="ERR_ReferenceComparison3"> <source>Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types.</source> <target state="translated">没有为类型“{1}”和“{2}”定义运算符“{0}”。请使用“Is”运算符比较两个引用的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchVariableNotLocal1"> <source>'{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.</source> <target state="translated">“{0}”不是局部变量或参数,因此不能用作“Catch”变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleMemberCantImplement"> <source>Members in a Module cannot implement interface members.</source> <target state="translated">模块中的成员无法实现接口成员。</target> <note /> </trans-unit> <trans-unit id="ERR_EventDelegatesCantBeFunctions"> <source>Events cannot be declared with a delegate type that has a return type.</source> <target state="translated">事件不能用具有返回类型的委托类型声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDate"> <source>Date constant is not valid.</source> <target state="translated">日期常量无效。</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverride4"> <source>'{0}' cannot override '{1}' because it is not declared 'Overridable'.</source> <target state="translated">“{0}”无法重写“{1}”,因为后者未声明为“Overridable”。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyArraysOnBoth"> <source>Array modifiers cannot be specified on both a variable and its type.</source> <target state="translated">不能在变量及其类型上同时指定数组修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_NotOverridableRequiresOverrides"> <source>'NotOverridable' cannot be specified for methods that do not override another method.</source> <target state="translated">'不能为不重写另一个方法的方法指定 "NotOverridable"。</target> <note /> </trans-unit> <trans-unit id="ERR_PrivateTypeOutsideType"> <source>Types declared 'Private' must be inside another type.</source> <target state="translated">声明为 "Private" 的类型必须在另一个类型内。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeRefResolutionError3"> <source>Import of type '{0}' from assembly or module '{1}' failed.</source> <target state="translated">从程序集或模块“{1}”导入类型“{0}”失败。</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTupleTypeRefResolutionError1"> <source>Predefined type '{0}' is not defined or imported.</source> <target state="translated">预定义的类型“{0}”未定义或未导入。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayWrongType"> <source>ParamArray parameters must have an array type.</source> <target state="translated">ParamArray 参数必须有数组类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CoClassMissing2"> <source>Implementing class '{0}' for interface '{1}' cannot be found.</source> <target state="translated">无法找到接口“{1}”的实现类“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidCoClass1"> <source>Type '{0}' cannot be used as an implementing class.</source> <target state="translated">类型“{0}”不能用作实现类。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMeReference"> <source>Reference to object under construction is not valid when calling another constructor.</source> <target state="translated">调用另一个构造函数时引用尚未完成的对象是无效的。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidImplicitMeReference"> <source>Implicit reference to object under construction is not valid when calling another constructor.</source> <target state="translated">调用另一个构造函数时隐式引用尚未完成的对象是无效的。</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeMemberNotFound2"> <source>Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'.</source> <target state="translated">类“{1}”中找不到成员“{0}”。此情况通常是由于不匹配的“Microsoft.VisualBasic.dll”造成的。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags"> <source>Property accessors cannot be declared '{0}'.</source> <target state="translated">不能将属性访问器声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlagsRestrict"> <source>Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.</source> <target state="translated">访问修饰符“{0}”无效。“Get”和“Set”的访问修饰符的限制性应该比属性访问级别更强。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyOneAccessorForGetSet"> <source>Access modifier can only be applied to either 'Get' or 'Set', but not both.</source> <target state="translated">访问修饰符只能用于 "Get" 或者 "Set",但不能同时用于这二者。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAccessibleSet"> <source>'Set' accessor of property '{0}' is not accessible.</source> <target state="translated">'属性“{0}”的“Set”访问器不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAccessibleGet"> <source>'Get' accessor of property '{0}' is not accessible.</source> <target state="translated">'属性“{0}”的“Get”访问器不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_WriteOnlyNoAccessorFlag"> <source>'WriteOnly' properties cannot have an access modifier on 'Set'.</source> <target state="translated">'"WriteOnly" 属性在 "Set" 上不能有访问修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyNoAccessorFlag"> <source>'ReadOnly' properties cannot have an access modifier on 'Get'.</source> <target state="translated">'"ReadOnly" 属性在 "Get" 上不能有访问修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags1"> <source>Property accessors cannot be declared '{0}' in a 'NotOverridable' property.</source> <target state="translated">属性访问器不能在“NotOverridable”属性中声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags2"> <source>Property accessors cannot be declared '{0}' in a 'Default' property.</source> <target state="translated">属性访问器不能在“Default”属性中声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags3"> <source>Property cannot be declared '{0}' because it contains a 'Private' accessor.</source> <target state="translated">属性包含“Private”访问器,因此不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InAccessibleCoClass3"> <source>Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'.</source> <target state="translated">接口“{1}”的实现类“{0}”是“{2}”,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingValuesForArraysInApplAttrs"> <source>Arrays used as attribute arguments are required to explicitly specify values for all elements.</source> <target state="translated">必须有用作特性参数的数组才能显式指定所有元素的值。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitEventMemberNotInvalid"> <source>'Exit AddHandler', 'Exit RemoveHandler' and 'Exit RaiseEvent' are not valid. Use 'Return' to exit from event members.</source> <target state="translated">'"Exit AddHandler"、"Exit RemoveHandler" 和 "Exit RaiseEvent" 无效。请使用 "Return" 从事件成员中退出。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsEvent"> <source>Statement cannot appear within an event body. End of event assumed.</source> <target state="translated">语句不能出现在事件体内。假定为事件末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndEvent"> <source>'Custom Event' must end with a matching 'End Event'.</source> <target state="translated">'Custom Event 必须以匹配的 "End Event" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndAddHandler"> <source>'AddHandler' declaration must end with a matching 'End AddHandler'.</source> <target state="translated">'"AddHandler" 声明必须以匹配的 "End AddHandler" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndRemoveHandler"> <source>'RemoveHandler' declaration must end with a matching 'End RemoveHandler'.</source> <target state="translated">'"RemoveHandler" 声明必须以匹配的 "End RemoveHandler" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndRaiseEvent"> <source>'RaiseEvent' declaration must end with a matching 'End RaiseEvent'.</source> <target state="translated">'"RaiseEvent" 声明必须以匹配的 "End RaiseEvent" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_CustomEventInvInInterface"> <source>'Custom' modifier is not valid on events declared in interfaces.</source> <target state="translated">'“Custom”修饰符在接口中声明的事件上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_CustomEventRequiresAs"> <source>'Custom' modifier is not valid on events declared without explicit delegate types.</source> <target state="translated">'“Custom”修饰符在未用显式委托类型声明的事件上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndEvent"> <source>'End Event' must be preceded by a matching 'Custom Event'.</source> <target state="translated">'“End Event”前面必须是匹配的“Custom Event”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndAddHandler"> <source>'End AddHandler' must be preceded by a matching 'AddHandler' declaration.</source> <target state="translated">'“End AddHandler”前面必须是匹配的“AddHandler”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndRemoveHandler"> <source>'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.</source> <target state="translated">'“End RemoveHandler”前面必须是匹配的“RemoveHandler”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndRaiseEvent"> <source>'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.</source> <target state="translated">'“End RaiseEvent”前面必须是匹配的“RaiseEvent”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAddHandlerDef"> <source>'AddHandler' is already declared.</source> <target state="translated">'已经声明 "AddHandler"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateRemoveHandlerDef"> <source>'RemoveHandler' is already declared.</source> <target state="translated">'已经声明 "RemoveHandler"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateRaiseEventDef"> <source>'RaiseEvent' is already declared.</source> <target state="translated">'已经声明 "RaiseEvent"。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingAddHandlerDef1"> <source>'AddHandler' definition missing for event '{0}'.</source> <target state="translated">'缺少事件“{0}”的“AddHandler”定义。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingRemoveHandlerDef1"> <source>'RemoveHandler' definition missing for event '{0}'.</source> <target state="translated">'缺少事件“{0}”的“RemoveHandler”定义。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingRaiseEventDef1"> <source>'RaiseEvent' definition missing for event '{0}'.</source> <target state="translated">'缺少事件“{0}”的“RaiseEvent”定义。</target> <note /> </trans-unit> <trans-unit id="ERR_EventAddRemoveHasOnlyOneParam"> <source>'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.</source> <target state="translated">'“AddHandler”和“RemoveHandler”方法必须正好有一个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_EventAddRemoveByrefParamIllegal"> <source>'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.</source> <target state="translated">'“AddHandler”和“RemoveHandler”方法参数不能声明为“ByRef”。</target> <note /> </trans-unit> <trans-unit id="ERR_SpecifiersInvOnEventMethod"> <source>Specifiers are not valid on 'AddHandler', 'RemoveHandler' and 'RaiseEvent' methods.</source> <target state="translated">说明符在 "AddHandler"、"RemoveHandler" 和 "RaiseEvent" 方法上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_AddRemoveParamNotEventType"> <source>'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.</source> <target state="translated">'“AddHandler”和“RemoveHandler”方法参数必须与包含事件具有相同的委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_RaiseEventShapeMismatch1"> <source>'RaiseEvent' method must have the same signature as the containing event's delegate type '{0}'.</source> <target state="translated">'“RaiseEvent”方法必须具有与包含事件的委托类型“{0}”相同的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_EventMethodOptionalParamIllegal1"> <source>'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared '{0}'.</source> <target state="translated">'“AddHandler”、“RemoveHandler”和“RaiseEvent”方法参数不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_CantReferToMyGroupInsideGroupType1"> <source>'{0}' cannot refer to itself through its default instance; use 'Me' instead.</source> <target state="translated">“{0}”不能通过其默认实例指代自身;请改用“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidUseOfCustomModifier"> <source>'Custom' modifier can only be used immediately before an 'Event' declaration.</source> <target state="translated">'"Custom" 修饰符只能在紧靠 "Event" 声明之前使用。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionStrictCustom"> <source>Option Strict Custom can only be used as an option to the command-line compiler (vbc.exe).</source> <target state="translated">Option Strict Custom 只能用作命令行编译器(vbc.exe)的选项。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteInvalidOnEventMember"> <source>'{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.</source> <target state="translated">“{0}”不能应用于“'AddHandler”、“RemoveHandler”或“'RaiseEvent”定义。如有必要,请将该属性直接应用于事件。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingIncompatible2"> <source>Method '{0}' does not have a signature compatible with delegate '{1}'.</source> <target state="translated">方法“{0}”没有与委托“{1}”兼容的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlName"> <source>XML name expected.</source> <target state="translated">应为 XML 名称。</target> <note /> </trans-unit> <trans-unit id="ERR_UndefinedXmlPrefix"> <source>XML namespace prefix '{0}' is not defined.</source> <target state="translated">未定义 XML 命名空间前缀“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateXmlAttribute"> <source>Duplicate XML attribute '{0}'.</source> <target state="translated">重复的 XML 属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_MismatchedXmlEndTag"> <source>End tag &lt;/{0}{1}{2}&gt; expected.</source> <target state="translated">应为结束标记 &lt;/{0}{1}{2}&gt;。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingXmlEndTag"> <source>Element is missing an end tag.</source> <target state="translated">元素缺少结束标记。</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedXmlPrefix"> <source>XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed.</source> <target state="translated">XML 命名空间前缀“{0}”已保留供 XML 使用,并且命名空间 URI 不能更改。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingVersionInXmlDecl"> <source>Required attribute 'version' missing from XML declaration.</source> <target state="translated">XML 声明中缺少必需的特性 "version"。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalAttributeInXmlDecl"> <source>XML declaration does not allow attribute '{0}{1}{2}'.</source> <target state="translated">XML 声明不允许属性“{0}{1}{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_QuotedEmbeddedExpression"> <source>Embedded expression cannot appear inside a quoted attribute value. Try removing quotes.</source> <target state="translated">带引号的特性值内不能出现嵌入式表达式。请尝试移除引号。</target> <note /> </trans-unit> <trans-unit id="ERR_VersionMustBeFirstInXmlDecl"> <source>XML attribute 'version' must be the first attribute in XML declaration.</source> <target state="translated">XML 特性 "version" 必须是 XML 声明中的第一个特性。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeOrder"> <source>XML attribute '{0}' must appear before XML attribute '{1}'.</source> <target state="translated">XML 特性“{0}”必须出现在 XML 特性“{1}”之前。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndEmbedded"> <source>Expected closing '%&gt;' for embedded expression.</source> <target state="translated">应为嵌入表达式的结束标记“%&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndPI"> <source>Expected closing '?&gt;' for XML processor instruction.</source> <target state="translated">应为 XML 处理器指令的结束标记“?&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndComment"> <source>Expected closing '--&gt;' for XML comment.</source> <target state="translated">应为 XML 注释的结束标记“--&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndCData"> <source>Expected closing ']]&gt;' for XML CDATA section.</source> <target state="translated">应为 XML CDATA 部分的结束标记“]]&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSQuote"> <source>Expected matching closing single quote for XML attribute value.</source> <target state="translated">XML 特性值应有匹配的右单引号。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedQuote"> <source>Expected matching closing double quote for XML attribute value.</source> <target state="translated">XML 特性值应有匹配的右双引号。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLT"> <source>Expected beginning '&lt;' for an XML tag.</source> <target state="translated">XML 标记前应有 "&lt;"。</target> <note /> </trans-unit> <trans-unit id="ERR_StartAttributeValue"> <source>Expected quoted XML attribute value or embedded expression.</source> <target state="translated">应为带引号的 XML 特性值或嵌入式表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDiv"> <source>Expected '/' for XML end tag.</source> <target state="translated">应使用“/”作为 XML 结束标记。</target> <note /> </trans-unit> <trans-unit id="ERR_NoXmlAxesLateBinding"> <source>XML axis properties do not support late binding.</source> <target state="translated">XML 轴属性不支持后期绑定。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlStartNameChar"> <source>Character '{0}' ({1}) is not allowed at the beginning of an XML name.</source> <target state="translated">XML 名称的开头不允许出现字符“{0}”({1})。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlNameChar"> <source>Character '{0}' ({1}) is not allowed in an XML name.</source> <target state="translated">XML 名称中允许字符“{0}”({1})。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlCommentChar"> <source>Character sequence '--' is not allowed in an XML comment.</source> <target state="translated">XML 注释中不允许出现字符序列“--”。</target> <note /> </trans-unit> <trans-unit id="ERR_EmbeddedExpression"> <source>An embedded expression cannot be used here.</source> <target state="translated">不能在此处使用嵌入式表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlWhiteSpace"> <source>Missing required white space.</source> <target state="translated">缺少必需的空白。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalProcessingInstructionName"> <source>XML processing instruction name '{0}' is not valid.</source> <target state="translated">XML 处理指令名称“{0}”无效。</target> <note /> </trans-unit> <trans-unit id="ERR_DTDNotSupported"> <source>XML DTDs are not supported.</source> <target state="translated">不支持 XML DTD。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlWhiteSpace"> <source>White space cannot appear here.</source> <target state="translated">此处不能使用空白。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSColon"> <source>Expected closing ';' for XML entity.</source> <target state="translated">应为 XML 实体的结束标记“;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlBeginEmbedded"> <source>Expected '%=' at start of an embedded expression.</source> <target state="translated">嵌入表达式的开头应为“%=”。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlEntityReference"> <source>XML entity references are not supported.</source> <target state="translated">不支持 XML 实体引用。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeValue1"> <source>Attribute value is not valid; expecting '{0}'.</source> <target state="translated">属性值无效;应为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeValue2"> <source>Attribute value is not valid; expecting '{0}' or '{1}'.</source> <target state="translated">属性值无效;应为“{0}”或“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedXmlNamespace"> <source>Prefix '{0}' cannot be bound to namespace name reserved for '{1}'.</source> <target state="translated">不能将前缀“{0}”绑定到为“{1}”保留的命名空间名称。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalDefaultNamespace"> <source>Namespace declaration with prefix cannot have an empty value inside an XML literal.</source> <target state="translated">带前缀的命名空间声明在 XML 文本中不能有空值。</target> <note /> </trans-unit> <trans-unit id="ERR_QualifiedNameNotAllowed"> <source>':' is not allowed. XML qualified names cannot be used in this context.</source> <target state="translated">'不允许使用 ":"。不能在此上下文中使用 XML 限定名称。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlns"> <source>Namespace declaration must start with 'xmlns'.</source> <target state="translated">命名空间声明必须以“xmlns”开头。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlnsPrefix"> <source>Element names cannot use the 'xmlns' prefix.</source> <target state="translated">元素名不能使用“xmlns”前缀。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlFeaturesNotAvailable"> <source>XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.</source> <target state="translated">XML 文本和 XML 轴属性不可用。添加对 System.Xml、System.Xml.Linq 和 System.Core 的引用,或其他声明 System.Linq.Enumerable、System.Xml.Linq.XElement、System.Xml.Linq.XName、System.Xml.Linq.XAttribute 和 System.Xml.Linq.XNamespace 类型的程序集。</target> <note /> </trans-unit> <trans-unit id="ERR_UnableToReadUacManifest2"> <source>Unable to open Win32 manifest file '{0}' : {1}</source> <target state="translated">无法打开 Win32 清单文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="WRN_UseValueForXmlExpression3"> <source>Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source> <target state="translated">无法将“{0}”转换为“{1}”。可使用“Value”属性来获取“{2}”的第一个元素的字符串值。</target> <note /> </trans-unit> <trans-unit id="WRN_UseValueForXmlExpression3_Title"> <source>Cannot convert IEnumerable(Of XElement) to String</source> <target state="translated">无法将 IEnumerable(Of XElement) 转换为字符串</target> <note /> </trans-unit> <trans-unit id="ERR_TypeMismatchForXml3"> <source>Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”。可使用“Value”属性来获取“{2}”的第一个元素的字符串值。</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryOperandsForXml4"> <source>Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'.</source> <target state="translated">没有为类型“{1}”和“{2}”定义运算符“{0}”。可使用“Value”属性来获取“{3}”的第一个元素的字符串值。</target> <note /> </trans-unit> <trans-unit id="ERR_FullWidthAsXmlDelimiter"> <source>Full width characters are not valid as XML delimiters.</source> <target state="translated">全角字符不能用作 XML 分隔符。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSubsystemVersion"> <source>The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise.</source> <target state="translated">值“{0}”不是有效的子系统版本。对于 ARM 或 AppContainerExe,版本必须为 6.02 或更高版本,对于其他内容,版本必须为 4.00 或更高版本。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFileAlignment"> <source>Invalid file section alignment '{0}'</source> <target state="translated">无效的文件节对齐方式“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOutputName"> <source>Invalid output name: {0}</source> <target state="translated">无效输出名: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInformationFormat"> <source>Invalid debug information format: {0}</source> <target state="translated">无效的调试信息格式: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_LibAnycpu32bitPreferredConflict"> <source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe.</source> <target state="translated">/platform:anycpu32bitpreferred 只能与 /t:exe、/t:winexe 和 /t:appcontainerexe 一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedAccess"> <source>Expression has the type '{0}' which is a restricted type and cannot be used to access members inherited from 'Object' or 'ValueType'.</source> <target state="translated">表达式的类型为“{0}”,这是受限类型,不能用于访问从“Object”或“ValueType”继承的成员。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedConversion1"> <source>Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'.</source> <target state="translated">类型“{0}”的表达式无法转换为“Object”或“ValueType”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypecharInLabel"> <source>Type characters are not allowed in label identifiers.</source> <target state="translated">标签标识符中不允许使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedType1"> <source>'{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.</source> <target state="translated">“{0}”不能设置为可以为 null,而且不能用作数组元素、字段、匿名类型成员、类型参数、"ByRef" 参数或 return 语句的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypecharInAlias"> <source>Type characters are not allowed on Imports aliases.</source> <target state="translated">在 Imports 别名上不允许使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAccessibleConstructorOnBase"> <source>Class '{0}' has no accessible 'Sub New' and cannot be inherited.</source> <target state="translated">类“{0}”没有可访问的“Sub New”,不能被继承。</target> <note /> </trans-unit> <trans-unit id="ERR_BadStaticLocalInStruct"> <source>Local variables within methods of structures cannot be declared 'Static'.</source> <target state="translated">结构方法内部的局部变量不能声明为“Static”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLocalStatic1"> <source>Static local variable '{0}' is already declared.</source> <target state="translated">已声明静态局部变量“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ImportAliasConflictsWithType2"> <source>Imports alias '{0}' conflicts with '{1}' declared in the root namespace.</source> <target state="translated">Imports 别名“{0}”与根命名空间中声明的“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_CantShadowAMustOverride1"> <source>'{0}' cannot shadow a method declared 'MustOverride'.</source> <target state="translated">“{0}”不能隐藏声明为“MustOverride”的方法。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleEventImplMismatch3"> <source>Event '{0}' cannot implement event '{2}.{1}' because its delegate type does not match the delegate type of another event implemented by '{0}'.</source> <target state="translated">事件“{0}”不能实现事件“{2}.{1}”,因为其委托类型与“{0}”实现的另一个事件的委托类型不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadSpecifierCombo2"> <source>'{0}' and '{1}' cannot be combined.</source> <target state="translated">“{0}”不能与“{1}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_MustBeOverloads2"> <source>{0} '{1}' must be declared 'Overloads' because another '{1}' is declared 'Overloads' or 'Overrides'.</source> <target state="translated">{0}“{1}”必须声明为“Overloads”,因为另一个“{1}”声明为“Overloads”或“Overrides”。</target> <note /> </trans-unit> <trans-unit id="ERR_MustOverridesInClass1"> <source>'{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.</source> <target state="translated">“{0}”包含声明为“MustOverride”的方法,因此它必须声明为“MustInherit”。</target> <note /> </trans-unit> <trans-unit id="ERR_HandlesSyntaxInClass"> <source>'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.</source> <target state="translated">'类中的“Handles”必须指定用单个标识符限定的“WithEvents”变量、“MyBase”、“MyClass”或“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_SynthMemberShadowsMustOverride5"> <source>'{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'.</source> <target state="translated">'为 {1}“{2}”隐式声明的“{0}”不能隐藏基 {3}“{4}”中的“MustOverride”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotOverrideInAccessibleMember"> <source>'{0}' cannot override '{1}' because it is not accessible in this context.</source> <target state="translated">“{0}”无法重写“{1}”,因为它在此上下文中是无法访问的。</target> <note /> </trans-unit> <trans-unit id="ERR_HandlesSyntaxInModule"> <source>'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.</source> <target state="translated">'模块中的“Handles”必须指定用单个标识符限定的“WithEvents”变量。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNotOpRequiresReferenceTypes1"> <source>'IsNot' requires operands that have reference types, but this operand has the value type '{0}'.</source> <target state="translated">'“IsNot”要求具有引用类型的操作数,但此操作数的值类型为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ClashWithReservedEnumMember1"> <source>'{0}' conflicts with the reserved member by this name that is implicitly declared in all enums.</source> <target state="translated">“{0}”与在所有枚举中隐式声明的同名保留成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_MultiplyDefinedEnumMember2"> <source>'{0}' is already declared in this {1}.</source> <target state="translated">'此 {1} 中已声明了“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadUseOfVoid"> <source>'System.Void' can only be used in a GetType expression.</source> <target state="translated">'“System.Void”只能在 GetType 表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_EventImplMismatch5"> <source>Event '{0}' cannot implement event '{1}' on interface '{2}' because their delegate types '{3}' and '{4}' do not match.</source> <target state="translated">事件“{0}”无法实现接口“{2}”上的事件“{1}”,因为其委托类型“{3}”和“{4}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeUnavailable3"> <source>Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'.</source> <target state="translated">程序集“{1}”中的类型“{0}”已转发到程序集“{2}”。您的项目中缺少对“{2}”的引用或者程序集中“{2}”缺少类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeFwdCycle2"> <source>'{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type.</source> <target state="translated">'程序集“{1}”中的“{0}”已被转发给自身,因此它是一种不受支持的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeInCCExpression"> <source>Non-intrinsic type names are not allowed in conditional compilation expressions.</source> <target state="translated">在条件编译表达式中不允许有非内部的类型名。</target> <note /> </trans-unit> <trans-unit id="ERR_BadCCExpression"> <source>Syntax error in conditional compilation expression.</source> <target state="translated">条件编译表达式中有语法错误。</target> <note /> </trans-unit> <trans-unit id="ERR_VoidArrayDisallowed"> <source>Arrays of type 'System.Void' are not allowed in this expression.</source> <target state="translated">此表达式中不允许使用 "System.Void" 类型的数组。</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataMembersAmbiguous3"> <source>'{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'.</source> <target state="translated">“{0}”不明确,因为 {1}“{2}”中存在多种具有此名称的成员</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOfExprAlwaysFalse2"> <source>Expression of type '{0}' can never be of type '{1}'.</source> <target state="translated">类型“{0}”的表达式永远不能为类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyPrivatePartialMethods1"> <source>Partial methods must be declared 'Private' instead of '{0}'.</source> <target state="translated">必须将分部方法声明为“Private”,而不是“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodsMustBePrivate"> <source>Partial methods must be declared 'Private'.</source> <target state="translated">必须将分部方法声明为 "Private"。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyOnePartialMethodAllowed2"> <source>Method '{0}' cannot be declared 'Partial' because only one method '{1}' can be marked 'Partial'.</source> <target state="translated">方法“{0}”不能声明为“Partial”,因为只有一个方法“{1}”可以标记为“Partial”。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyOneImplementingMethodAllowed3"> <source>Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method.</source> <target state="translated">方法“{0}”无法实现分部方法“{1}”,因为它已经由“{2}”实现。分部方法只能由一个方法实现。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodMustBeEmpty"> <source>Partial methods must have empty method bodies.</source> <target state="translated">分部方法必须具有空方法体。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodsMustBeSub1"> <source>'{0}' cannot be declared 'Partial' because partial methods must be Subs.</source> <target state="translated">“{0}”不能声明为“Partial”,因为分部方法必须为 Subs。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodGenericConstraints2"> <source>Method '{0}' does not have the same generic constraints as the partial method '{1}'.</source> <target state="translated">方法“{0}”没有与分部方法“{1}”相同的泛型约束。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialDeclarationImplements1"> <source>Partial method '{0}' cannot use the 'Implements' keyword.</source> <target state="translated">分部方法“{0}”不能使用“Implements”关键字。</target> <note /> </trans-unit> <trans-unit id="ERR_NoPartialMethodInAddressOf1"> <source>'AddressOf' cannot be applied to '{0}' because '{0}' is a partial method without an implementation.</source> <target state="translated">'“AddressOf”不能应用于“{0}”,因为“{0}”是不包含实现的分部方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementationMustBePrivate2"> <source>Method '{0}' must be declared 'Private' in order to implement partial method '{1}'.</source> <target state="translated">方法“{0}”必须声明为“Private”,以便实现分部方法“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodParamNamesMustMatch3"> <source>Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'.</source> <target state="translated">参数名“{0}”与在分部方法声明“{2}”上定义的相应参数的名称“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodTypeParamNameMismatch3"> <source>Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'.</source> <target state="translated">类型参数“{0}”的名称与在分部方法声明“{2}”上定义的相应类型参数“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeSharedProperty1"> <source>'Shared' attribute property '{0}' cannot be the target of an assignment.</source> <target state="translated">'“Shared”特性属性“{0}”不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeReadOnlyProperty1"> <source>'ReadOnly' attribute property '{0}' cannot be the target of an assignment.</source> <target state="translated">'“ReadOnly”特性属性“{0}”不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateResourceName1"> <source>Resource name '{0}' cannot be used more than once.</source> <target state="translated">资源名称“{0}”不能多次使用。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateResourceFileName1"> <source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly.</source> <target state="translated">每个链接的资源和模块都必须有唯一的文件名。此程序集中多次指定了文件名“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeMustBeClassNotStruct1"> <source>'{0}' cannot be used as an attribute because it is not a class.</source> <target state="translated">“{0}”不是类,因此不能用作属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeMustInheritSysAttr"> <source>'{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'.</source> <target state="translated">“{0}”不从“System.Attribute”继承,因此不能用作属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeCannotBeAbstract"> <source>'{0}' cannot be used as an attribute because it is declared 'MustInherit'.</source> <target state="translated">“{0}”已声明为“MustInherit”,因此不能用作属性。</target> <note /> </trans-unit> <trans-unit id="ERR_UnableToOpenResourceFile1"> <source>Unable to open resource file '{0}': {1}</source> <target state="translated">无法打开资源文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicProperty1"> <source>Attribute member '{0}' cannot be the target of an assignment because it is not declared 'Public'.</source> <target state="translated">特性成员“{0}”未声明为“Public”,因此不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_STAThreadAndMTAThread0"> <source>'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.</source> <target state="translated">'"System.STAThreadAttribute" 和 "System.MTAThreadAttribute" 不能同时应用于同一方法。</target> <note /> </trans-unit> <trans-unit id="ERR_IndirectUnreferencedAssembly4"> <source>Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project.</source> <target state="translated">项目“{0}”间接引用包含“{2}”的程序集“{1}”。请在您的项目中添加对“{3}”的文件引用。 </target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicType1"> <source>Type '{0}' cannot be used in an attribute because it is not declared 'Public'.</source> <target state="translated">类型“{0}”未声明为“Public”,因此不能用在特性中。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicContType2"> <source>Type '{0}' cannot be used in an attribute because its container '{1}' is not declared 'Public'.</source> <target state="translated">类型“{0}”的容器“{1}”未声明为“Public”,因此不能用在特性中。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnNonEmptySubOrFunction"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于带有非空体的 Sub、Function 或 Operator。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportNotLegalOnDeclare"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Declare.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于 Declare。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportNotLegalOnGetOrSet"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Get or Set.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于 Get 或 Set。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnGenericSubOrFunction"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a method that is generic or contained in a generic type.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于属于泛型类型或者包含在泛型类型中的方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassOnGeneric"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”不能应用于属于泛型类型或者包含在泛型类型中的类。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnInstanceMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于实例方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnInterfaceMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to interface methods.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于接口方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportNotLegalOnEventMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to 'AddHandler', 'RemoveHandler' or 'RaiseEvent' method.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于 "AddHandler"、"RemoveHandler" 或 "RaiseEvent" 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyBadArguments"> <source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source> <target state="translated">友元程序集引用“{0}”无效。不能在 InternalsVisibleTo 声明中指定版本、区域性、公钥标记或处理器架构。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyStrongNameRequired"> <source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source> <target state="translated">友元程序集引用“{0}”无效。强名称签名的程序集必须在其 InternalsVisibleTo 声明中指定一个公钥。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyNameInvalid"> <source>Friend declaration '{0}' is invalid and cannot be resolved.</source> <target state="translated">友元声明“{0}”无效,且无法解析。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyBadAccessOverride2"> <source>Member '{0}' cannot override member '{1}' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.</source> <target state="translated">成员“{0}”无法重写另一个程序集/项目中定义的成员“{1}”,因为访问修饰符“Protected Friend”扩展了可访问性。请改用“Protected”。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfLocalBeforeDeclaration1"> <source>Local variable '{0}' cannot be referred to before it is declared.</source> <target state="translated">局部变量“{0}”在声明之前不能被引用。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfKeywordFromModule1"> <source>'{0}' is not valid within a Module.</source> <target state="translated">“{0}”在模块中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BogusWithinLineIf"> <source>Statement cannot end a block outside of a line 'If' statement.</source> <target state="translated">语句不能在“If”语句行之外结束块。</target> <note /> </trans-unit> <trans-unit id="ERR_CharToIntegralTypeMismatch1"> <source>'Char' values cannot be converted to '{0}'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit.</source> <target state="translated">'“Char”值不能转换为“{0}”。请使用“Microsoft.VisualBasic.AscW”将字符解释为 Unicode 值,或者使用“Microsoft.VisualBasic.Val”将字符解释为数字。</target> <note /> </trans-unit> <trans-unit id="ERR_IntegralToCharTypeMismatch1"> <source>'{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit.</source> <target state="translated">“{0}”值不能转换为“Char”。使用“Microsoft.VisualBasic.ChrW”将数值解释为 Unicode 字符或先将其转换为“String”以产生数字。</target> <note /> </trans-unit> <trans-unit id="ERR_NoDirectDelegateConstruction1"> <source>Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.</source> <target state="translated">委托“{0}”需要使用一个“AddressOf”表达式或 lambda 表达式作为其构造函数的唯一参数。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodMustBeFirstStatementOnLine"> <source>Method declaration statements must be the first statement on a logical line.</source> <target state="translated">方法声明语句必须是逻辑行上的第一条语句。</target> <note /> </trans-unit> <trans-unit id="ERR_AttrAssignmentNotFieldOrProp1"> <source>'{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property.</source> <target state="translated">“{0}”不是字段或属性(Property),因此不能命名为属性(Attribute)说明符中的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsObjectComparison1"> <source>Option Strict On disallows operands of type Object for operator '{0}'. Use the 'Is' operator to test for object identity.</source> <target state="translated">Option Strict On 不允许将类型 Object 的操作数用于运算符“{0}”。请使用“Is”运算符测试对象标识。</target> <note /> </trans-unit> <trans-unit id="ERR_NoConstituentArraySizes"> <source>Bounds can be specified only for the top-level array when initializing an array of arrays.</source> <target state="translated">初始化数组的数组时,只能指定顶级数组的界限。</target> <note /> </trans-unit> <trans-unit id="ERR_FileAttributeNotAssemblyOrModule"> <source>'Assembly' or 'Module' expected.</source> <target state="translated">'应为“Assembly”或“Module”。</target> <note /> </trans-unit> <trans-unit id="ERR_FunctionResultCannotBeIndexed1"> <source>'{0}' has no parameters and its return type cannot be indexed.</source> <target state="translated">“{0}”没有任何参数,并且无法对它的返回类型进行索引。</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentSyntax"> <source>Comma, ')', or a valid expression continuation expected.</source> <target state="translated">应为逗号、")" 或有效的表达式继续符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedResumeOrGoto"> <source>'Resume' or 'GoTo' expected.</source> <target state="translated">'应为 "Resume" 或 "GoTo"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAssignmentOperator"> <source>'=' expected.</source> <target state="translated">'应为 "="。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgAlsoOmitted2"> <source>Parameter '{0}' in '{1}' already has a matching omitted argument.</source> <target state="translated">“{1}”中的形参“{0}”已具有匹配的省略实参。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotCallEvent1"> <source>'{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.</source> <target state="translated">“{0}”是事件,不能直接调用。请使用“RaiseEvent”语句引发事件。</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachCollectionDesignPattern1"> <source>Expression is of type '{0}', which is not a collection type.</source> <target state="translated">表达式的类型为“{0}”,该类型不是集合类型。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueForNonOptionalParam"> <source>Default values cannot be supplied for parameters that are not declared 'Optional'.</source> <target state="translated">无法向未声明为 "Optional" 的参数提供默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDotAfterMyBase"> <source>'MyBase' must be followed by '.' and an identifier.</source> <target state="translated">'“MyBase”的后面必须跟有“.”和标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDotAfterMyClass"> <source>'MyClass' must be followed by '.' and an identifier.</source> <target state="translated">'“MyClass”的后面必须跟有“.”和标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictArgumentCopyBackNarrowing3"> <source>Option Strict On disallows narrowing from type '{1}' to type '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source> <target state="translated">将“ByRef”形参“{0}”的值复制回匹配实参时,Option Strict On 不允许从类型“{1}”收缩为类型“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_LbElseifAfterElse"> <source>'#ElseIf' cannot follow '#Else' as part of a '#If' block.</source> <target state="translated">'"#ElseIf" 不能作为 "#If" 块的一部分跟在 "#Else" 之后。</target> <note /> </trans-unit> <trans-unit id="ERR_StandaloneAttribute"> <source>Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.</source> <target state="translated">特性说明符不是一个完整的语句。请使用行继续符将该特性应用于下列语句。</target> <note /> </trans-unit> <trans-unit id="ERR_NoUniqueConstructorOnBase2"> <source>Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,因它的基类“{1}”有多个不使用参数就可以调用的可访问“Sub New”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtraNextVariable"> <source>'Next' statement names more variables than there are matching 'For' statements.</source> <target state="translated">'“Next”语句命名的变量比已有的匹配“For”语句多。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNewCallTooMany2"> <source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">“{1}”的基类“{0}”没有不使用参数就可以调用的可访问“Sub New”,因此该“Sub New”的第一个语句必须是对“MyBase.New”或“MyClass.New”的调用。</target> <note /> </trans-unit> <trans-unit id="ERR_ForCtlVarArraySizesSpecified"> <source>Array declared as for loop control variable cannot be declared with an initial size.</source> <target state="translated">声明用于循环控制变量的数组时不能使用初始大小的值。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnNewOverloads"> <source>The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'.</source> <target state="translated">“{0}”关键字用于重载继承的成员;重载“Sub New”时不要使用“{0}”关键字。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharOnGenericParam"> <source>Type character cannot be used in a type parameter declaration.</source> <target state="translated">在类型参数声明中不能使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_TooFewGenericArguments1"> <source>Too few type arguments to '{0}'.</source> <target state="translated">“{0}”的类型参数太少。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyGenericArguments1"> <source>Too many type arguments to '{0}'.</source> <target state="translated">“{0}”的类型参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfied2"> <source>Type argument '{0}' does not inherit from or implement the constraint type '{1}'.</source> <target state="translated">类型参数“{0}”不能继承自或实现约束类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOrMemberNotGeneric1"> <source>'{0}' has no type parameters and so cannot have type arguments.</source> <target state="translated">“{0}”没有类型形参,因此不能有类型实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NewIfNullOnGenericParam"> <source>'New' cannot be used on a type parameter that does not have a 'New' constraint.</source> <target state="translated">'不能在没有 "New" 约束的类型参数上使用 "New"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleClassConstraints1"> <source>Type parameter '{0}' can only have one constraint that is a class.</source> <target state="translated">类型参数“{0}”只能有一个属于类的约束。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstNotClassInterfaceOrTypeParam1"> <source>Type constraint '{0}' must be either a class, interface or type parameter.</source> <target state="translated">类型约束“{0}”必须是类、接口或类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateTypeParamName1"> <source>Type parameter already declared with name '{0}'.</source> <target state="translated">类型参数已使用名称“{0}”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_UnboundTypeParam2"> <source>Type parameter '{0}' for '{1}' cannot be inferred.</source> <target state="translated">无法推断“{1}”的类型参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_IsOperatorGenericParam1"> <source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source> <target state="translated">'类型“{0}”是没有类约束的类型参数,因此类型“{0}”的“Is”操作数只能与“Nothing”比较。</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentCopyBackNarrowing3"> <source>Copying the value of 'ByRef' parameter '{0}' back to the matching argument narrows from type '{1}' to type '{2}'.</source> <target state="translated">将“ByRef”参数“{0}”的值复制回匹配的参数将导致从类型“{1}”到类型“{2}”的收缩。</target> <note /> </trans-unit> <trans-unit id="ERR_ShadowingGenericParamWithMember1"> <source>'{0}' has the same name as a type parameter.</source> <target state="translated">“{0}”与一个类型参数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericParamBase2"> <source>{0} '{1}' cannot inherit from a type parameter.</source> <target state="translated">{0}“{1}”不能从类型参数中继承。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsGenericParam"> <source>Type parameter not allowed in 'Implements' clause.</source> <target state="translated">“Implements”子句中不允许类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyNullLowerBound"> <source>Array lower bounds can be only '0'.</source> <target state="translated">数组的下限只能是“0”。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassConstraintNotInheritable1"> <source>Type constraint cannot be a 'NotInheritable' class.</source> <target state="translated">类型约束不能是“NotInheritable”类。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintIsRestrictedType1"> <source>'{0}' cannot be used as a type constraint.</source> <target state="translated">“{0}”不能用作类型约束。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericParamsOnInvalidMember"> <source>Type parameters cannot be specified on this declaration.</source> <target state="translated">在此声明上不能指定类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericArgsOnAttributeSpecifier"> <source>Type arguments are not valid because attributes cannot be generic.</source> <target state="translated">由于特性不能是泛型,因此类型参数无效。</target> <note /> </trans-unit> <trans-unit id="ERR_AttrCannotBeGenerics"> <source>Type parameters, generic types or types contained in generic types cannot be used as attributes.</source> <target state="translated">类型参数、泛型类型或泛型类型中包含的类型不能用作特性。</target> <note /> </trans-unit> <trans-unit id="ERR_BadStaticLocalInGenericMethod"> <source>Local variables within generic methods cannot be declared 'Static'.</source> <target state="translated">泛型方法中的局部变量不能声明为“Static”。</target> <note /> </trans-unit> <trans-unit id="ERR_SyntMemberShadowsGenericParam3"> <source>{0} '{1}' implicitly defines a member '{2}' which has the same name as a type parameter.</source> <target state="translated">{0}“{1}”隐式定义了与某个类型参数同名的成员“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintAlreadyExists1"> <source>Constraint type '{0}' already specified for this type parameter.</source> <target state="translated">已为此类型参数指定了约束类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacePossiblyImplTwice2"> <source>Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,该接口的实现可能与另一个已实现的接口“{1}”的实现冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ModulesCannotBeGeneric"> <source>Modules cannot be generic.</source> <target state="translated">模块不能是泛型的。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericClassCannotInheritAttr"> <source>Classes that are generic or contained in a generic type cannot inherit from an attribute class.</source> <target state="translated">属于泛型或包含在泛型类型中的类不能从特性类继承。</target> <note /> </trans-unit> <trans-unit id="ERR_DeclaresCantBeInGeneric"> <source>'Declare' statements are not allowed in generic types or types contained in generic types.</source> <target state="translated">'泛型类型或包含在泛型类型中的类型中不允许“Declare”语句。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithConstraintMismatch2"> <source>'{0}' cannot override '{1}' because they differ by type parameter constraints.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在类型参数约束上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsWithConstraintMismatch3"> <source>'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints.</source> <target state="translated">“{0}”无法实现“{1}.{2}”,因为它们在类型参数约束上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_OpenTypeDisallowed"> <source>Type parameters or types constructed with type parameters are not allowed in attribute arguments.</source> <target state="translated">特性实参中不允许类型形参或用类型形参构造的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_HandlesInvalidOnGenericMethod"> <source>Generic methods cannot use 'Handles' clause.</source> <target state="translated">泛型方法不能使用“Handles”子句。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleNewConstraints"> <source>'New' constraint cannot be specified multiple times for the same type parameter.</source> <target state="translated">'"New" 约束不能为同一类型参数指定多次。</target> <note /> </trans-unit> <trans-unit id="ERR_MustInheritForNewConstraint2"> <source>Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”声明为“MustInherit”,并且不满足类型形参“{1}”的“New”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuitableNewForNewConstraint2"> <source>Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”必须具有一个公共的无参数实例构造函数,才能满足类型形参“{1}”的“New”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_BadGenericParamForNewConstraint2"> <source>Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'.</source> <target state="translated">类型参数“{0}”必须具有“New”约束或“Structure”约束,才能满足类型参数“{1}”的“New”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_NewArgsDisallowedForTypeParam"> <source>Arguments cannot be passed to a 'New' used on a type parameter.</source> <target state="translated">无法给类型形参上使用的 "New" 传递实参。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateRawGenericTypeImport1"> <source>Generic type '{0}' cannot be imported more than once.</source> <target state="translated">不能多次导入泛型类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypeArgumentCountOverloadCand1"> <source>Overload resolution failed because no accessible '{0}' accepts this number of type arguments.</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”接受此数量的类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeArgsUnexpected"> <source>Type arguments unexpected.</source> <target state="translated">不应为类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NameSameAsMethodTypeParam1"> <source>'{0}' is already declared as a type parameter of this method.</source> <target state="translated">“{0}”已声明为此方法的类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamNameFunctionNameCollision"> <source>Type parameter cannot have the same name as its defining function.</source> <target state="translated">类型参数不能与其定义函数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstraintSyntax"> <source>Type or 'New' expected.</source> <target state="translated">应为类型或“New”。</target> <note /> </trans-unit> <trans-unit id="ERR_OfExpected"> <source>'Of' required when specifying type arguments for a generic type or method.</source> <target state="translated">'在指定泛型类型或方法的类型参数时需要 "Of"。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayOfRawGenericInvalid"> <source>'(' unexpected. Arrays of uninstantiated generic types are not allowed.</source> <target state="translated">'不应为 "("。不允许非实例化泛型类型的数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachAmbiguousIEnumerable1"> <source>'For Each' on type '{0}' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'.</source> <target state="translated">'类型“{0}”的“For Each”不明确,因为此类型实现了“System.Collections.Generic.IEnumerable(Of T)”的多个实例化。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNotOperatorGenericParam1"> <source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source> <target state="translated">'类型“{0}”是没有类约束的类型参数,因此类型“{0}”的“Isnot”操作数只能与“Nothing”比较。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamQualifierDisallowed"> <source>Type parameters cannot be used as qualifiers.</source> <target state="translated">类型参数不能用作限定符。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamMissingCommaOrRParen"> <source>Comma or ')' expected.</source> <target state="translated">应为逗号或 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamMissingAsCommaOrRParen"> <source>'As', comma or ')' expected.</source> <target state="translated">'应为 "As"、逗号或 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleReferenceConstraints"> <source>'Class' constraint cannot be specified multiple times for the same type parameter.</source> <target state="translated">'"Class" 约束不能为同一类型参数指定多次。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleValueConstraints"> <source>'Structure' constraint cannot be specified multiple times for the same type parameter.</source> <target state="translated">'"Structure" 约束不能为同一类型参数指定多次。</target> <note /> </trans-unit> <trans-unit id="ERR_NewAndValueConstraintsCombined"> <source>'New' constraint and 'Structure' constraint cannot be combined.</source> <target state="translated">'"New" 约束不能与 "Structure" 约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_RefAndValueConstraintsCombined"> <source>'Class' constraint and 'Structure' constraint cannot be combined.</source> <target state="translated">'"Class" 约束不能与 "Structure" 约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgForStructConstraint2"> <source>Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”不满足类型形参“{1}”的“Structure”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgForRefConstraint2"> <source>Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”不满足类型形参“{1}”的“Class”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_RefAndClassTypeConstrCombined"> <source>'Class' constraint and a specific class type constraint cannot be combined.</source> <target state="translated">'"Class" 约束不能与特定的类类型约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_ValueAndClassTypeConstrCombined"> <source>'Structure' constraint and a specific class type constraint cannot be combined.</source> <target state="translated">'"Structure" 约束不能与特定的类类型约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintClashIndirectIndirect4"> <source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'.</source> <target state="translated">从类型参数约束“{1}”获得的间接约束“{0}”与从类型参数约束“{3}”获得的间接约束“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintClashDirectIndirect3"> <source>Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'.</source> <target state="translated">约束“{0}”与从类型参数约束“{2}”获得的间接约束“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintClashIndirectDirect3"> <source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'.</source> <target state="translated">从类型参数约束“{1}”获得的间接约束“{0}”与约束“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintCycleLink2"> <source> '{0}' is constrained to '{1}'.</source> <target state="translated"> “{0}”被约束为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintCycle2"> <source>Type parameter '{0}' cannot be constrained to itself: {1}</source> <target state="translated">类型参数“{0}”不能约束为自身: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamWithStructConstAsConst"> <source>Type parameter with a 'Structure' constraint cannot be used as a constraint.</source> <target state="translated">具有 "Structure" 约束的类型参数不能用作约束。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableDisallowedForStructConstr1"> <source>'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed.</source> <target state="translated">'“System.Nullable”不满足类型参数“{0}”的“Structure”约束。仅允许不可为 null 的“Structure”类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingDirectConstraints3"> <source>Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'.</source> <target state="translated">约束“{0}”与已为类型参数“{2}”指定的约束“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceUnifiesWithInterface2"> <source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,该接口与接口“{1}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseUnifiesWithInterfaces3"> <source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,它所继承的接口“{1}”可能与接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceBaseUnifiesWithBase4"> <source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the interface '{3}' inherits for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,继承的接口“{1}”可能与接口“{3}”继承的接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceUnifiesWithBase3"> <source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' from which the interface '{2}' inherits for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,该接口与接口“{2}”继承的接口“{1}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassInheritsBaseUnifiesWithInterfaces3"> <source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to implemented interface '{2}' for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,它所继承的接口“{1}”可能与实现的接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassInheritsInterfaceBaseUnifiesWithBase4"> <source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the implemented interface '{3}' inherits for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,它所继承的接口“{1}”可能与实现的接口“{3}”所继承的接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassInheritsInterfaceUnifiesWithBase3"> <source>Cannot implement interface '{0}' because it could be identical to interface '{1}' from which the implemented interface '{2}' inherits for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,它可能与实现的接口“{2}”所继承的接口“{1}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_OptionalsCantBeStructGenericParams"> <source>Generic parameters used as optional parameter types must be class constrained.</source> <target state="translated">用作可选参数类型的泛型参数必须受类约束。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfNullableMethod"> <source>Methods of 'System.Nullable(Of T)' cannot be used as operands of the 'AddressOf' operator.</source> <target state="translated">“System.Nullable(Of T)”的方法不能用作“AddressOf”运算符的操作数。</target> <note /> </trans-unit> <trans-unit id="ERR_IsOperatorNullable1"> <source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source> <target state="translated">'类型“{0}”是可以为 null 的类型,因此“{0}”的“Is”操作数只能与“Nothing”进行比较。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNotOperatorNullable1"> <source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source> <target state="translated">'类型“{0}”是可以为 null 的类型,因此“{0}”的“IsNot”操作数只能与“Nothing”进行比较。</target> <note /> </trans-unit> <trans-unit id="ERR_ShadowingTypeOutsideClass1"> <source>'{0}' cannot be declared 'Shadows' outside of a class, structure, or interface.</source> <target state="translated">“{0}”不能在类、结构或接口外声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertySetParamCollisionWithValue"> <source>Property parameters cannot have the name 'Value'.</source> <target state="translated">属性参数的名称不能为 "Value"。</target> <note /> </trans-unit> <trans-unit id="ERR_SxSIndirectRefHigherThanDirectRef3"> <source>The project currently contains references to more than one version of '{0}', a direct reference to version {2} and an indirect reference to version {1}. Change the direct reference to use version {1} (or higher) of {0}.</source> <target state="translated">项目当前包含对多个版本的“{0}”的引用、对版本 {2} 的直接引用和对版本 {1} 的间接引用。请将直接引用更改为使用 {0} 的版本 {1} (或更高版本)。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateReferenceStrong"> <source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source> <target state="translated">导入了具有等效标识的多个程序集:“{0}”和“{1}”。请删除重复引用之一。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateReference2"> <source>Project already has a reference to assembly '{0}'. A second reference to '{1}' cannot be added.</source> <target state="translated">项目已经具有对程序集“{0}”的引用。无法添加另一个对“{1}”的引用。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalCallOrIndex"> <source>Illegal call expression or index expression.</source> <target state="translated">非法的调用表达式或索引表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictDefaultPropertyAttribute"> <source>Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'.</source> <target state="translated">默认属性与“{0}”上定义的“DefaultMemberAttribute”之间有冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeUuid2"> <source>'{0}' cannot be applied because the format of the GUID '{1}' is not correct.</source> <target state="translated">'GUID“{1}”的格式不正确,因此无法应用“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassAndReservedAttribute1"> <source>'Microsoft.VisualBasic.ComClassAttribute' and '{0}' cannot both be applied to the same class.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”和“{0}”不能同时应用于同一个类。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassRequiresPublicClass2"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because its container '{1}' is not declared 'Public'.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”的容器“{1}”未声明为“Public”,因此不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassReservedDispIdZero1"> <source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”为默认属性保留的值为零,因此“System.Runtime.InteropServices.DispIdAttribute”不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassReservedDispId1"> <source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”保留的值小于零,因此“System.Runtime.InteropServices.DispIdAttribute”不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassDuplicateGuids1"> <source>'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on '{0}' cannot have the same value.</source> <target state="translated">“{0}”上“Microsoft.VisualBasic.ComClassAttribute”的“InterfaceId”和“EventsId”参数的值不能相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassCantBeAbstract0"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”不能应用于被声明为“MustInherit”的类。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassRequiresPublicClass1"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because it is not declared 'Public'.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”未声明为“Public”,因此不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UnknownOperator"> <source>Operator declaration must be one of: +, -, *, \, /, ^, &amp;, Like, Mod, And, Or, Xor, Not, &lt;&lt;, &gt;&gt;, =, &lt;&gt;, &lt;, &lt;=, &gt;, &gt;=, CType, IsTrue, IsFalse.</source> <target state="translated">运算符声明必须是以下符号之一: +、-、*、\、/、^、&amp;,、Like、Mod、And、Or、Xor、Not、&lt;&lt;、&gt;&gt;、=、&lt;&gt;、&lt;、&lt;=、&gt;、&gt;=、CType、IsTrue 和 IsFalse。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateConversionCategoryUsed"> <source>'Widening' and 'Narrowing' cannot be combined.</source> <target state="translated">'"Widening" 不能与 "Narrowing" 组合。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorNotOverloadable"> <source>Operator is not overloadable. Operator declaration must be one of: +, -, *, \, /, ^, &amp;, Like, Mod, And, Or, Xor, Not, &lt;&lt;, &gt;&gt;, =, &lt;&gt;, &lt;, &lt;=, &gt;, &gt;=, CType, IsTrue, IsFalse.</source> <target state="translated">运算符不可重载。运算符声明必须是以下符号之一: +、-、*、\、/、^、&amp;,、Like、Mod、And、Or、Xor、Not、&lt;&lt;、&gt;&gt;、=、&lt;&gt;、&lt;、&lt;=、&gt;、&gt;=、CType、IsTrue 和 IsFalse。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidHandles"> <source>'Handles' is not valid on operator declarations.</source> <target state="translated">'“Handles”在运算符声明上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidImplements"> <source>'Implements' is not valid on operator declarations.</source> <target state="translated">'“Implements”在运算符声明上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_EndOperatorExpected"> <source>'End Operator' expected.</source> <target state="translated">'应为 "End Operator"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndOperatorNotAtLineStart"> <source>'End Operator' must be the first statement on a line.</source> <target state="translated">'“End Operator”必须是一行中的第一条语句。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndOperator"> <source>'End Operator' must be preceded by a matching 'Operator'.</source> <target state="translated">'“End Operator”前面必须是匹配的“Operator”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitOperatorNotValid"> <source>'Exit Operator' is not valid. Use 'Return' to exit an operator.</source> <target state="translated">'"Exit Operator" 无效。请使用 "Return" 从运算符中退出。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayIllegal1"> <source>'{0}' parameters cannot be declared 'ParamArray'.</source> <target state="translated">“{0}”参数不能声明为 "ParamArray"。</target> <note /> </trans-unit> <trans-unit id="ERR_OptionalIllegal1"> <source>'{0}' parameters cannot be declared 'Optional'.</source> <target state="translated">“{0}”参数不能声明为“Optional”。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorMustBePublic"> <source>Operators must be declared 'Public'.</source> <target state="translated">运算符必须声明为 "Public"。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorMustBeShared"> <source>Operators must be declared 'Shared'.</source> <target state="translated">运算符必须声明为 "Shared"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadOperatorFlags1"> <source>Operators cannot be declared '{0}'.</source> <target state="translated">运算符不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OneParameterRequired1"> <source>Operator '{0}' must have one parameter.</source> <target state="translated">运算符“{0}”必须有一个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TwoParametersRequired1"> <source>Operator '{0}' must have two parameters.</source> <target state="translated">运算符“{0}”必须有两个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OneOrTwoParametersRequired1"> <source>Operator '{0}' must have either one or two parameters.</source> <target state="translated">运算符“{0}”必须有一个两个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvMustBeWideningOrNarrowing"> <source>Conversion operators must be declared either 'Widening' or 'Narrowing'.</source> <target state="translated">转换运算符必须声明为“Widening”或者“Narrowing”。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorDeclaredInModule"> <source>Operators cannot be declared in modules.</source> <target state="translated">运算符不能在模块中声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSpecifierOnNonConversion1"> <source>Only conversion operators can be declared '{0}'.</source> <target state="translated">只有转换运算符可以声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UnaryParamMustBeContainingType1"> <source>Parameter of this unary operator must be of the containing type '{0}'.</source> <target state="translated">此一元运算符的参数必须属于包含类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryParamMustBeContainingType1"> <source>At least one parameter of this binary operator must be of the containing type '{0}'.</source> <target state="translated">此二元运算符的至少一个参数必须属于包含类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvParamMustBeContainingType1"> <source>Either the parameter type or the return type of this conversion operator must be of the containing type '{0}'.</source> <target state="translated">此转换运算符的参数类型或返回类型必须属于包含类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorRequiresBoolReturnType1"> <source>Operator '{0}' must have a return type of Boolean.</source> <target state="translated">运算符“{0}”必须具有 Boolean 返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToSameType"> <source>Conversion operators cannot convert from a type to the same type.</source> <target state="translated">转换运算符不能从某一类型转换为相同的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToInterfaceType"> <source>Conversion operators cannot convert to an interface type.</source> <target state="translated">转换运算符不能转换为接口类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToBaseType"> <source>Conversion operators cannot convert from a type to its base type.</source> <target state="translated">转换运算符不能从某一类型转换为它的基类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToDerivedType"> <source>Conversion operators cannot convert from a type to its derived type.</source> <target state="translated">转换运算符不能从某一类型转换为它的派生类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToObject"> <source>Conversion operators cannot convert to Object.</source> <target state="translated">转换运算符不能转换为 Object。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromInterfaceType"> <source>Conversion operators cannot convert from an interface type.</source> <target state="translated">转换运算符不能从接口类型转换。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromBaseType"> <source>Conversion operators cannot convert from a base type.</source> <target state="translated">转换运算符不能从基类型转换。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromDerivedType"> <source>Conversion operators cannot convert from a derived type.</source> <target state="translated">转换运算符不能从派生类型转换。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromObject"> <source>Conversion operators cannot convert from Object.</source> <target state="translated">转换运算符不能从 Object 转换。</target> <note /> </trans-unit> <trans-unit id="ERR_MatchingOperatorExpected2"> <source>Matching '{0}' operator is required for '{1}'.</source> <target state="translated">“{1}”需要匹配“{0}”运算符。</target> <note /> </trans-unit> <trans-unit id="ERR_UnacceptableLogicalOperator3"> <source>Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression.</source> <target state="translated">“{0}”的返回类型和参数类型必须是“{1}”,才能在“{2}”表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionOperatorRequired3"> <source>Type '{0}' must define operator '{1}' to be used in a '{2}' expression.</source> <target state="translated">类型“{0}”必须定义运算符“{1}”,才能在“{2}”表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CopyBackTypeMismatch3"> <source>Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'.</source> <target state="translated">由于类型“{1}”不能转换为类型“{2}”,因此无法将“ByRef”参数“{0}”的值复制回匹配的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ForLoopOperatorRequired2"> <source>Type '{0}' must define operator '{1}' to be used in a 'For' statement.</source> <target state="translated">类型“{0}”必须定义运算符“{1}”,才能在“For”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_UnacceptableForLoopOperator2"> <source>Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source> <target state="translated">“{0}”的返回类型和参数类型必须是“{1}”,才能在“For”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_UnacceptableForLoopRelOperator2"> <source>Parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source> <target state="translated">“{0}”的参数类型必须是“{1}”,才能在“For”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorRequiresIntegerParameter1"> <source>Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'.</source> <target state="translated">运算符“{0}”必须有另一个“Integer”或“Integer?”类型的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyNullableOnBoth"> <source>Nullable modifier cannot be specified on both a variable and its type.</source> <target state="translated">不能在变量及其类型上同时指定可以为 null 的修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgForStructConstraintNull"> <source>Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.</source> <target state="translated">类型“{0}”必须是一个被约束为“Structure”的值类型或类型参数,才能与“Nullable”或可以为 null 的修饰符“?”一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyArrayAndNullableOnBoth"> <source>Nullable modifier '?' and array modifiers '(' and ')' cannot be specified on both a variable and its type.</source> <target state="translated">不能在变量及其类型上同时指定可为 null 的修饰符“?”和数组修饰符“(”/“)”。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyTypeCharacterOnIIF"> <source>Expressions used with an 'If' expression cannot contain type characters.</source> <target state="translated">与“If”表达式一起使用的表达式不能包含类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFName"> <source>'If' operands cannot be named arguments.</source> <target state="translated">'“If”操作数不能是命名参数。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFConversion"> <source>Cannot infer a common type for the second and third operands of the 'If' operator. One must have a widening conversion to the other.</source> <target state="translated">无法推断“If”运算符的第二个和第三个操作数的通用类型。其中一个必须是另一个的扩大转换。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalCondTypeInIIF"> <source>First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type.</source> <target state="translated">二进制“If”表达式中的第一个操作数必须是可以为 null 的类型或引用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CantCallIIF"> <source>'If' operator cannot be used in a 'Call' statement.</source> <target state="translated">'“If”运算符不能在“Call”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyAsNewAndNullable"> <source>Nullable modifier cannot be specified in variable declarations with 'As New'.</source> <target state="translated">在变量声明中不能用“As New”指定可以为 null 的修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFConversion2"> <source>Cannot infer a common type for the first and second operands of the binary 'If' operator. One must have a widening conversion to the other.</source> <target state="translated">无法推断二元“If”运算符的第一个和第二个操作数的通用类型。其中一个必须是另一个的扩大转换。</target> <note /> </trans-unit> <trans-unit id="ERR_BadNullTypeInCCExpression"> <source>Nullable types are not allowed in conditional compilation expressions.</source> <target state="translated">在条件编译表达式中不允许有可以为 null 的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableImplicit"> <source>Nullable modifier cannot be used with a variable whose implicit type is 'Object'.</source> <target state="translated">可以为 null 的修饰符不能与隐式类型为 "Object" 的变量一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingRuntimeHelper"> <source>Requested operation is not available because the runtime library function '{0}' is not defined.</source> <target state="translated">所请求的操作不可用,因为没有定义运行库函数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDotAfterGlobalNameSpace"> <source>'Global' must be followed by '.' and an identifier.</source> <target state="translated">'“Global”的后面必须跟有“.”和标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_NoGlobalExpectedIdentifier"> <source>'Global' not allowed in this context; identifier expected.</source> <target state="translated">'此上下文中不允许 "Global";应为标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_NoGlobalInHandles"> <source>'Global' not allowed in handles; local name expected.</source> <target state="translated">'句柄中不允许 "Global";应为本地名称。</target> <note /> </trans-unit> <trans-unit id="ERR_ElseIfNoMatchingIf"> <source>'ElseIf' must be preceded by a matching 'If' or 'ElseIf'.</source> <target state="translated">'"ElseIf" 前面必须是匹配的 "If" 或 "ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeConstructor2"> <source>Attribute constructor has a 'ByRef' parameter of type '{0}'; cannot use constructors with byref parameters to apply the attribute.</source> <target state="translated">特性构造函数有一个“{0}”类型的“ByRef”参数;不能用带有 byref 参数的构造函数来应用特性。</target> <note /> </trans-unit> <trans-unit id="ERR_EndUsingWithoutUsing"> <source>'End Using' must be preceded by a matching 'Using'.</source> <target state="translated">'“End Using”前面必须是匹配的“Using”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndUsing"> <source>'Using' must end with a matching 'End Using'.</source> <target state="translated">'“Using”必须以匹配的“End Using”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoUsing"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'Using' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“Using”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_UsingRequiresDisposePattern"> <source>'Using' operand of type '{0}' must implement 'System.IDisposable'.</source> <target state="translated">“{0}”类型的“Using”操作数必须实现“System.IDisposable”。</target> <note /> </trans-unit> <trans-unit id="ERR_UsingResourceVarNeedsInitializer"> <source>'Using' resource variable must have an explicit initialization.</source> <target state="translated">'"Using" 资源变量必须有一个显式初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_UsingResourceVarCantBeArray"> <source>'Using' resource variable type can not be array type.</source> <target state="translated">'"Using" 资源变量类型不能是数组类型。</target> <note /> </trans-unit> <trans-unit id="ERR_OnErrorInUsing"> <source>'On Error' statements are not valid within 'Using' statements.</source> <target state="translated">'"On Error" 语句在 "Using" 语句内无效。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyNameConflictInMyCollection"> <source>'{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace.</source> <target state="translated">“{0}”与“My”组中公开的类型“{1}”所使用的成员同名。请重命名该类型或其封闭命名空间。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidImplicitVar"> <source>Implicit variable '{0}' is invalid because of '{1}'.</source> <target state="translated">由于“{1}”,隐式变量“{0}”无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectInitializerRequiresFieldName"> <source>Object initializers require a field name to initialize.</source> <target state="translated">对象初始值设定项需要一个字段名称以便进行初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedFrom"> <source>'From' expected.</source> <target state="translated">'应为“From”。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaBindingMismatch1"> <source>Nested function does not have the same signature as delegate '{0}'.</source> <target state="translated">嵌套函数与委托“{0}”的签名不相同。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaBindingMismatch2"> <source>Nested sub does not have a signature that is compatible with delegate '{0}'.</source> <target state="translated">嵌套 Sub 的签名与委托“{0}”不兼容。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftByRefParamQuery1"> <source>'ByRef' parameter '{0}' cannot be used in a query expression.</source> <target state="translated">'不能在查询表达式中使用“ByRef”参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeNotSupported"> <source>Expression cannot be converted into an expression tree.</source> <target state="translated">无法将表达式转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftStructureMeQuery"> <source>Instance members and 'Me' cannot be used within query expressions in structures.</source> <target state="translated">无法在结构中的查询表达式中使用实例成员和“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_InferringNonArrayType1"> <source>Variable cannot be initialized with non-array type '{0}'.</source> <target state="translated">无法用非数组类型“{0}”初始化变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefParamInExpressionTree"> <source>References to 'ByRef' parameters cannot be converted to an expression tree.</source> <target state="translated">对“ByRef”参数的引用无法转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAnonTypeMemberName1"> <source>Anonymous type member or property '{0}' is already declared.</source> <target state="translated">已声明匿名类型成员或属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAnonymousTypeForExprTree"> <source>Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.</source> <target state="translated">无法将匿名类型转换为表达式树,因为此类型的属性用于初始化其他属性。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftAnonymousType1"> <source>Anonymous type property '{0}' cannot be used in the definition of a lambda expression within the same initialization list.</source> <target state="translated">不能在同一个初始化列表中的 lambda 表达式定义中使用匿名类型属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionOnlyAllowedOnModuleSubOrFunction"> <source>'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations.</source> <target state="translated">'“Extension”特性只能应用于“Module”、“Sub”或“Function”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodNotInModule"> <source>Extension methods can be defined only in modules.</source> <target state="translated">只能在模块中定义扩展方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodNoParams"> <source>Extension methods must declare at least one parameter. The first parameter specifies which type to extend.</source> <target state="translated">扩展方法必须至少声明一个参数。第一个参数指定要扩展的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodOptionalFirstArg"> <source>'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source> <target state="translated">'“Optional”无法应用于扩展方法的第一个参数。第一个参数指定要扩展哪个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodParamArrayFirstArg"> <source>'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source> <target state="translated">"ParamArray" 无法应用于扩展方法的第一个参数。第一个参数指定要扩展哪个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeFieldNameInference"> <source>Anonymous type member name can be inferred only from a simple or qualified name with no arguments.</source> <target state="translated">只能从不带参数的简单名或限定名中推断匿名类型成员名称。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotMemberOfAnonymousType2"> <source>'{0}' is not a member of '{1}'; it does not exist in the current context.</source> <target state="translated">“{0}”不是“{1}”的成员;它不存在于当前上下文。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionAttributeInvalid"> <source>The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods.</source> <target state="translated">编译器找到的“System.Runtime.CompilerServices.ExtensionAttribute”的自定义设计版本无效。必须将其特性用法标志设置为允许程序集、类和方法使用。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypePropertyOutOfOrder1"> <source>Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established.</source> <target state="translated">无法使用匿名类型成员属性“{0}”来推断另一个成员属性的类型,因为尚未建立“{0}”的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeDisallowsTypeChar"> <source>Type characters cannot be used in anonymous type declarations.</source> <target state="translated">不能在匿名类型声明中使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleLiteralDisallowsTypeChar"> <source>Type characters cannot be used in tuple literals.</source> <target state="translated">类型字符无法用在元组文本中。</target> <note /> </trans-unit> <trans-unit id="ERR_NewWithTupleTypeSyntax"> <source>'New' cannot be used with tuple type. Use a tuple literal expression instead.</source> <target state="translated">"New" 不能与元组类型共同使用。请改用元组字面量表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct"> <source>Predefined type '{0}' must be a structure.</source> <target state="translated">预定义的类型“{0}”必须是一种结构。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodUncallable1"> <source>Extension method '{0}' has type constraints that can never be satisfied.</source> <target state="translated">扩展方法“{0}”具有无法满足的类型约束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodOverloadCandidate3"> <source> Extension method '{0}' defined in '{1}': {2}</source> <target state="translated"> “{1}”中定义的扩展方法“{0}”: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingMismatch"> <source>Method does not have a signature compatible with the delegate.</source> <target state="translated">方法没有与委托兼容的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingTypeInferenceFails"> <source>Type arguments could not be inferred from the delegate.</source> <target state="translated">未能从委托中推断类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyArgs"> <source>Too many arguments.</source> <target state="translated">参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgAlsoOmitted1"> <source>Parameter '{0}' already has a matching omitted argument.</source> <target state="translated">形参“{0}”已具有匹配的省略实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgUsedTwice1"> <source>Parameter '{0}' already has a matching argument.</source> <target state="translated">形参“{0}”已具有匹配的实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamNotFound1"> <source>'{0}' is not a method parameter.</source> <target state="translated">“{0}”不是方法参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedArgument1"> <source>Argument not specified for parameter '{0}'.</source> <target state="translated">没有为参数“{0}”指定参数。</target> <note /> </trans-unit> <trans-unit id="ERR_UnboundTypeParam1"> <source>Type parameter '{0}' cannot be inferred.</source> <target state="translated">无法推断类型参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodOverloadCandidate2"> <source> Extension method '{0}' defined in '{1}'.</source> <target state="translated"> “{1}”中定义的扩展方法“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeNeedField"> <source>Anonymous type must contain at least one member.</source> <target state="translated">匿名类型必须至少包含一个成员。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeNameWithoutPeriod"> <source>Anonymous type member name must be preceded by a period.</source> <target state="translated">匿名类型成员名前面必须有一个句点。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeExpectedIdentifier"> <source>Identifier expected, preceded with a period.</source> <target state="translated">应为开头带有句点的标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyArgs2"> <source>Too many arguments to extension method '{0}' defined in '{1}'.</source> <target state="translated">对“{1}”中定义的扩展方法“{0}”而言,参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgAlsoOmitted3"> <source>Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument.</source> <target state="translated">“{2}”中定义的扩展方法中的“{1}”形参“{0}”已具有匹配的省略实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgUsedTwice3"> <source>Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument.</source> <target state="translated">“{2}”中定义的扩展方法“{1}”的形参“{0}”已具有匹配的实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamNotFound3"> <source>'{0}' is not a parameter of extension method '{1}' defined in '{2}'.</source> <target state="translated">“{0}”不是“{2}”中定义的扩展方法“{1}”的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedArgument3"> <source>Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'.</source> <target state="translated">没有为“{2}”中定义的扩展方法“{1}”的形参“{0}”指定实参。</target> <note /> </trans-unit> <trans-unit id="ERR_UnboundTypeParam3"> <source>Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred.</source> <target state="translated">无法推断“{2}”中定义的扩展方法“{1}”的类型参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TooFewGenericArguments2"> <source>Too few type arguments to extension method '{0}' defined in '{1}'.</source> <target state="translated">对“{1}”中定义的扩展方法“{0}”而言,类型参数太少。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyGenericArguments2"> <source>Too many type arguments to extension method '{0}' defined in '{1}'.</source> <target state="translated">对“{1}”中定义的扩展方法“{0}”而言,类型参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedInOrEq"> <source>'In' or '=' expected.</source> <target state="translated">'应为“In”或“=”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedQueryableSource"> <source>Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.</source> <target state="translated">类型“{0}”的表达式不可查询。请确保不缺少程序集引用和/或 LINQ 提供程序的命名空间导入。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryOperatorNotFound"> <source>Definition of method '{0}' is not accessible in this context.</source> <target state="translated">方法“{0}”的定义在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseOnErrorGotoWithClosure"> <source>Method cannot contain both a '{0}' statement and a definition of a variable that is used in a lambda or query expression.</source> <target state="translated">方法不能同时包含“{0}”语句以及在 lambda 或查询表达式中使用的变量的定义。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotGotoNonScopeBlocksWithClosure"> <source>'{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression.</source> <target state="translated">“{0}{1}”无效,因为“{2}”所在的范围定义一个用在 lambda 表达式或查询表达式中的变量。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftRestrictedTypeQuery"> <source>Instance of restricted type '{0}' cannot be used in a query expression.</source> <target state="translated">不能在查询表达式中使用受限类型“{0}”的实例。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryAnonymousTypeFieldNameInference"> <source>Range variable name can be inferred only from a simple or qualified name with no arguments.</source> <target state="translated">只能从不带参数的简单名或限定名中推断范围变量名。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryDuplicateAnonTypeMemberName1"> <source>Range variable '{0}' is already declared.</source> <target state="translated">已声明范围变量“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryAnonymousTypeDisallowsTypeChar"> <source>Type characters cannot be used in range variable declarations.</source> <target state="translated">在范围变量声明中不能使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyInClosure"> <source>'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.</source> <target state="translated">'在构造函数内的 lambda 表达式中,"ReadOnly" 变量不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ExprTreeNoMultiDimArrayCreation"> <source>Multi-dimensional array cannot be converted to an expression tree.</source> <target state="translated">多维数组无法转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_ExprTreeNoLateBind"> <source>Late binding operations cannot be converted to an expression tree.</source> <target state="translated">后期绑定操作无法转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedBy"> <source>'By' expected.</source> <target state="translated">'应为 "By"。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryInvalidControlVariableName1"> <source>Range variable name cannot match the name of a member of the 'Object' class.</source> <target state="translated">范围变量名无法与 "Object" 类的成员名匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIn"> <source>'In' expected.</source> <target state="translated">'应为“In”。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNameNotDeclared"> <source>Name '{0}' is either not declared or not in the current scope.</source> <target state="translated">名称“{0}”未声明或不在当前作用域中。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedFunctionArgumentNarrowing3"> <source>Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'.</source> <target state="translated">与参数“{0}”匹配的嵌套函数的返回类型从“{1}”收缩到“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonTypeFieldXMLNameInference"> <source>Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source> <target state="translated">无法根据不是有效 Visual Basic 标识符的 XML 标识符推断出匿名类型成员名称。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryAnonTypeFieldXMLNameInference"> <source>Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source> <target state="translated">无法根据不是有效 Visual Basic 标识符的 XML 标识符推断出范围变量名。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedInto"> <source>'Into' expected.</source> <target state="translated">'应为“Into”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharOnAggregation"> <source>Aggregate function name cannot be used with a type character.</source> <target state="translated">聚合函数名不能与类型字符一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedOn"> <source>'On' expected.</source> <target state="translated">'应为 "On"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEquals"> <source>'Equals' expected.</source> <target state="translated">'应为“Equals”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAnd"> <source>'And' expected.</source> <target state="translated">'应为 "And"。</target> <note /> </trans-unit> <trans-unit id="ERR_EqualsTypeMismatch"> <source>'Equals' cannot compare a value of type '{0}' with a value of type '{1}'.</source> <target state="translated">'“Equals”不能对类型为“{0}”的值与类型“{1}”的值进行比较。</target> <note /> </trans-unit> <trans-unit id="ERR_EqualsOperandIsBad"> <source>You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) {0} must appear on one side of the 'Equals' operator, and range variable(s) {1} must appear on the other.</source> <target state="translated">“Equals”运算符的每一侧都必须至少引用一个范围变量。范围变量 {0} 必须出现在“Equals”运算符的一侧,范围变量 {1} 必须出现在另一侧。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNotDelegate1"> <source>Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source> <target state="translated">Lambda 表达式无法转换为“{0}”,因为“{0}”不是委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNotCreatableDelegate1"> <source>Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source> <target state="translated">Lambda 表达式无法转换为“{0}”,因为类型“{0}”被声明为“MustInherit”,无法创建。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotInferNullableForVariable1"> <source>A nullable type cannot be inferred for variable '{0}'.</source> <target state="translated">对于变量“{0}”不能推断可以为 null 的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableTypeInferenceNotSupported"> <source>Nullable type inference is not supported in this context.</source> <target state="translated">在该上下文中不支持可以为 null 的类型推理。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedJoin"> <source>'Join' expected.</source> <target state="translated">'应为“Join”。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableParameterMustSpecifyType"> <source>Nullable parameters must specify a type.</source> <target state="translated">可以为 null 的参数必须指定一个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_IterationVariableShadowLocal2"> <source>Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source> <target state="translated">范围变量“{0}”隐藏封闭块中的某个变量、以前定义的某个范围变量或者在查询表达式中隐式声明的某个变量。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdasCannotHaveAttributes"> <source>Attributes cannot be applied to parameters of lambda expressions.</source> <target state="translated">特性不能应用于 lambda 表达式的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaInSelectCaseExpr"> <source>Lambda expressions are not valid in the first expression of a 'Select Case' statement.</source> <target state="translated">Lambda 表达式在 "Select Case" 语句的第一个表达式中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfInSelectCaseExpr"> <source>'AddressOf' expressions are not valid in the first expression of a 'Select Case' statement.</source> <target state="translated">'“AddressOf”表达式在“Select Case”语句的第一个表达式中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableCharNotSupported"> <source>The '?' character cannot be used here.</source> <target state="translated">此处不能使用 "?" 字符。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftStructureMeLambda"> <source>Instance members and 'Me' cannot be used within a lambda expression in structures.</source> <target state="translated">无法在结构中的 lambda 表达式内使用实例成员和“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftByRefParamLambda1"> <source>'ByRef' parameter '{0}' cannot be used in a lambda expression.</source> <target state="translated">'不能在 lambda 表达式中使用“ByRef”参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftRestrictedTypeLambda"> <source>Instance of restricted type '{0}' cannot be used in a lambda expression.</source> <target state="translated">不能在 lambda 表达式中使用受限类型“{0}”的实例。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaParamShadowLocal1"> <source>Lambda parameter '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source> <target state="translated">Lambda 参数“{0}”隐藏封闭块中的某个变量、以前定义的某个范围变量或者在查询表达式中隐式声明的某个变量。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowImplicitObjectLambda"> <source>Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.</source> <target state="translated">Option Strict On 要求使用 "As" 子句来声明其类型无法推断的每个 lambda 表达式参数。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyParamsOnLambdaParamNoType"> <source>Array modifiers cannot be specified on lambda expression parameter name. They must be specified on its type.</source> <target state="translated">不能在 lambda 表达式的参数名中指定数组修饰符。数组修饰符必须在其类型中指定。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailure1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断类型形参的数据类型。显式指定该数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailure2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailure3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicit1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments.</source> <target state="translated">无法从这些实参推断类型形参的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicit2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicit3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureAmbiguous1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为可能会存在多个类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureAmbiguous2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为可能会存在多个类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureAmbiguous3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断“{0}”中定义的扩展方法“{1}”中类型形参的数据类型,因为可能会存在多个类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为可能会存在多个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为可能会存在多个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible.</source> <target state="translated">无法从这些实参推断“{0}”中定义的扩展方法“{1}”中类型形参的数据类型,因为可能会存在多个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoBest1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为这些数据类型不会转换为同一类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoBest2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoBest3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为这些数据类型不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingMismatchStrictOff2"> <source>Option Strict On does not allow narrowing in implicit type conversions between method '{0}' and delegate '{1}'.</source> <target state="translated">Option Strict On 不允许对方法“{0}”和委托“{1}”之间的隐式类型转换进行收缩。</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleReturnTypeOfMember2"> <source>'{0}' is not accessible in this context because the return type is not accessible.</source> <target state="translated">“{0}”是不可访问的返回类型,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIdentifierOrGroup"> <source>'Group' or an identifier expected.</source> <target state="translated">'应为“Group”或标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedGroup"> <source>'Group' not allowed in this context; identifier expected.</source> <target state="translated">'此上下文中不允许 "Group";应为标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingMismatchStrictOff3"> <source>Option Strict On does not allow narrowing in implicit type conversions between extension method '{0}' defined in '{2}' and delegate '{1}'.</source> <target state="translated">Option Strict On 不允许对“{2}”中定义的扩展方法“{0}”和委托“{1}”之间的隐式类型转换进行收缩。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingIncompatible3"> <source>Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'.</source> <target state="translated">“{2}”中定义的扩展方法“{0}”没有与委托“{1}”兼容的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentNarrowing2"> <source>Argument matching parameter '{0}' narrows to '{1}'.</source> <target state="translated">与形参“{0}”匹配的实参收缩到“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadCandidate1"> <source> {0}</source> <target state="translated"> {0}</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyInitializedInStructure"> <source>Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.</source> <target state="translated">如果没有将结构中包含的自动实现的属性标记为 "Shared",这些属性就不能有初始值设定项。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeDisallowsElements"> <source>XML elements cannot be selected from type '{0}'.</source> <target state="translated">XML 元素不能从类型“{0}”中选择。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeDisallowsAttributes"> <source>XML attributes cannot be selected from type '{0}'.</source> <target state="translated">XML 特性不能从类型“{0}”中选择。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeDisallowsDescendants"> <source>XML descendant elements cannot be selected from type '{0}'.</source> <target state="translated">XML 子代元素不能从类型“{0}”中选择。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOrMemberNotGeneric2"> <source>Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments.</source> <target state="translated">“{1}”中定义的扩展方法“{0}”不是泛型方法(或没有可用的类型形参),因此无法拥有类型实参。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodCannotBeLateBound"> <source>Late-bound extension methods are not supported.</source> <target state="translated">不支持后期绑定的扩展方法。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceArrayRankMismatch1"> <source>Cannot infer a data type for '{0}' because the array dimensions do not match.</source> <target state="translated">无法推断“{0}”的数据类型,因为数组维数不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryStrictDisallowImplicitObject"> <source>Type of the range variable cannot be inferred, and late binding is not allowed with Option Strict on. Use an 'As' clause to specify the type.</source> <target state="translated">无法推断范围变量的类型,且 Option Strict on 不允许后期绑定。请使用“As”子句来指定类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotEmbedInterfaceWithGeneric"> <source>Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.</source> <target state="translated">无法嵌入类型“{0}”,因为它有泛型参数。请考虑禁用互操作类型嵌入。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseGenericTypeAcrossAssemblyBoundaries"> <source>Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source> <target state="translated">无法跨程序集边界使用类型“{0}”,因为它有身为嵌入的互操作类型的泛型类型参数。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbol2"> <source>'{0}' is obsolete: '{1}'.</source> <target state="translated">“{0}”已过时:“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbol2_Title"> <source>Type or member is obsolete</source> <target state="translated">类型或成员已过时</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverloadBase4"> <source>{0} '{1}' shadows an overloadable member declared in the base {2} '{3}'. If you want to overload the base method, this method must be declared 'Overloads'.</source> <target state="translated">{0}“{1}”隐藏在基 {2}“{3}”中声明的可重载的成员。如果要重载基方法,则此方法必须声明为“Overloads”。</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverloadBase4_Title"> <source>Member shadows an overloadable member declared in the base type</source> <target state="translated">成员隐藏在基类型中声明的可重载的成员</target> <note /> </trans-unit> <trans-unit id="WRN_OverrideType5"> <source>{0} '{1}' conflicts with {2} '{1}' in the base {3} '{4}' and should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”与基 {3}“{4}”中的 {2}“{1}”冲突,应该声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_OverrideType5_Title"> <source>Member conflicts with member in the base type and should be declared 'Shadows'</source> <target state="translated">成员与基类型中的成员发生冲突,因此应声明为 "Shadows"</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverride2"> <source>{0} '{1}' shadows an overridable method in the base {2} '{3}'. To override the base method, this method must be declared 'Overrides'.</source> <target state="translated">{0}“{1}”隐藏基 {2}“{3}”中的可重写方法。若要重写基方法,必须将此方法声明为“Overrides”。</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverride2_Title"> <source>Member shadows an overridable method in the base type</source> <target state="translated">成员隐藏基类型中的可重写的方法</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultnessShadowed4"> <source>Default property '{0}' conflicts with the default property '{1}' in the base {2} '{3}'. '{0}' will be the default property. '{0}' should be declared 'Shadows'.</source> <target state="translated">默认属性“{0}”与基 {2}“{3}”中的默认属性“{1}”冲突。“{0}”将成为默认属性。“{0}”应声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultnessShadowed4_Title"> <source>Default property conflicts with the default property in the base type</source> <target state="translated">默认属性与基类型中的默认属性发生冲突</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1"> <source>'{0}' is obsolete.</source> <target state="translated">“{0}”已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1_Title"> <source>Type or member is obsolete</source> <target state="translated">类型或成员已过时</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration0"> <source>Possible problem detected while building assembly: {0}</source> <target state="translated">生成程序集时检测到可能存在的问题: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration0_Title"> <source>Possible problem detected while building assembly</source> <target state="translated">生成程序集时检测到可能的问题</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration1"> <source>Possible problem detected while building assembly '{0}': {1}</source> <target state="translated">生成程序集“{0}”时检测到可能存在的问题: {1}</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration1_Title"> <source>Possible problem detected while building assembly</source> <target state="translated">生成程序集时检测到可能的问题</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassNoMembers1"> <source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class '{0}' but '{0}' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.</source> <target state="translated">'为类“{0}”指定了“Microsoft.VisualBasic.ComClassAttribute”,但“{0}”没有可以向 COM 公开的公共成员;因此不生成 COM 接口。</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassNoMembers1_Title"> <source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class but class has no public members that can be exposed to COM</source> <target state="translated">'为类指定了 "Microsoft.VisualBasic.ComClassAttribute",但类没有可向 COM 公开的公共成员</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsMember5"> <source>{0} '{1}' implicitly declares '{2}', which conflicts with a member in the base {3} '{4}', and so the {0} should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”隐式声明的“{2}”与基 {3}“{4}”中的成员冲突,因此应将 {0} 声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsMember5_Title"> <source>Property or event implicitly declares type or member that conflicts with a member in the base type</source> <target state="translated">属性或事件隐式声明与基类型中的成员发生冲突的类型或成员</target> <note /> </trans-unit> <trans-unit id="WRN_MemberShadowsSynthMember6"> <source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in the base {4} '{5}' and should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”与为基 {4}“{5}”中 {2}“{3}”隐式声明的成员冲突,应将它声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_MemberShadowsSynthMember6_Title"> <source>Member conflicts with a member implicitly declared for property or event in the base type</source> <target state="translated">成员与为基类型中的属性或事件隐式声明的成员冲突</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsSynthMember7"> <source>{0} '{1}' implicitly declares '{2}', which conflicts with a member implicitly declared for {3} '{4}' in the base {5} '{6}'. {0} should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”隐式声明的“{2}”与为基 {5}“{6}”中的 {3}“{4}”隐式声明的成员冲突。{0} 应声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsSynthMember7_Title"> <source>Property or event implicitly declares member, which conflicts with a member implicitly declared for property or event in the base type</source> <target state="translated">属性或事件隐式声明与为基类型中的属性或事件隐式声明的成员发生冲突的成员</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor3"> <source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source> <target state="translated">“{1}”的“{0}”访问器已过时:“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor3_Title"> <source>Property accessor is obsolete</source> <target state="translated">属性访问器已过时</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor2"> <source>'{0}' accessor of '{1}' is obsolete.</source> <target state="translated">“{1}”的“{0}”访问器已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor2_Title"> <source>Property accessor is obsolete</source> <target state="translated">属性访问器已过时</target> <note /> </trans-unit> <trans-unit id="WRN_FieldNotCLSCompliant1"> <source>Type of member '{0}' is not CLS-compliant.</source> <target state="translated">成员“{0}”的类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_FieldNotCLSCompliant1_Title"> <source>Type of member is not CLS-compliant</source> <target state="translated">成员的类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_BaseClassNotCLSCompliant2"> <source>'{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant.</source> <target state="translated">“{0}”不符合 CLS,因为它是从不符合 CLS 的“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_BaseClassNotCLSCompliant2_Title"> <source>Type is not CLS-compliant because it derives from base type that is not CLS-compliant</source> <target state="translated">类型不符合 CLS,原因是它从不符合 CLS 的基类型派生</target> <note /> </trans-unit> <trans-unit id="WRN_ProcTypeNotCLSCompliant1"> <source>Return type of function '{0}' is not CLS-compliant.</source> <target state="translated">函数“{0}”的返回类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_ProcTypeNotCLSCompliant1_Title"> <source>Return type of function is not CLS-compliant</source> <target state="translated">函数的返回类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_ParamNotCLSCompliant1"> <source>Type of parameter '{0}' is not CLS-compliant.</source> <target state="translated">参数“{0}”的类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_ParamNotCLSCompliant1_Title"> <source>Type of parameter is not CLS-compliant</source> <target state="translated">参数的类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2"> <source>'{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant.</source> <target state="translated">“{0}”不符合 CLS,因为它所继承的接口“{1}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2_Title"> <source>Type is not CLS-compliant because the interface it inherits from is not CLS-compliant</source> <target state="translated">类型不符合 CLS,原因是它继承自的接口不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_CLSMemberInNonCLSType3"> <source>{0} '{1}' cannot be marked CLS-compliant because its containing type '{2}' is not CLS-compliant.</source> <target state="translated">{0}“{1}”不能被标记为符合 CLS,因为它的包含类型“{2}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_CLSMemberInNonCLSType3_Title"> <source>Member cannot be marked CLS-compliant because its containing type is not CLS-compliant</source> <target state="translated">无法将成员标记为符合 CLS,原因是它的包含类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_NameNotCLSCompliant1"> <source>Name '{0}' is not CLS-compliant.</source> <target state="translated">名称“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_NameNotCLSCompliant1_Title"> <source>Name is not CLS-compliant</source> <target state="translated">名称不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_EnumUnderlyingTypeNotCLS1"> <source>Underlying type '{0}' of Enum is not CLS-compliant.</source> <target state="translated">枚举的基础类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_EnumUnderlyingTypeNotCLS1_Title"> <source>Underlying type of Enum is not CLS-compliant</source> <target state="translated">枚举的基础类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMemberInCLSInterface1"> <source>Non CLS-compliant '{0}' is not allowed in a CLS-compliant interface.</source> <target state="translated">在符合 CLS 的接口中不允许出现不符合 CLS 的“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMemberInCLSInterface1_Title"> <source>Non CLS-compliant member is not allowed in a CLS-compliant interface</source> <target state="translated">在符合 CLS 的接口中不允许出现不符合 CLS 的成员</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMustOverrideInCLSType1"> <source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type '{0}'.</source> <target state="translated">在符合 CLS 的类型“{0}”中不允许出现不符合 CLS 的 "MustOverride" 成员。</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMustOverrideInCLSType1_Title"> <source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type</source> <target state="translated">在符合 CLS 的类型中不允许出现不符合 CLS 的 "Mustoverride" 成员</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayOverloadsNonCLS2"> <source>'{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types.</source> <target state="translated">“{0}”不符合 CLS,因为它重载仅在数组参数类型的数组或数组参数类型的秩方面与它不同的“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayOverloadsNonCLS2_Title"> <source>Method is not CLS-compliant because it overloads method which differs from it only by array of array parameter types or by the rank of the array parameter types</source> <target state="translated">方法不符合 CLS,因为它重载仅在数组参数类型的数组或数组参数类型的秩方面与它不同的方法</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant1"> <source>Root namespace '{0}' is not CLS-compliant.</source> <target state="translated">根命名空间“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant1_Title"> <source>Root namespace is not CLS-compliant</source> <target state="translated">根命名空间不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant2"> <source>Name '{0}' in the root namespace '{1}' is not CLS-compliant.</source> <target state="translated">根命名空间“{1}”中的名称“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant2_Title"> <source>Part of the root namespace is not CLS-compliant</source> <target state="translated">根命名空间的一部分不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_GenericConstraintNotCLSCompliant1"> <source>Generic parameter constraint type '{0}' is not CLS-compliant.</source> <target state="translated">泛型形参约束类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_GenericConstraintNotCLSCompliant1_Title"> <source>Generic parameter constraint type is not CLS-compliant</source> <target state="translated">泛型参数约束类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_TypeNotCLSCompliant1"> <source>Type '{0}' is not CLS-compliant.</source> <target state="translated">类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_TypeNotCLSCompliant1_Title"> <source>Type is not CLS-compliant</source> <target state="translated">类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_OptionalValueNotCLSCompliant1"> <source>Type of optional value for optional parameter '{0}' is not CLS-compliant.</source> <target state="translated">可选参数“{0}”的可选值的类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_OptionalValueNotCLSCompliant1_Title"> <source>Type of optional value for optional parameter is not CLS-compliant</source> <target state="translated">可选参数的可选值类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_CLSAttrInvalidOnGetSet"> <source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.</source> <target state="translated">System.CLSCompliantAttribute 不能应用于属性 "Get" 或 "Set"。</target> <note /> </trans-unit> <trans-unit id="WRN_CLSAttrInvalidOnGetSet_Title"> <source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'</source> <target state="translated">System.CLSCompliantAttribute 不能应用于属性 "Get" 或 "Set"</target> <note /> </trans-unit> <trans-unit id="WRN_TypeConflictButMerged6"> <source>{0} '{1}' and partial {2} '{3}' conflict in {4} '{5}', but are being merged because one of them is declared partial.</source> <target state="translated">{0}“{1}”和分部 {2}“{3}”在 {4}“{5}”中冲突,但由于其中的一个被声明为 Partial,因此正在合并。</target> <note /> </trans-unit> <trans-unit id="WRN_TypeConflictButMerged6_Title"> <source>Type and partial type conflict, but are being merged because one of them is declared partial</source> <target state="translated">类型和分部类型冲突,但由于其中一个被声明为 Partial,因此正在合并</target> <note /> </trans-unit> <trans-unit id="WRN_ShadowingGenericParamWithParam1"> <source>Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.</source> <target state="translated">类型参数“{0}”与封闭类型的类型参数同名。封闭类型的类型参数将被隐藏。</target> <note /> </trans-unit> <trans-unit id="WRN_ShadowingGenericParamWithParam1_Title"> <source>Type parameter has the same name as a type parameter of an enclosing type</source> <target state="translated">类型参数与封闭类型的类型参数具有相同的名称</target> <note /> </trans-unit> <trans-unit id="WRN_CannotFindStandardLibrary1"> <source>Could not find standard library '{0}'.</source> <target state="translated">未能找到标准库“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_CannotFindStandardLibrary1_Title"> <source>Could not find standard library</source> <target state="translated">找不到标准库</target> <note /> </trans-unit> <trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2"> <source>Delegate type '{0}' of event '{1}' is not CLS-compliant.</source> <target state="translated">事件“{1}”的委托类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2_Title"> <source>Delegate type of event is not CLS-compliant</source> <target state="translated">事件的委托类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties"> <source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate.</source> <target state="translated">System.Diagnostics.DebuggerHiddenAttribute 在应用于属性定义时不影响“Get”或“Set”。请根据相应的情况,将此特性直接应用于“Get”和“Set”过程。</target> <note /> </trans-unit> <trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties_Title"> <source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition</source> <target state="translated">在应用到属性定义时,System.Diagnostics.DebuggerHiddenAttribute 不影响 "Get" 或 "Set"</target> <note /> </trans-unit> <trans-unit id="WRN_SelectCaseInvalidRange"> <source>Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound.</source> <target state="translated">为 "Case" 语句指定的范围无效。请确保下限小于或等于上限。</target> <note /> </trans-unit> <trans-unit id="WRN_SelectCaseInvalidRange_Title"> <source>Range specified for 'Case' statement is not valid</source> <target state="translated">为 "Case" 语句指定的范围无效</target> <note /> </trans-unit> <trans-unit id="WRN_CLSEventMethodInNonCLSType3"> <source>'{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant.</source> <target state="translated">'事件“{1}”的“{0}”方法不能被标记为符合 CLS,因为它的包含类型“{2}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_CLSEventMethodInNonCLSType3_Title"> <source>AddHandler or RemoveHandler method for event cannot be marked CLS compliant because its containing type is not CLS compliant</source> <target state="translated">事件的 AddHandler 方法或 RemoveHandler 方法无法标记为符合 CLS,原因是它的包含类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_ExpectedInitComponentCall2"> <source>'{0}' in designer-generated type '{1}' should call InitializeComponent method.</source> <target state="translated">'设计器生成的类型“{1}”中的“{0}”应调用 InitializeComponent 方法。</target> <note /> </trans-unit> <trans-unit id="WRN_ExpectedInitComponentCall2_Title"> <source>Constructor in designer-generated type should call InitializeComponent method</source> <target state="translated">设计器生成的类型中的构造函数应调用 InitializeComponent 方法</target> <note /> </trans-unit> <trans-unit id="WRN_NamespaceCaseMismatch3"> <source>Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'.</source> <target state="translated">命名空间名“{0}”的大小写与“{2}”中命名空间名“{1}”的大小写不匹配。</target> <note /> </trans-unit> <trans-unit id="WRN_NamespaceCaseMismatch3_Title"> <source>Casing of namespace name does not match</source> <target state="translated">命名空间名称的大小写不匹配</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1"> <source>Namespace or type specified in the Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source> <target state="translated">Imports“{0}”中指定的命名空间或类型不包含任何公共成员,或者找不到该命名空间或类型。确保定义了该命名空间或类型且其中至少包含一个公共成员。确保导入的元素名不使用任何别名。</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1_Title"> <source>Namespace or type specified in Imports statement doesn't contain any public member or cannot be found</source> <target state="translated">在 Imports 语句中指定的命名空间或类型不包含任何公共成员或找不到公共成员</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1"> <source>Namespace or type specified in the project-level Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source> <target state="translated">项目级 Imports“{0}”中指定的命名空间或类型不包含任何公共成员,或者找不到公共成员。要确保定义了该命名空间或类型且其中至少包含一个公共成员;还要确保导入的元素名不使用任何别名。</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1_Title"> <source>Namespace or type imported at project level doesn't contain any public member or cannot be found</source> <target state="translated">在项目级别导入的命名空间或类型不包含任何公共成员或找不到公共成员</target> <note /> </trans-unit> <trans-unit id="WRN_IndirectRefToLinkedAssembly2"> <source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly from assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source> <target state="translated">已创建对嵌入的互操作程序集“{0}”的引用,因为程序集“{1}”间接引用了该程序集。请考虑更改其中一个程序集的“嵌入互操作类型”属性。</target> <note /> </trans-unit> <trans-unit id="WRN_IndirectRefToLinkedAssembly2_Title"> <source>A reference was created to embedded interop assembly because of an indirect reference to that assembly</source> <target state="translated">已创建对嵌入的互操作程序集的引用,因为间接引用了该程序集</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase3"> <source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source> <target state="translated">类“{0}”应该声明一个“Sub New”,因为其基类“{2}”中的“{1}”被标记为已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase3_Title"> <source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source> <target state="translated">类应声明 "Sub New",原因是它的基类中的构造函数被标记为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase4"> <source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source> <target state="translated">类“{0}”应该声明一个“Sub New”,因为其基类“{2}”中的“{1}”被标记为已过时:“{3}”。</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase4_Title"> <source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source> <target state="translated">类应声明 "Sub New",原因是它的基类中的构造函数被标记为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall3"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source> <target state="translated">此“Sub New”中的第一条语句应为对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标记为已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall3_Title"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source> <target state="translated">此 "Sub New" 的第一条语句必须是对 "MyBase.New" 或 "MyClass.New" 的显式调用,原因是基类中的构造函数被标为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall4"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'</source> <target state="translated">此“Sub New”中的第一条语句应为对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标记为已过时:“{3}”</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall4_Title"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source> <target state="translated">此 "Sub New" 的第一条语句必须是对 "MyBase.New" 或 "MyClass.New" 的显式调用,原因是基类中的构造函数被标为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinOperator"> <source>Operator without an 'As' clause; type of Object assumed.</source> <target state="translated">运算符没有 "As" 子句;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinOperator_Title"> <source>Operator without an 'As' clause</source> <target state="translated">运算符没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_ConstraintsFailedForInferredArgs2"> <source>Type arguments inferred for method '{0}' result in the following warnings :{1}</source> <target state="translated">为方法“{0}”推断的类型参数导致以下警告:{1}</target> <note /> </trans-unit> <trans-unit id="WRN_ConstraintsFailedForInferredArgs2_Title"> <source>Type arguments inferred for method result in warnings</source> <target state="translated">为方法推断的类型参数导致警告</target> <note /> </trans-unit> <trans-unit id="WRN_ConditionalNotValidOnFunction"> <source>Attribute 'Conditional' is only valid on 'Sub' declarations.</source> <target state="translated">特性 "Conditional" 只在 "Sub" 声明中有效。</target> <note /> </trans-unit> <trans-unit id="WRN_ConditionalNotValidOnFunction_Title"> <source>Attribute 'Conditional' is only valid on 'Sub' declarations</source> <target state="translated">特性 "Conditional" 只在 "Sub" 声明中有效</target> <note /> </trans-unit> <trans-unit id="WRN_UseSwitchInsteadOfAttribute"> <source>Use command-line option '{0}' or appropriate project settings instead of '{1}'.</source> <target state="translated">请使用命令行选项“{0}”或适当的项目设置,而不是“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UseSwitchInsteadOfAttribute_Title"> <source>Use command-line option /keyfile, /keycontainer, or /delaysign instead of AssemblyKeyFileAttribute, AssemblyKeyNameAttribute, or AssemblyDelaySignAttribute</source> <target state="translated">使用命令行选项 /keyfile、/keycontainer 或 /delaysign,而不要使用 AssemblyKeyFileAttribute、AssemblyKeyNameAttribute 或 AssemblyDelaySignAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveAddHandlerCall"> <source>Statement recursively calls the containing '{0}' for event '{1}'.</source> <target state="translated">语句以递归方式调用事件“{1}”的包含“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveAddHandlerCall_Title"> <source>Statement recursively calls the event's containing AddHandler</source> <target state="translated">语句递归调用事件包含的 AddHandler</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionCopyBack"> <source>Implicit conversion from '{1}' to '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source> <target state="translated">将“ByRef”形参“{0}”的值复制回匹配实参时,发生从“{1}”到“{2}”的隐式转换。</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionCopyBack_Title"> <source>Implicit conversion in copying the value of 'ByRef' parameter back to the matching argument</source> <target state="translated">在把 "ByRef" 参数的值复制回匹配参数的过程中进行隐式转换</target> <note /> </trans-unit> <trans-unit id="WRN_MustShadowOnMultipleInheritance2"> <source>{0} '{1}' conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”与继承层次结构中的其他同名成员冲突,因此应声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_MustShadowOnMultipleInheritance2_Title"> <source>Method conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'</source> <target state="translated">方法与继承层次结构中的其他同名成员冲突,因此应声明为 "Shadows"</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveOperatorCall"> <source>Expression recursively calls the containing Operator '{0}'.</source> <target state="translated">表达式以递归方式调用包含运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveOperatorCall_Title"> <source>Expression recursively calls the containing Operator</source> <target state="translated">表达式递归调用包含运算符</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversion2"> <source>Implicit conversion from '{0}' to '{1}'.</source> <target state="translated">从“{0}”到“{1}”的隐式转换。</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversion2_Title"> <source>Implicit conversion</source> <target state="translated">隐式转换</target> <note /> </trans-unit> <trans-unit id="WRN_MutableStructureInUsing"> <source>Local variable '{0}' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source> <target state="translated">局部变量“{0}”是只读的并且其类型是结构。调用此变量的成员或通过 ByRef 传递它不会更改其内容,并可能导致意外的错误。考虑在“Using”块之外声明此变量。</target> <note /> </trans-unit> <trans-unit id="WRN_MutableStructureInUsing_Title"> <source>Local variable declared by Using statement is read-only and its type is a structure</source> <target state="translated">Using 语句声明的局部变量是只读的,它的类型是一种结构</target> <note /> </trans-unit> <trans-unit id="WRN_MutableGenericStructureInUsing"> <source>Local variable '{0}' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source> <target state="translated">局部变量“{0}”是只读的。其类型为结构时,调用其成员或使用 ByRef 传递该类型不会更改其内容,并可能会导致意外的结果。考虑在“Using”块之外声明此变量。</target> <note /> </trans-unit> <trans-unit id="WRN_MutableGenericStructureInUsing_Title"> <source>Local variable declared by Using statement is read-only and its type may be a structure</source> <target state="translated">Using 语句声明的局部变量是只读的,它的类型可能是一种结构</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionSubst1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionSubst1_Title"> <source>Implicit conversion</source> <target state="translated">隐式转换</target> <note /> </trans-unit> <trans-unit id="WRN_LateBindingResolution"> <source>Late bound resolution; runtime errors could occur.</source> <target state="translated">后期绑定解决方案;可能会发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_LateBindingResolution_Title"> <source>Late bound resolution</source> <target state="translated">后期绑定解决方案</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1"> <source>Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity.</source> <target state="translated">对运算符“{0}”使用了 Object 类型的操作数;应使用“Is”运算符来测试对象标识。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1_Title"> <source>Operands of type Object used for operator</source> <target state="translated">为运算符使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath2"> <source>Operands of type Object used for operator '{0}'; runtime errors could occur.</source> <target state="translated">对运算符“{0}”使用了 Object 类型的操作数;可能会发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath2_Title"> <source>Operands of type Object used for operator</source> <target state="translated">为运算符使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedVar1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedVar1_Title"> <source>Variable declaration without an 'As' clause</source> <target state="translated">变量声明没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumed1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumed1_Title"> <source>Function without an 'As' clause</source> <target state="translated">函数没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedProperty1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedProperty1_Title"> <source>Property without an 'As' clause</source> <target state="translated">属性没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinVarDecl"> <source>Variable declaration without an 'As' clause; type of Object assumed.</source> <target state="translated">变量声明没有 "As" 子句;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinVarDecl_Title"> <source>Variable declaration without an 'As' clause</source> <target state="translated">变量声明没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinFunction"> <source>Function without an 'As' clause; return type of Object assumed.</source> <target state="translated">函数没有 "As" 子句;假定返回类型为 Object。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinFunction_Title"> <source>Function without an 'As' clause</source> <target state="translated">函数没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinProperty"> <source>Property without an 'As' clause; type of Object assumed.</source> <target state="translated">属性没有 "As" 子句;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinProperty_Title"> <source>Property without an 'As' clause</source> <target state="translated">属性没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocal"> <source>Unused local variable: '{0}'.</source> <target state="translated">未使用的局部变量:“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocal_Title"> <source>Unused local variable</source> <target state="translated">未使用的本地变量</target> <note /> </trans-unit> <trans-unit id="WRN_SharedMemberThroughInstance"> <source>Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.</source> <target state="translated">通过实例访问共享成员、常量成员、枚举成员或嵌套类型;将不计算限定表达式。</target> <note /> </trans-unit> <trans-unit id="WRN_SharedMemberThroughInstance_Title"> <source>Access of shared member, constant member, enum member or nested type through an instance</source> <target state="translated">通过实例访问共享成员、常量成员、枚举成员或嵌套类型</target> <note /> </trans-unit> <trans-unit id="WRN_RecursivePropertyCall"> <source>Expression recursively calls the containing property '{0}'.</source> <target state="translated">表达式递归调用包含属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RecursivePropertyCall_Title"> <source>Expression recursively calls the containing property</source> <target state="translated">表达式递归调用包含属性</target> <note /> </trans-unit> <trans-unit id="WRN_OverlappingCatch"> <source>'Catch' block never reached, because '{0}' inherits from '{1}'.</source> <target state="translated">'永远不会到达“Catch”块,因为“{0}”从“{1}”继承。</target> <note /> </trans-unit> <trans-unit id="WRN_OverlappingCatch_Title"> <source>'Catch' block never reached; exception type's base type handled above in the same Try statement</source> <target state="translated">'永远不会到达 "Catch" 块;异常类型的基类型已在上面同一个 Try 语句中处理</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRef"> <source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime.</source> <target state="translated">变量“{0}”在赋值前通过引用传递。可能会在运行时导致 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRef_Title"> <source>Variable is passed by reference before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已通过引用传递</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateCatch"> <source>'Catch' block never reached; '{0}' handled above in the same Try statement.</source> <target state="translated">'永远不会到达“Catch”块;“{0}”已在上面同一个 Try 语句中处理。</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateCatch_Title"> <source>'Catch' block never reached; exception type handled above in the same Try statement</source> <target state="translated">'永远不会到达 "Catch" 块;异常类型已在上面同一个 Try 语句中处理</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1Not"> <source>Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity.</source> <target state="translated">对运算符“{0}”使用了 Object 类型的操作数;应使用“IsNot”运算符来测试对象标识。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1Not_Title"> <source>Operands of type Object used for operator &lt;&gt;</source> <target state="translated">为运算符 &lt;&gt; 使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_BadChecksumValExtChecksum"> <source>Bad checksum value, non hex digits or odd number of hex digits.</source> <target state="translated">错误的校验和值、非十六进制数字或奇数个十六进制数字。</target> <note /> </trans-unit> <trans-unit id="WRN_BadChecksumValExtChecksum_Title"> <source>Bad checksum value, non hex digits or odd number of hex digits</source> <target state="translated">错误的校验和值、非十六进制数字或奇数个十六进制数字</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleDeclFileExtChecksum"> <source>File name already declared with a different GUID and checksum value.</source> <target state="translated">已使用另一个 GUID 和校验和值声明了文件名。</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleDeclFileExtChecksum_Title"> <source>File name already declared with a different GUID and checksum value</source> <target state="translated">已使用另一个 GUID 和校验和值声明了文件名</target> <note /> </trans-unit> <trans-unit id="WRN_BadGUIDFormatExtChecksum"> <source>Bad GUID format.</source> <target state="translated">错误的 GUID 格式。</target> <note /> </trans-unit> <trans-unit id="WRN_BadGUIDFormatExtChecksum_Title"> <source>Bad GUID format</source> <target state="translated">错误的 GUID 格式</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMathSelectCase"> <source>Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur.</source> <target state="translated">在 "Select"、"Case" 语句的表达式中使用了 Object 类型的操作数;可能会发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMathSelectCase_Title"> <source>Operands of type Object used in expressions for 'Select', 'Case' statements</source> <target state="translated">"Select"、"Case" 语句的表达式中使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_EqualToLiteralNothing"> <source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.</source> <target state="translated">此表达式的计算结果始终为 Nothing (由于来自等于运算符的 null 传播)。若要检查值是否为 null,请考虑使用 "Is Nothing"。</target> <note /> </trans-unit> <trans-unit id="WRN_EqualToLiteralNothing_Title"> <source>This expression will always evaluate to Nothing</source> <target state="translated">此表达式的计算结果始终为 Nothing</target> <note /> </trans-unit> <trans-unit id="WRN_NotEqualToLiteralNothing"> <source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'.</source> <target state="translated">此表达式的计算结果始终为 Nothing (由于来自等于运算符的 null 传播)。若要检查值是否不为 null,请考虑使用 "IsNot Nothing"。</target> <note /> </trans-unit> <trans-unit id="WRN_NotEqualToLiteralNothing_Title"> <source>This expression will always evaluate to Nothing</source> <target state="translated">此表达式的计算结果始终为 Nothing</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocalConst"> <source>Unused local constant: '{0}'.</source> <target state="translated">未使用的局部常量:“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocalConst_Title"> <source>Unused local constant</source> <target state="translated">未使用的局部常量</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassInterfaceShadows5"> <source>'Microsoft.VisualBasic.ComClassAttribute' on class '{0}' implicitly declares {1} '{2}', which conflicts with a member of the same name in {3} '{4}'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base {4}.</source> <target state="translated">'类“{0}”上的“Microsoft.VisualBasic.ComClassAttribute”隐式声明的 {1}“{2}”与 {3}“{4}”中的同名成员冲突。如果要隐藏基 {4} 上的名称,请使用“Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)”。</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassInterfaceShadows5_Title"> <source>'Microsoft.VisualBasic.ComClassAttribute' on class implicitly declares member, which conflicts with a member of the same name</source> <target state="translated">'类上的 "Microsoft.VisualBasic.ComClassAttribute" 隐式声明与同名成员发生冲突的成员</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassPropertySetObject1"> <source>'{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.</source> <target state="translated">“{0}”无法作为属性“Let”向 COM 公开。将无法使用“Let”语句从 Visual Basic 6.0 向该属性分配非对象值(如数字或字符串)。</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassPropertySetObject1_Title"> <source>Property cannot be exposed to COM as a property 'Let'</source> <target state="translated">无法将属性作为 "Let" 属性向 COM 公开</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRef"> <source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime.</source> <target state="translated">变量“{0}”在赋值前被使用。可能会在运行时导致 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRef_Title"> <source>Variable is used before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已被使用</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncRef1"> <source>Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source> <target state="translated">函数“{0}”不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncRef1_Title"> <source>Function doesn't return a value on all code paths</source> <target state="translated">函数没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpRef1"> <source>Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source> <target state="translated">运算符“{0}”不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpRef1_Title"> <source>Operator doesn't return a value on all code paths</source> <target state="translated">运算符没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropRef1"> <source>Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source> <target state="translated">属性“{0}”不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropRef1_Title"> <source>Property doesn't return a value on all code paths</source> <target state="translated">属性没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRefStr"> <source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source> <target state="translated">变量“{0}”在赋值前通过引用传递。可能会在运行时导致 null 引用异常。请确保结构或所有引用成员在使用前已经初始化</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRefStr_Title"> <source>Variable is passed by reference before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已通过引用传递</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefStr"> <source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source> <target state="translated">变量“{0}”在赋值前被使用。可能会在运行时导致 null 引用异常。请确保结构或所有引用成员在使用前已经初始化</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefStr_Title"> <source>Variable is used before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已被使用</target> <note /> </trans-unit> <trans-unit id="WRN_StaticLocalNoInference"> <source>Static variable declared without an 'As' clause; type of Object assumed.</source> <target state="translated">未使用 "As" 子句声明的静态变量;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_StaticLocalNoInference_Title"> <source>Static variable declared without an 'As' clause</source> <target state="translated">声明静态变量时未使用 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName"> <source>Assembly reference '{0}' is invalid and cannot be resolved.</source> <target state="translated">程序集引用“{0}”无效,无法解析。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName_Title"> <source>Assembly reference is invalid and cannot be resolved</source> <target state="translated">程序集引用无效,无法解析</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadXMLLine"> <source>XML comment block must immediately precede the language element to which it applies. XML comment will be ignored.</source> <target state="translated">XML 注释块必须紧挨着它应用于的语言元素的前面。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadXMLLine_Title"> <source>XML comment block must immediately precede the language element to which it applies</source> <target state="translated">XML 注释块必须紧跟它所应用于的语言元素</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocMoreThanOneCommentBlock"> <source>Only one XML comment block is allowed per language element.</source> <target state="translated">每个语言元素只能有一个 XML 注释块。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocMoreThanOneCommentBlock_Title"> <source>Only one XML comment block is allowed per language element</source> <target state="translated">每个语言元素只能有一个 XML 注释块</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocNotFirstOnLine"> <source>XML comment must be the first statement on a line. XML comment will be ignored.</source> <target state="translated">XML 注释必须是一行中的第一条语句。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocNotFirstOnLine_Title"> <source>XML comment must be the first statement on a line</source> <target state="translated">XML 注释必须是一行上的第一条语句</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInsideMethod"> <source>XML comment cannot appear within a method or a property. XML comment will be ignored.</source> <target state="translated">XML 注释不能在方法或属性内出现。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInsideMethod_Title"> <source>XML comment cannot appear within a method or a property</source> <target state="translated">XML 注释不能在方法或属性内出现</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParseError1"> <source>XML documentation parse error: {0} XML comment will be ignored.</source> <target state="translated">XML 文档分析错误: {0} XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParseError1_Title"> <source>XML documentation parse error</source> <target state="translated">XML 文档分析错误</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocDuplicateXMLNode1"> <source>XML comment tag '{0}' appears with identical attributes more than once in the same XML comment block.</source> <target state="translated">具有相同特性的 XML 注释标记“{0}”在同一 XML 注释块中出现多次。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocDuplicateXMLNode1_Title"> <source>XML comment tag appears with identical attributes more than once in the same XML comment block</source> <target state="translated">具有相同属性的 XML 注释标记在同一个 XML 注释块中出现多次</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocIllegalTagOnElement2"> <source>XML comment tag '{0}' is not permitted on a '{1}' language element.</source> <target state="translated">“{1}”语言元素中不允许 XML 注释标记“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocIllegalTagOnElement2_Title"> <source>XML comment tag is not permitted on language element</source> <target state="translated">语言元素中不允许出现 XML 注释标记</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadParamTag2"> <source>XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement.</source> <target state="translated">XML 注释参数“{0}”和相应的“{1}”语句的参数不匹配。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadParamTag2_Title"> <source>XML comment parameter does not match a parameter on the corresponding declaration statement</source> <target state="translated">XML 注释参数与相应的声明语句上的参数不匹配</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParamTagWithoutName"> <source>XML comment parameter must have a 'name' attribute.</source> <target state="translated">XML 注释参数必须具有 "name" 属性。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParamTagWithoutName_Title"> <source>XML comment parameter must have a 'name' attribute</source> <target state="translated">XML 注释参数必须具有 "name" 属性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefAttributeNotFound1"> <source>XML comment has a tag with a 'cref' attribute '{0}' that could not be resolved.</source> <target state="translated">XML 注释中的一个标记具有未能解析的“cref”特性“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefAttributeNotFound1_Title"> <source>XML comment has a tag with a 'cref' attribute that could not be resolved</source> <target state="translated">XML 注释包含具有无法解析的 "cref" 属性的标记</target> <note /> </trans-unit> <trans-unit id="WRN_XMLMissingFileOrPathAttribute1"> <source>XML comment tag 'include' must have a '{0}' attribute. XML comment will be ignored.</source> <target state="translated">XML 注释标记“include”必须具有“{0}”特性。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLMissingFileOrPathAttribute1_Title"> <source>XML comment tag 'include' must have 'file' and 'path' attributes</source> <target state="translated">XML 注释标记 "include" 必须具有 "file" 和 "path" 特性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLCannotWriteToXMLDocFile2"> <source>Unable to create XML documentation file '{0}': {1}</source> <target state="translated">无法创建 XML 文档文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLCannotWriteToXMLDocFile2_Title"> <source>Unable to create XML documentation file</source> <target state="translated">无法创建 XML 文档文件</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocWithoutLanguageElement"> <source>XML documentation comments must precede member or type declarations.</source> <target state="translated">XML 文档注释必须位于成员声明或类型声明之前。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocWithoutLanguageElement_Title"> <source>XML documentation comments must precede member or type declarations</source> <target state="translated">XML 文档注释必须位于成员声明或类型声明之前</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty"> <source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.</source> <target state="translated">WriteOnly 属性中不允许有 XML 注释标记 "returns"。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty_Title"> <source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property</source> <target state="translated">"WriteOnly" 属性中不允许出现 XML 注释标记 "returns"</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocOnAPartialType"> <source>XML comment cannot be applied more than once on a partial {0}. XML comments for this {0} will be ignored.</source> <target state="translated">XML 注释在分部 {0} 中不能应用多次。此 {0} 的 XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocOnAPartialType_Title"> <source>XML comment cannot be applied more than once on a partial type</source> <target state="translated">XML 注释无法在一个分部类型上应用多次</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnADeclareSub"> <source>XML comment tag 'returns' is not permitted on a 'declare sub' language element.</source> <target state="translated">declare sub 语言元素中不允许有 XML 注释标记 "returns"。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnADeclareSub_Title"> <source>XML comment tag 'returns' is not permitted on a 'declare sub' language element</source> <target state="translated">"declare sub" 语言元素中不允许出现 XML 注释标记 "returns"</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocStartTagWithNoEndTag"> <source>XML documentation parse error: Start tag '{0}' doesn't have a matching end tag. XML comment will be ignored.</source> <target state="translated">XML 文档分析错误: 开始标记“{0}”没有匹配的结束标记。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocStartTagWithNoEndTag_Title"> <source>XML documentation parse error: Start tag doesn't have a matching end tag</source> <target state="translated">XML 文档分析错误: 开始标记没有匹配的结束标记</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadGenericParamTag2"> <source>XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement.</source> <target state="translated">XML 注释类型参数“{0}”和相应的“{1}”语句的类型参数不匹配。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadGenericParamTag2_Title"> <source>XML comment type parameter does not match a type parameter on the corresponding declaration statement</source> <target state="translated">XML 注释类型参数与相应的声明语句上的类型参数不匹配</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocGenericParamTagWithoutName"> <source>XML comment type parameter must have a 'name' attribute.</source> <target state="translated">XML 注释类型参数必须具有 "name" 属性。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocGenericParamTagWithoutName_Title"> <source>XML comment type parameter must have a 'name' attribute</source> <target state="translated">XML 注释类型参数必须具有 "name" 属性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocExceptionTagWithoutCRef"> <source>XML comment exception must have a 'cref' attribute.</source> <target state="translated">XML 注释异常必须具有 "cref" 属性。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocExceptionTagWithoutCRef_Title"> <source>XML comment exception must have a 'cref' attribute</source> <target state="translated">XML 注释异常必须具有 "cref" 属性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInvalidXMLFragment"> <source>Unable to include XML fragment '{0}' of file '{1}'.</source> <target state="translated">无法包括文件“{1}”的 XML 段落“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInvalidXMLFragment_Title"> <source>Unable to include XML fragment</source> <target state="translated">无法包括 XML 段落</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadFormedXML"> <source>Unable to include XML fragment '{1}' of file '{0}'. {2}</source> <target state="translated">无法包括文件“{0}”的 XML 段落“{1}”。{2}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadFormedXML_Title"> <source>Unable to include XML fragment</source> <target state="translated">无法包括 XML 段落</target> <note /> </trans-unit> <trans-unit id="WRN_InterfaceConversion2"> <source>Runtime errors might occur when converting '{0}' to '{1}'.</source> <target state="translated">将“{0}”转换为“{1}”时可能发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_InterfaceConversion2_Title"> <source>Runtime errors might occur when converting to or from interface type</source> <target state="translated">运行时错误可能在转换到或从接口类型转换时发生</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableLambda"> <source>Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source> <target state="translated">在 lambda 表达式中使用迭代变量可能会产生意外的结果。应改为在循环中创建一个局部变量并将迭代变量的值赋给它。</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableLambda_Title"> <source>Using the iteration variable in a lambda expression may have unexpected results</source> <target state="translated">在 lambda 表达式中使用迭代变量可能会产生意外的结果</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaPassedToRemoveHandler"> <source>Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.</source> <target state="translated">Lambda 表达式将不会从此事件处理程序中移除。将 lambda 表达式赋给变量,并使用该变量添加和移除事件。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaPassedToRemoveHandler_Title"> <source>Lambda expression will not be removed from this event handler</source> <target state="translated">Lambda 表达式将不会从此事件处理程序中删除</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableQuery"> <source>Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source> <target state="translated">在查询表达式中使用迭代变量可能会产生意外的结果。应改为在循环中创建一个局部变量并将迭代变量的值赋给它。</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableQuery_Title"> <source>Using the iteration variable in a query expression may have unexpected results</source> <target state="translated">在查询表达式中使用迭代变量可能会产生意外的结果</target> <note /> </trans-unit> <trans-unit id="WRN_RelDelegatePassedToRemoveHandler"> <source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler.</source> <target state="translated">"AddressOf" 表达式在此上下文中不起作用,因为 "AddressOf" 的方法参数需要到该事件的委托类型的宽松转换。将 "AddressOf' 表达式赋给变量,并使用变量将该方法作为处理程序进行添加或移除。</target> <note /> </trans-unit> <trans-unit id="WRN_RelDelegatePassedToRemoveHandler_Title"> <source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event</source> <target state="translated">"AddressOf" 表达式在此上下文中不起作用,原因是 "AddressOf" 的方法参数需要到该事件的委托类型的宽松转换</target> <note /> </trans-unit> <trans-unit id="WRN_QueryMissingAsClauseinVarDecl"> <source>Range variable is assumed to be of type Object because its type cannot be inferred. Use an 'As' clause to specify a different type.</source> <target state="translated">假定范围变量属于对象类型,因为无法推断其类型。请使用“As”子句指定不同类型。</target> <note /> </trans-unit> <trans-unit id="WRN_QueryMissingAsClauseinVarDecl_Title"> <source>Range variable is assumed to be of type Object because its type cannot be inferred</source> <target state="translated">范围变量被假设为 Object 类型,原因是无法推断它的类型</target> <note /> </trans-unit> <trans-unit id="ERR_MultilineLambdaMissingFunction"> <source>Multiline lambda expression is missing 'End Function'.</source> <target state="translated">多行 lambda 表达式缺少 "End Function"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultilineLambdaMissingSub"> <source>Multiline lambda expression is missing 'End Sub'.</source> <target state="translated">多行 lambda 表达式缺少 "End Sub"。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeOnLambdaReturnType"> <source>Attributes cannot be applied to return types of lambda expressions.</source> <target state="translated">特性不能应用于 lambda 表达式的返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_SubDisallowsStatement"> <source>Statement is not valid inside a single-line statement lambda.</source> <target state="translated">该语句在单行语句 lambda 中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresParenthesesBang"> <source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() &lt;statement&gt;)!key</source> <target state="translated">此单行语句 lambda 必须括在括号中。例如: (Sub() &lt;语句&gt;)!key</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresParenthesesDot"> <source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() &lt;statement&gt;).Invoke()</source> <target state="translated">此单行语句 lambda 必须括在括号中。例如: (Sub() &lt;语句&gt;).Invoke()</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresParenthesesLParen"> <source>This single-line statement lambda must be enclosed in parentheses. For example: Call (Sub() &lt;statement&gt;) ()</source> <target state="translated">此单行语句 lambda 必须括在括号中。例如: Call (Sub() &lt;语句&gt;) ()</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresSingleStatement"> <source>Single-line statement lambdas must include exactly one statement.</source> <target state="translated">单行语句 lambda 必须仅包含一个语句。</target> <note /> </trans-unit> <trans-unit id="ERR_StaticInLambda"> <source>Static local variables cannot be declared inside lambda expressions.</source> <target state="translated">无法在 lambda 表达式内声明静态局部变量。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializedExpandedProperty"> <source>Expanded Properties cannot be initialized.</source> <target state="translated">无法初始化扩展属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyCantHaveParams"> <source>Auto-implemented properties cannot have parameters.</source> <target state="translated">自动实现的属性不能带有参数。</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyCantBeWriteOnly"> <source>Auto-implemented properties cannot be WriteOnly.</source> <target state="translated">自动实现的属性不能为 WriteOnly。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFCount"> <source>'If' operator requires either two or three operands.</source> <target state="translated">'“If”运算符需要两个或三个操作数。</target> <note /> </trans-unit> <trans-unit id="ERR_NotACollection1"> <source>Cannot initialize the type '{0}' with a collection initializer because it is not a collection type.</source> <target state="translated">无法用集合初始值设定项初始化类型“{0}”,因为该类型不是集合类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAddMethod1"> <source>Cannot initialize the type '{0}' with a collection initializer because it does not have an accessible 'Add' method.</source> <target state="translated">无法用集合初始值设定项初始化类型“{0}”,因为该类型没有可访问的“Add”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_CantCombineInitializers"> <source>An Object Initializer and a Collection Initializer cannot be combined in the same initialization.</source> <target state="translated">不能将对象初始值设定项与集合初始值设定项组合到同一个初始化过程中。</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyAggregateInitializer"> <source>An aggregate collection initializer entry must contain at least one element.</source> <target state="translated">聚合集合初始值设定项必须至少包含一个元素。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlEndElementNoMatchingStart"> <source>XML end element must be preceded by a matching start element.</source> <target state="translated">XML 结束元素前面必须是匹配的开始元素。</target> <note /> </trans-unit> <trans-unit id="ERR_MultilineLambdasCannotContainOnError"> <source>'On Error' and 'Resume' cannot appear inside a lambda expression.</source> <target state="translated">'“On Error”和“Resume”不能出现在 lambda 表达式内。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceDisallowedHere"> <source>Keywords 'Out' and 'In' can only be used in interface and delegate declarations.</source> <target state="translated">关键字 "Out" 和 "In" 只能在接口声明和委托声明中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlEndCDataNotAllowedInContent"> <source>The literal string ']]&gt;' is not allowed in element content.</source> <target state="translated">元素内容中不允许使用字符串“]]&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadsModifierInModule"> <source>Inappropriate use of '{0}' keyword in a module.</source> <target state="translated">模块中不恰当地使用了“{0}”关键字。</target> <note /> </trans-unit> <trans-unit id="ERR_UndefinedTypeOrNamespace1"> <source>Type or namespace '{0}' is not defined.</source> <target state="translated">未定义类型或命名空间“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_IdentityDirectCastForFloat"> <source>Using DirectCast operator to cast a floating-point value to the same type is not supported.</source> <target state="translated">不支持使用 DirectCast 运算符将浮点值强制转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType"> <source>Using DirectCast operator to cast a value-type to the same type is obsolete.</source> <target state="translated">使用 DirectCast 运算符将值类型强制转换为同一类型的做法已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType_Title"> <source>Using DirectCast operator to cast a value-type to the same type is obsolete</source> <target state="translated">使用 DirectCast 运算符将值类型强制转换为同一类型的做法已过时</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode"> <source>Unreachable code detected.</source> <target state="translated">检测到无法访问的代码。</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode_Title"> <source>Unreachable code detected</source> <target state="translated">检测到无法访问的代码</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncVal1"> <source>Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">函数“{0}”不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncVal1_Title"> <source>Function doesn't return a value on all code paths</source> <target state="translated">函数没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpVal1"> <source>Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">运算符“{0}”不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpVal1_Title"> <source>Operator doesn't return a value on all code paths</source> <target state="translated">运算符没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropVal1"> <source>Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">属性“{0}”不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropVal1_Title"> <source>Property doesn't return a value on all code paths</source> <target state="translated">属性没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="ERR_NestedGlobalNamespace"> <source>Global namespace may not be nested in another namespace.</source> <target state="translated">全局命名空间不能嵌套在另一个命名空间中。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatch6"> <source>'{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'.</source> <target state="translated">“{0}”不能通过 {4}“{5}”在 {2}“{3}”中公开类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadMetaDataReference1"> <source>'{0}' cannot be referenced because it is not a valid assembly.</source> <target state="translated">“{0}”不是有效程序集,因此无法引用它。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyDoesntImplementAllAccessors"> <source>'{0}' cannot be implemented by a {1} property.</source> <target state="translated">“{0}”无法由 {1} 属性实现。</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedMustOverride"> <source> {0}: {1}</source> <target state="translated"> {0}: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_IfTooManyTypesObjectDisallowed"> <source>Cannot infer a common type because more than one type is possible.</source> <target state="translated">无法推断通用类型,因为可能存在多个类型。</target> <note /> </trans-unit> <trans-unit id="WRN_IfTooManyTypesObjectAssumed"> <source>Cannot infer a common type because more than one type is possible; 'Object' assumed.</source> <target state="translated">无法推断通用类型,因为可能存在多个类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_IfTooManyTypesObjectAssumed_Title"> <source>Cannot infer a common type because more than one type is possible</source> <target state="translated">无法推断通用类型,原因是可能存在多个类型</target> <note /> </trans-unit> <trans-unit id="ERR_IfNoTypeObjectDisallowed"> <source>Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.</source> <target state="translated">无法推断通用类型,且 Option Strict On 不允许假定“Object”。</target> <note /> </trans-unit> <trans-unit id="WRN_IfNoTypeObjectAssumed"> <source>Cannot infer a common type; 'Object' assumed.</source> <target state="translated">无法推断通用类型;假定为“Object”。</target> <note /> </trans-unit> <trans-unit id="WRN_IfNoTypeObjectAssumed_Title"> <source>Cannot infer a common type</source> <target state="translated">无法推断通用类型</target> <note /> </trans-unit> <trans-unit id="ERR_IfNoType"> <source>Cannot infer a common type.</source> <target state="translated">无法推断通用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyFileFailure"> <source>Error extracting public key from file '{0}': {1}</source> <target state="translated">从文件“{0}”中提取公钥时出错: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyContainerFailure"> <source>Error extracting public key from container '{0}': {1}</source> <target state="translated">从容器“{0}”中提取公钥时出错: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefNotEqualToThis"> <source>Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</source> <target state="translated">友元访问权限由“{0}”授予,但是输出程序集的公钥与授予程序集中特性指定的公钥不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefSigningMismatch"> <source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source> <target state="translated">友元访问权限由“{0}”授予,但是输出程序集的强名称签名状态与授予程序集的强名称签名状态不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignNoKey"> <source>Public sign was specified and requires a public key, but no public key was specified</source> <target state="translated">已指定公共符号并且它需要一个公钥,但未指定任何公钥</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignNetModule"> <source>Public signing is not supported for netmodules.</source> <target state="translated">netmodule 不支持公共签名。</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning"> <source>Attribute '{0}' is ignored when public signing is specified.</source> <target state="translated">指定公共签名时,将忽略特性“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title"> <source>Attribute is ignored when public signing is specified.</source> <target state="translated">指定公共签名时,将忽略特性。</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey"> <source>Delay signing was specified and requires a public key, but no public key was specified.</source> <target state="translated">指定了延迟签名,这需要公钥,但是未指定任何公钥。</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey_Title"> <source>Delay signing was specified and requires a public key, but no public key was specified</source> <target state="translated">指定了延迟签名,这需要公钥,但是未指定任何公钥</target> <note /> </trans-unit> <trans-unit id="ERR_SignButNoPrivateKey"> <source>Key file '{0}' is missing the private key needed for signing.</source> <target state="translated">密钥文件“{0}”缺少进行签名所需的私钥。</target> <note /> </trans-unit> <trans-unit id="ERR_FailureSigningAssembly"> <source>Error signing assembly '{0}': {1}</source> <target state="translated">对程序集“{0}”签名时出错: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat"> <source>The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]]</source> <target state="translated">指定的版本字符串不符合所需格式 - major[.minor[.build|*[.revision|*]]]</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">指定版本字符串不符合建议格式 - major.minor.build.revision</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat_Title"> <source>The specified version string does not conform to the recommended format</source> <target state="translated">指定的版本字符串不符合建议的格式</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat2"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">指定版本字符串不符合建议格式 - major.minor.build.revision</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCultureForExe"> <source>Executables cannot be satellite assemblies; culture should always be empty</source> <target state="translated">可执行文件不能是附属程序集;区域性应始终为空</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored"> <source>The entry point of the program is global script code; ignoring '{0}' entry point.</source> <target state="translated">程序的入口点是全局脚本代码;正在忽略“{0}”入口点。</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored_Title"> <source>The entry point of the program is global script code; ignoring entry point</source> <target state="translated">程序的入口点是全局脚本代码;正在忽略入口点</target> <note /> </trans-unit> <trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName"> <source>The xmlns attribute has special meaning and should not be written with a prefix.</source> <target state="translated">xmlns 特性具有特殊含义,不应使用前缀进行编写。</target> <note /> </trans-unit> <trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName_Title"> <source>The xmlns attribute has special meaning and should not be written with a prefix</source> <target state="translated">xmlns 特性具有特殊含义,不应使用前缀进行编写</target> <note /> </trans-unit> <trans-unit id="WRN_PrefixAndXmlnsLocalName"> <source>It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:{0}' to define a prefix named '{0}'?</source> <target state="translated">建议不要将特性命名为 xmlns。是否有意编写“xmlns:{0}”以定义名为“{0}”的前缀?</target> <note /> </trans-unit> <trans-unit id="WRN_PrefixAndXmlnsLocalName_Title"> <source>It is not recommended to have attributes named xmlns</source> <target state="translated">不建议拥有名为 xmlns 的属性</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSingleScript"> <source>Expected a single script (.vbx file)</source> <target state="translated">需要一个脚本 (.vbx 文件)</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedAssemblyName"> <source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source> <target state="translated">程序集名“{0}”保留名称,不能在交互会话中用作引用</target> <note /> </trans-unit> <trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts"> <source>#R is only allowed in scripts</source> <target state="translated">仅在脚本中允许 #R</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotAllowedInScript"> <source>You cannot declare Namespace in script code</source> <target state="translated">不能在脚本代码中声明命名空间</target> <note /> </trans-unit> <trans-unit id="ERR_KeywordNotAllowedInScript"> <source>You cannot use '{0}' in top-level script code</source> <target state="translated">您不能使用顶级脚本代码中的“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNoType"> <source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source> <target state="translated">无法推断返回类型。请考虑添加一个“As”子句来指定返回类型。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaNoTypeObjectAssumed"> <source>Cannot infer a return type; 'Object' assumed.</source> <target state="translated">无法推断返回类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaNoTypeObjectAssumed_Title"> <source>Cannot infer a return type</source> <target state="translated">无法推断返回类型</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaTooManyTypesObjectAssumed"> <source>Cannot infer a return type because more than one type is possible; 'Object' assumed.</source> <target state="translated">无法推断返回类型,因为可能存在多个类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaTooManyTypesObjectAssumed_Title"> <source>Cannot infer a return type because more than one type is possible</source> <target state="translated">无法推断返回类型,原因是可能存在多个类型</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNoTypeObjectDisallowed"> <source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source> <target state="translated">无法推断返回类型。请考虑添加一个 "As" 子句来指定返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaTooManyTypesObjectDisallowed"> <source>Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.</source> <target state="translated">无法推断返回类型,因为可能存在多个类型。请考虑添加一个 "As" 子句来指定返回类型。</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch"> <source>The command line switch '{0}' is not yet implemented and was ignored.</source> <target state="translated">命令行开关“{0}”尚未实现,已忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch_Title"> <source>Command line switch is not yet implemented</source> <target state="translated">命令行开关尚未实现</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitNoTypeObjectDisallowed"> <source>Cannot infer an element type, and Option Strict On does not allow 'Object' to be assumed. Specifying the type of the array might correct this error.</source> <target state="translated">无法推断元素类型,且 Option Strict On 不允许假定 "Object"。指定数组的类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitNoType"> <source>Cannot infer an element type. Specifying the type of the array might correct this error.</source> <target state="translated">无法推断元素类型。指定数组的类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitTooManyTypesObjectDisallowed"> <source>Cannot infer an element type because more than one type is possible. Specifying the type of the array might correct this error.</source> <target state="translated">无法推断元素类型,因为可能存在多个类型。指定数组的类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitNoTypeObjectAssumed"> <source>Cannot infer an element type; 'Object' assumed.</source> <target state="translated">无法推断元素类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitNoTypeObjectAssumed_Title"> <source>Cannot infer an element type</source> <target state="translated">无法推断元素类型</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed"> <source>Cannot infer an element type because more than one type is possible; 'Object' assumed.</source> <target state="translated">无法推断元素类型,因为可能存在多个类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed_Title"> <source>Cannot infer an element type because more than one type is possible</source> <target state="translated">无法推断元素类型,原因是可能存在多个类型</target> <note /> </trans-unit> <trans-unit id="WRN_TypeInferenceAssumed3"> <source>Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed.</source> <target state="translated">未能推断“{1}”中“{0}”的数据类型。假定为“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_TypeInferenceAssumed3_Title"> <source>Data type could not be inferred</source> <target state="translated">无法推断数据类型</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousCastConversion2"> <source>Option Strict On does not allow implicit conversions from '{0}' to '{1}' because the conversion is ambiguous.</source> <target state="translated">Option Strict 不允许进行“{0}”到“{1}”的隐式转换,因为转换不明确。</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousCastConversion2"> <source>Conversion from '{0}' to '{1}' may be ambiguous.</source> <target state="translated">从“{0}”到“{1}”的转换可能不明确。</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousCastConversion2_Title"> <source>Conversion may be ambiguous</source> <target state="translated">转换可能不明确</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceIEnumerableSuggestion3"> <source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑改用“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceIEnumerableSuggestion3"> <source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑改用“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceIEnumerableSuggestion3_Title"> <source>Type cannot be converted to target collection type</source> <target state="translated">无法将类型转换为目标集合类型</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedIn6"> <source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source> <target state="translated">“{4}”不能转换为“{5}”,因为根据“{3}”中“In”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedOut6"> <source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source> <target state="translated">“{4}”不能转换为“{5}”,因为根据“{3}”中“Out”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedIn6"> <source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source> <target state="translated">从“{4}”到“{5}”的隐式转换;此转换可能失败,因为根据“{3}”中“In”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedIn6_Title"> <source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'In' generic parameter</source> <target state="translated">隐式转换;此转换可能失败,原因是目标类型不是从源类型派生的,而这是 "In" 泛型参数所必需的</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedOut6"> <source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source> <target state="translated">从“{4}”到“{5}”的隐式转换;此转换可能失败,因为根据“{3}”中“Out”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedOut6_Title"> <source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'Out' generic parameter</source> <target state="translated">隐式转换;此转换可能失败,原因是目标类型不是从源类型派生的,而这是 "Out" 泛型参数所必需的</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedTryIn4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedTryOut4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryIn4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryIn4_Title"> <source>Type cannot be converted to target type</source> <target state="translated">无法将类型转换为目标类型</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryOut4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryOut4_Title"> <source>Type cannot be converted to target type</source> <target state="translated">无法将类型转换为目标类型</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceDeclarationAmbiguous3"> <source>Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'.</source> <target state="translated">“{2}”中的“In”和“Out”参数导致接口“{0}”与另一个已实现的接口“{1}”一起使用时目的不明确。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceDeclarationAmbiguous3_Title"> <source>Interface is ambiguous with another implemented interface due to 'In' and 'Out' parameters</source> <target state="translated">接口对于另一个实现的接口不明确,原因在于 "In" 和 "Out" 参数</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInterfaceNesting"> <source>Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.</source> <target state="translated">无法在含有 "In" 或 "Out" 类型参数的接口中声明枚举、类和结构。</target> <note /> </trans-unit> <trans-unit id="ERR_VariancePreventsSynthesizedEvents2"> <source>Event definitions with parameters are not allowed in an interface such as '{0}' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within '{0}'. For example, 'Event {1} As Action(Of ...)'.</source> <target state="translated">在“{0}”这样的含有“In”或“Out”类型参数的接口中,不允许带参数的事件定义。考虑使用不在“{0}”中定义的委托类型来声明事件。例如,“Event {1} As Action(Of ...)”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInByRefDisallowed1"> <source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“In”和“Out”类型参数不能用于 ByRef 参数类型,且“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInNullableDisallowed2"> <source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用于“{1}”,因为“In”和“Out”类型参数不能设置为可以为 null,并且“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowed1"> <source>Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowedForGeneric3"> <source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{2}”中的“{1}”,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowedHere2"> <source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowedHereForGeneric4"> <source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”中“{3}”的“{2}”,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInPropertyDisallowed1"> <source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly.</source> <target state="translated">在此上下文中,类型“{0}”不能用作属性类型,因为“{0}”是“In”类型参数,且该属性未标记为 WriteOnly。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInReadOnlyPropertyDisallowed1"> <source>Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用作 ReadOnly 属性类型,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInReturnDisallowed1"> <source>Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用作返回类型,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutByRefDisallowed1"> <source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“In”和“Out”类型参数不能用于 ByRef 参数类型,且“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutByValDisallowed1"> <source>Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用作 ByVal 参数类型,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutConstraintDisallowed1"> <source>Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用作泛型类型约束,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutNullableDisallowed2"> <source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用于“{1}”,因为“In”和“Out”类型参数不能设置为可以为 null,并且“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowed1"> <source>Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowedForGeneric3"> <source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{2}”中的“{1}”,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowedHere2"> <source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowedHereForGeneric4"> <source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”中“{3}”的“{2}”,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutPropertyDisallowed1"> <source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly.</source> <target state="translated">在此上下文中,类型“{0}”不能用作属性类型,因为“{0}”是“Out”类型参数,且该属性未标记为 ReadOnly。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutWriteOnlyPropertyDisallowed1"> <source>Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用作 WriteOnly 属性类型,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowed2"> <source>Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能用于此上下文,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowedForGeneric4"> <source>Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能在此上下文中用于“{3}”中的“{2}”,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowedHere3"> <source>Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能在此上下文用于“{2}”,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowedHereForGeneric5"> <source>Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能在此上下文中用于“{2}”中“{4}”的“{3}”,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterNotValidForType"> <source>Parameter not valid for the specified unmanaged type.</source> <target state="translated">参数对于指定非托管类型无效。</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields"> <source>Unmanaged type '{0}' not valid for fields.</source> <target state="translated">非托管类型“{0}”对于字段无效。</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields"> <source>Unmanaged type '{0}' is only valid for fields.</source> <target state="translated">非托管类型“{0}”仅对字段有效。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired1"> <source>Attribute parameter '{0}' must be specified.</source> <target state="translated">必须指定特性参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired2"> <source>Attribute parameter '{0}' or '{1}' must be specified.</source> <target state="translated">必须指定特性参数“{0}”或“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_MemberConflictWithSynth4"> <source>Conflicts with '{0}', which is implicitly declared for '{1}' in {2} '{3}'.</source> <target state="translated">与为 {2}“{3}”中的“{1}”隐式声明的“{0}”冲突。</target> <note /> </trans-unit> <trans-unit id="IDS_ProjectSettingsLocationName"> <source>&lt;project settings&gt;</source> <target state="translated">&lt;项目设置&gt;</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty"> <source>Attributes applied on a return type of a WriteOnly Property have no effect.</source> <target state="translated">应用于 WriteOnly 属性的返回类型的特性不起作用。</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty_Title"> <source>Attributes applied on a return type of a WriteOnly Property have no effect</source> <target state="translated">应用于 WriteOnly 属性的返回类型的特性不起作用</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidTarget"> <source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source> <target state="translated">安全特性“{0}”对此声明类型无效。安全特性仅对程序集、类型和方法声明有效。</target> <note /> </trans-unit> <trans-unit id="ERR_AbsentReferenceToPIA1"> <source>Cannot find the interop type that matches the embedded type '{0}'. Are you missing an assembly reference?</source> <target state="translated">找不到与嵌入的类型“{0}”匹配的互操作类型。是否缺少程序集引用?</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLinkClassWithNoPIA1"> <source>Reference to class '{0}' is not allowed when its assembly is configured to embed interop types.</source> <target state="translated">当类“{0}”的程序集配置为嵌入互操作类型时,不允许使用对该类的引用。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidStructMemberNoPIA1"> <source>Embedded interop structure '{0}' can contain only public instance fields.</source> <target state="translated">嵌入的互操作结构“{0}”只能包含公共实例字段。</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIAAttributeMissing2"> <source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source> <target state="translated">无法嵌入互操作类型“{0}”,因为它缺少必需的“{1}”特性。</target> <note /> </trans-unit> <trans-unit id="ERR_PIAHasNoAssemblyGuid1"> <source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source> <target state="translated">无法嵌入来自程序集“{0}”的互操作类型,因为它缺少“{1}”特性。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLocalTypes3"> <source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider disabling the embedding of interop types.</source> <target state="translated">无法嵌入程序集“{1}”和“{2}”中找到的互操作类型“{0}”。请考虑禁用互操作类型的嵌入。</target> <note /> </trans-unit> <trans-unit id="ERR_PIAHasNoTypeLibAttribute1"> <source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source> <target state="translated">无法嵌入来自程序集“{0}”的互操作类型,因为它缺少“{1}”特性或“{2}”特性。</target> <note /> </trans-unit> <trans-unit id="ERR_SourceInterfaceMustBeInterface"> <source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source> <target state="translated">接口“{0}”的源接口无效,该源接口是嵌入事件“{1}”所必需的。</target> <note /> </trans-unit> <trans-unit id="ERR_EventNoPIANoBackingMember"> <source>Source interface '{0}' is missing method '{1}', which is required to embed event '{2}'.</source> <target state="translated">源接口“{0}”缺少方法“{2}”,此方法对嵌入事件“{1}”是必需的。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedInteropType"> <source>Nested type '{0}' cannot be embedded.</source> <target state="translated">无法嵌入嵌套类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalTypeNameClash2"> <source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types.</source> <target state="translated">嵌入来自程序集“{1}”中的互操作类型“{0}”会导致当前程序集中发生名称冲突。请考虑禁用互操作类型的嵌入。</target> <note /> </trans-unit> <trans-unit id="ERR_InteropMethodWithBody1"> <source>Embedded interop method '{0}' contains a body.</source> <target state="translated">嵌入互操作方法“{0}”包含主体。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncInQuery"> <source>'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.</source> <target state="translated">'"Await" 只能在初始 "From" 子句的第一个集合表达式或 "Join" 子句的集合表达式的查询表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_BadGetAwaiterMethod1"> <source>'Await' requires that the type '{0}' have a suitable GetAwaiter method.</source> <target state="translated">'“Await”要求类型“{0}”包含适当的 GetAwaiter 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_BadIsCompletedOnCompletedGetResult2"> <source>'Await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.</source> <target state="translated">'“Await”要求“{1}.GetAwaiter()”的返回类型“{0}”包含适当的 IsCompleted、OnCompleted 和 GetResult 成员,并实现 INotifyCompletion 或 ICriticalNotifyCompletion</target> <note /> </trans-unit> <trans-unit id="ERR_DoesntImplementAwaitInterface2"> <source>'{0}' does not implement '{1}'.</source> <target state="translated">“{0}”未实现“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitNothing"> <source>Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.</source> <target state="translated">不能等待 Nothing。请考虑改为等待“Task.Yield()”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncByRefParam"> <source>Async methods cannot have ByRef parameters.</source> <target state="translated">异步方法不能包含 ByRef 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAsyncIteratorModifiers"> <source>'Async' and 'Iterator' modifiers cannot be used together.</source> <target state="translated">'“Async”和“Iterator”修饰符不能一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_BadResumableAccessReturnVariable"> <source>The implicit return variable of an Iterator or Async method cannot be accessed.</source> <target state="translated">无法访问迭代器方法或异步方法的隐式返回变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnFromNonGenericTaskAsync"> <source>'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.</source> <target state="translated">'此异步方法中的 "Return" 语句无法返回值,因为函数的返回类型为 "Task" 。请考虑将函数的返回类型更改为 "Task(Of T)"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturnOperand1"> <source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task(Of {0})'.</source> <target state="translated">这是一个异步方法,因此返回表达式的类型必须为“{0}”而不是“Task(Of {0})”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturn"> <source>The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).</source> <target state="translated">只能在 Sub 上或者在返回 Task 或 Task(Of T) 的函数上使用 "Async" 修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_CantAwaitAsyncSub1"> <source>'{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function.</source> <target state="translated">“{0}”不返回 Task 且无法等待。请考虑将它更改为 Async Function。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidLambdaModifier"> <source>'Only the 'Async' or 'Iterator' modifier is valid on a lambda.</source> <target state="translated">'仅“Async”或“Iterator”修饰符在 lambda 上有效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInNonAsyncMethod"> <source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of {0})'.</source> <target state="translated">'“Await”只能在异步方法中使用。请考虑使用“Async”修饰符标记此方法,并将其返回类型更改为“Task(Of {0})”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInNonAsyncVoidMethod"> <source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.</source> <target state="translated">'“Await”只能用于异步方法中。请考虑用“Async”修饰符标记此方法,并将其返回类型更改为“Task”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInNonAsyncLambda"> <source>'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.</source> <target state="translated">'“Await”只能用于异步 lambda 表达式中。请考虑用“Async”修饰符标记此 lambda 表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitNotInAsyncMethodOrLambda"> <source>'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.</source> <target state="translated">'仅当其包含方法或 lambda 表达式用“Async”修饰符标记时,才能使用“Await”。</target> <note /> </trans-unit> <trans-unit id="ERR_StatementLambdaInExpressionTree"> <source>Statement lambdas cannot be converted to expression trees.</source> <target state="translated">语句 lambda 不能转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression"> <source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.</source> <target state="translated">由于此调用不会等待,因此在调用完成前将继续执行当前方法。请考虑对调用结果应用 Await 运算符。</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression_Title"> <source>Because this call is not awaited, execution of the current method continues before the call is completed</source> <target state="translated">由于此调用不会等待,因此在调用完成前将继续执行当前方法</target> <note /> </trans-unit> <trans-unit id="ERR_LoopControlMustNotAwait"> <source>Loop control variable cannot include an 'Await'.</source> <target state="translated">循环控制变量不可包含 "Await"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadStaticInitializerInResumable"> <source>Static variables cannot appear inside Async or Iterator methods.</source> <target state="translated">静态变量不能出现在异步方法或迭代器方法内。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedResumableType1"> <source>'{0}' cannot be used as a parameter type for an Iterator or Async method.</source> <target state="translated">“{0}”不能用作 Iterator 或 Async 方法的参数类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorAsync"> <source>Constructor must not have the 'Async' modifier.</source> <target state="translated">构造函数不得包含“Async”修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodsMustNotBeAsync1"> <source>'{0}' cannot be declared 'Partial' because it has the 'Async' modifier.</source> <target state="translated">“{0}”不能声明为“Partial”,因为它具有“Async”修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_ResumablesCannotContainOnError"> <source>'On Error' and 'Resume' cannot appear inside async or iterator methods.</source> <target state="translated">'"On Error" 和 "Resume" 不能出现在异步方法或迭代器方法内。</target> <note /> </trans-unit> <trans-unit id="ERR_ResumableLambdaInExpressionTree"> <source>Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.</source> <target state="translated">无法将带 "Async" 或 "Iterator" 修饰符的 lambda 转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftRestrictedTypeResumable1"> <source>Variable of restricted type '{0}' cannot be declared in an Async or Iterator method.</source> <target state="translated">不能在异步方法或迭代器方法中声明受限类型“{0}”的变量。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInTryHandler"> <source>'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.</source> <target state="translated">'不能在“Catch”语句、“Finally”语句或“SyncLock”语句内使用“Await”。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits"> <source>This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.</source> <target state="translated">此异步方法缺少 "Await" 运算符,因此它将同步运行。请考虑使用 "Await" 运算符等待非阻止 API 调用,或使用 "Await Task.Run(...)" 利用后台线程执行占用大量 CPU 的工作。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits_Title"> <source>This async method lacks 'Await' operators and so will run synchronously</source> <target state="translated">此异步方法缺少 "Await" 运算符,因此将以同步方式运行</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableDelegate"> <source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.</source> <target state="translated">从此 Async Function 返回的任务将被删除,并且忽略其中的任何异常。考虑将其更改为 Async Sub,以便传播其异常。</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableDelegate_Title"> <source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored</source> <target state="translated">自此 Async Function 返回的任务将被丢弃,它包含的任何异常也将被忽略</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalAsyncInClassOrStruct"> <source>Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source> <target state="translated">在具有“SecurityCritical”或“SecuritySafeCritical”属性的 [Class|Structure|Interface|Module] 中不允许使用 Async 或 Iterator 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalAsync"> <source>Security attribute '{0}' cannot be applied to an Async or Iterator method.</source> <target state="translated">安全属性“{0}”不能应用于 Async 或 Iterator 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnResumableMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于异步方法或迭代器方法。</target> <note /> </trans-unit> <trans-unit id="ERR_SynchronizedAsyncMethod"> <source>'MethodImplOptions.Synchronized' cannot be applied to an Async method.</source> <target state="translated">'"MethodImplOptions.Synchronized" 不能应用于异步方法。</target> <note /> </trans-unit> <trans-unit id="ERR_AsyncSubMain"> <source>The 'Main' method cannot be marked 'Async'.</source> <target state="translated">"Main" 方法不能标记为 "Async"。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncSubCouldBeFunction"> <source>Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.</source> <target state="translated">此处某些重载使用的是 Async Function 而不是 Async Sub。请考虑使用 Async Function 或将此 Async Sub 显式强制转换为所需类型。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncSubCouldBeFunction_Title"> <source>Some overloads here take an Async Function rather than an Async Sub</source> <target state="translated">此处的一些重载采用的是 Async Function,而不是 Async Sub</target> <note /> </trans-unit> <trans-unit id="ERR_MyGroupCollectionAttributeCycle"> <source>MyGroupCollectionAttribute cannot be applied to itself.</source> <target state="translated">MyGroupCollectionAttribute 不能应用于自身。</target> <note /> </trans-unit> <trans-unit id="ERR_LiteralExpected"> <source>Literal expected.</source> <target state="translated">应为文本。</target> <note /> </trans-unit> <trans-unit id="ERR_WinRTEventWithoutDelegate"> <source>Event declarations that target WinMD must specify a delegate type. Add an As clause to the event declaration.</source> <target state="translated">面向 WinMD 的事件声明必须指定委托类型。请在事件声明中添加一个 As 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_MixingWinRTAndNETEvents"> <source>Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}'</source> <target state="translated">事件“{0}”无法实现 Windows 运行时事件“{1}”和常规 .NET 事件“{2}”</target> <note /> </trans-unit> <trans-unit id="ERR_EventImplRemoveHandlerParamWrong"> <source>Event '{0}' cannot implement event '{1}' on interface '{2}' because the parameters of their 'RemoveHandler' methods do not match.</source> <target state="translated">事件“{0}”无法实现接口“{2}”上的事件“{1}”,因为其“RemoveHandler”方法的参数不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_AddParamWrongForWinRT"> <source>The type of the 'AddHandler' method's parameter must be the same as the type of the event.</source> <target state="translated">“AddHandler”方法的参数的类型必须与事件的类型相同。</target> <note /> </trans-unit> <trans-unit id="ERR_RemoveParamWrongForWinRT"> <source>In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken'</source> <target state="translated">在 Windows Runtime 事件中,“RemoveHandler”方法参数的类型必须为“EventRegistrationToken”</target> <note /> </trans-unit> <trans-unit id="ERR_ReImplementingWinRTInterface5"> <source>'{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed</source> <target state="translated">'“实现 {2}”中的“{0}.{1}”已由基类“{3}”实现。不允许重新实现 Windows Runtime 接口“{4}”</target> <note /> </trans-unit> <trans-unit id="ERR_ReImplementingWinRTInterface4"> <source>'{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed</source> <target state="translated">“{0}.{1}”已由基类“{2}”实现。不允许重新实现 Windows Runtime 接口“{3}”</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorByRefParam"> <source>Iterator methods cannot have ByRef parameters.</source> <target state="translated">迭代器方法不能包含 ByRef 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorExpressionLambda"> <source>Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.</source> <target state="translated">单行 lambda 不能包含“Iterator”修饰符。请改用多行 lambda。</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorReturn"> <source>Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.</source> <target state="translated">迭代器函数必须返回 IEnumerable(Of T) 或 IEnumerator(Of T),或返回非泛型格式的 IEnumerable 或 IEnumerator。</target> <note /> </trans-unit> <trans-unit id="ERR_BadReturnValueInIterator"> <source>To return a value from an Iterator function, use 'Yield' rather than 'Return'.</source> <target state="translated">若要从迭代器函数返回值,请使用“Yield”而不是“Return”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInNonIteratorMethod"> <source>'Yield' can only be used in a method marked with the 'Iterator' modifier.</source> <target state="translated">'只能在用“Iterator”修饰符标记的方法中使用“Yield”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInTryHandler"> <source>'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.</source> <target state="translated">'不能在“Catch”语句或“Finally”语句内使用“Yield”。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1"> <source>The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">Windows 运行时事件“{0}”的 AddHandler 不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1_Title"> <source>The AddHandler for Windows Runtime event doesn't return a value on all code paths</source> <target state="translated">Windows 运行时事件的 AddHandler 没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodDefaultParameterValueMismatch2"> <source>Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'.</source> <target state="translated">方法“{0}”的可选参数没有与分部方法“{1}”的相应参数相同的默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodParamArrayMismatch2"> <source>Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'.</source> <target state="translated">方法“{0}”的参数在分部方法“{1}”的相应参数的 ParamArray 修饰符上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMismatch"> <source>Module name '{0}' stored in '{1}' must match its filename.</source> <target state="translated">存储在“{1}”中的模块名“{0}”必须与其文件名匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleName"> <source>Invalid module name: {0}</source> <target state="translated">无效的模块名称: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden"> <source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source.</source> <target state="translated">来自模块“{1}”的特性“{0}”将忽略,以便支持源中出现的实例。</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title"> <source>Attribute from module will be ignored in favor of the instance appearing in source</source> <target state="translated">为支持源中出现的实例,将忽略模块的特性</target> <note /> </trans-unit> <trans-unit id="ERR_CmdOptionConflictsSource"> <source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source> <target state="translated">源文件中提供的特定“{0}”与选项“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName"> <source>Referenced assembly '{0}' does not have a strong name.</source> <target state="translated">引用程序集“{0}”没有强名称。</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title"> <source>Referenced assembly does not have a strong name</source> <target state="translated">引用程序集没有强名称</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSignaturePublicKey"> <source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source> <target state="translated">在 AssemblySignatureKeyAttribute 中指定的签名公钥无效。</target> <note /> </trans-unit> <trans-unit id="ERR_CollisionWithPublicTypeInModule"> <source>Type '{0}' conflicts with public type defined in added module '{1}'.</source> <target state="translated">类型“{0}”与添加的模块“{1}”中定义的公共类型冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypeConflictsWithDeclaration"> <source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">从模块“{1}”导出的类型“{0}”与此程序集主模块中声明的类型冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypesConflict"> <source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">从模块“{1}”导出的类型“{0}”与从模块“{3}”导出的类型“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch"> <source>Referenced assembly '{0}' has different culture setting of '{1}'.</source> <target state="translated">引用程序集“{0}”具有不同区域性设置“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch_Title"> <source>Referenced assembly has different culture setting</source> <target state="translated">引用程序集具有不同区域性设置</target> <note /> </trans-unit> <trans-unit id="ERR_AgnosticToMachineModule"> <source>Agnostic assembly cannot have a processor specific module '{0}'.</source> <target state="translated">不可知的程序集不能具有特定于处理器的模块“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingMachineModule"> <source>Assembly and module '{0}' cannot target different processors.</source> <target state="translated">程序集和模块“{0}”不能以不同处理器为目标。</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly"> <source>Referenced assembly '{0}' targets a different processor.</source> <target state="translated">引用程序集“{0}”面向的是另一个处理器。</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly_Title"> <source>Referenced assembly targets a different processor</source> <target state="translated">引用程序集面向的是另一个处理器</target> <note /> </trans-unit> <trans-unit id="ERR_CryptoHashFailed"> <source>Cryptographic failure while creating hashes.</source> <target state="translated">创建哈希时加密失败。</target> <note /> </trans-unit> <trans-unit id="ERR_CantHaveWin32ResAndManifest"> <source>Conflicting options specified: Win32 resource file; Win32 manifest.</source> <target state="translated">指定的选项冲突: Win32 资源文件;Win32 清单。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration"> <source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">转发的类型“{0}”与此程序集主模块中声明的类型冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypesConflict"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source> <target state="translated">转发到程序集“{1}”的类型“{0}”与转发到程序集“{3}”的类型“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_TooLongMetadataName"> <source>Name '{0}' exceeds the maximum length allowed in metadata.</source> <target state="translated">名称“{0}”超出元数据中允许的最大长度。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingNetModuleReference"> <source>Reference to '{0}' netmodule missing.</source> <target state="translated">缺少对“{0}”netmodule 的引用。</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMustBeUnique"> <source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source> <target state="translated">模块“{0}”已在此程序集中定义。每个模块必须具有唯一的文件名。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithExportedType"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">转发到程序集“{1}”的类型“{0}”与从模块“{3}”导出的类型“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="IDS_MSG_ADDREFERENCE"> <source>Adding assembly reference '{0}'</source> <target state="translated">正在添加程序集引用“{0}”</target> <note /> </trans-unit> <trans-unit id="IDS_MSG_ADDLINKREFERENCE"> <source>Adding embedded assembly reference '{0}'</source> <target state="translated">正在添加嵌入程序集引用“{0}”</target> <note /> </trans-unit> <trans-unit id="IDS_MSG_ADDMODULE"> <source>Adding module reference '{0}'</source> <target state="translated">正在添加模块引用“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_NestingViolatesCLS1"> <source>Type '{0}' does not inherit the generic type parameters of its container.</source> <target state="translated">类型“{0}”不继承其容器的泛型类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_PDBWritingFailed"> <source>Failure writing debug information: {0}</source> <target state="translated">写入调试信息失败: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute"> <source>The parameter has multiple distinct default values.</source> <target state="translated">参数具有多个不同的默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_FieldHasMultipleDistinctConstantValues"> <source>The field has multiple distinct constant values.</source> <target state="translated">字段具有多个不同的常量值。</target> <note /> </trans-unit> <trans-unit id="ERR_EncNoPIAReference"> <source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source> <target state="translated">无法继续,因为编辑包括对嵌入类型的引用:“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_EncReferenceToAddedMember"> <source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source> <target state="translated">在当前调试会话期间添加的成员“{0}”只能从其声明的程序集“{1}”中访问。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedModule1"> <source>'{0}' is an unsupported .NET module.</source> <target state="translated">“{0}”是不受支持的 .NET 模块。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedEvent1"> <source>'{0}' is an unsupported event.</source> <target state="translated">“{0}”是不受支持的事件。</target> <note /> </trans-unit> <trans-unit id="PropertiesCanNotHaveTypeArguments"> <source>Properties can not have type arguments</source> <target state="translated">属性不能具有类型参数</target> <note /> </trans-unit> <trans-unit id="IdentifierSyntaxNotWithinSyntaxTree"> <source>IdentifierSyntax not within syntax tree</source> <target state="translated">IdentifierSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="AnonymousObjectCreationExpressionSyntaxNotWithinTree"> <source>AnonymousObjectCreationExpressionSyntax not within syntax tree</source> <target state="translated">AnonymousObjectCreationExpressionSyntax 未在语法树内</target> <note /> </trans-unit> <trans-unit id="FieldInitializerSyntaxNotWithinSyntaxTree"> <source>FieldInitializerSyntax not within syntax tree</source> <target state="translated">FieldInitializerSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="IDS_TheSystemCannotFindThePathSpecified"> <source>The system cannot find the path specified</source> <target state="translated">系统无法找到指定路径</target> <note /> </trans-unit> <trans-unit id="ThereAreNoPointerTypesInVB"> <source>There are no pointer types in VB.</source> <target state="translated">VB 中没有任何指针属性。</target> <note /> </trans-unit> <trans-unit id="ThereIsNoDynamicTypeInVB"> <source>There is no dynamic type in VB.</source> <target state="translated">VB 中没有任何动态类型。</target> <note /> </trans-unit> <trans-unit id="VariableSyntaxNotWithinSyntaxTree"> <source>variableSyntax not within syntax tree</source> <target state="translated">variableSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="AggregateSyntaxNotWithinSyntaxTree"> <source>AggregateSyntax not within syntax tree</source> <target state="translated">AggregateSyntax 未在语法树内</target> <note /> </trans-unit> <trans-unit id="FunctionSyntaxNotWithinSyntaxTree"> <source>FunctionSyntax not within syntax tree</source> <target state="translated">FunctionSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="PositionIsNotWithinSyntax"> <source>Position is not within syntax tree</source> <target state="translated">位置不在语法树中</target> <note /> </trans-unit> <trans-unit id="RangeVariableSyntaxNotWithinSyntaxTree"> <source>RangeVariableSyntax not within syntax tree</source> <target state="translated">RangeVariableSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="DeclarationSyntaxNotWithinSyntaxTree"> <source>DeclarationSyntax not within syntax tree</source> <target state="translated">DeclarationSyntax 未在语法树内</target> <note /> </trans-unit> <trans-unit id="StatementOrExpressionIsNotAValidType"> <source>StatementOrExpression is not an ExecutableStatementSyntax or an ExpressionSyntax</source> <target state="translated">StatementOrExpression 不是 ExecutableStatementSyntax 或 ExpressionSyntax</target> <note /> </trans-unit> <trans-unit id="DeclarationSyntaxNotWithinTree"> <source>DeclarationSyntax not within tree</source> <target state="translated">DeclarationSyntax 未在树内</target> <note /> </trans-unit> <trans-unit id="TypeParameterNotWithinTree"> <source>TypeParameter not within tree</source> <target state="translated">TypeParameter 不在树中</target> <note /> </trans-unit> <trans-unit id="NotWithinTree"> <source> not within tree</source> <target state="translated"> 不在树中</target> <note /> </trans-unit> <trans-unit id="LocationMustBeProvided"> <source>Location must be provided in order to provide minimal type qualification.</source> <target state="translated">必须提供位置才能提供最低程度的类型限定。</target> <note /> </trans-unit> <trans-unit id="SemanticModelMustBeProvided"> <source>SemanticModel must be provided in order to provide minimal type qualification.</source> <target state="translated">必须提供 SemanticModel 才能提供最低程度的类型限定。</target> <note /> </trans-unit> <trans-unit id="NumberOfTypeParametersAndArgumentsMustMatch"> <source>the number of type parameters and arguments should be the same</source> <target state="translated">类型形参和实参的数量应相同</target> <note /> </trans-unit> <trans-unit id="ERR_ResourceInModule"> <source>Cannot link resource files when building a module</source> <target state="translated">生成模块时,无法链接资源文件</target> <note /> </trans-unit> <trans-unit id="NotAVbSymbol"> <source>Not a VB symbol.</source> <target state="translated">不是 VB 符号。</target> <note /> </trans-unit> <trans-unit id="ElementsCannotBeNull"> <source>Elements cannot be null.</source> <target state="translated">元素不能为 Null。</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportClause"> <source>Unused import clause.</source> <target state="translated">未使用导入子句。</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportStatement"> <source>Unused import statement.</source> <target state="translated">未使用导入语句。</target> <note /> </trans-unit> <trans-unit id="WrongSemanticModelType"> <source>Expected a {0} SemanticModel.</source> <target state="translated">应为 {0} SemanticModel。</target> <note /> </trans-unit> <trans-unit id="PositionNotWithinTree"> <source>Position must be within span of the syntax tree.</source> <target state="translated">位置必须处于语法树范围内。</target> <note /> </trans-unit> <trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation"> <source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source> <target state="translated">要推断的语法节点不能属于来自当前编译的语法树。</target> <note /> </trans-unit> <trans-unit id="ChainingSpeculativeModelIsNotSupported"> <source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source> <target state="translated">不支持链接推理语义模型。应从非推理 ParentModel 创建推理模型。</target> <note /> </trans-unit> <trans-unit id="IDS_ToolName"> <source>Microsoft (R) Visual Basic Compiler</source> <target state="translated">Microsoft (R) Visual Basic 编译器</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine1"> <source>{0} version {1}</source> <target state="translated">{0} 版本 {1}</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">版权所有(C) Microsoft Corporation。保留所有权利。</target> <note /> </trans-unit> <trans-unit id="IDS_LangVersions"> <source>Supported language versions:</source> <target state="translated">支持的语言版本:</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong"> <source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source> <target state="translated">本地名称“{0}”对于 PDB 太长。请考虑缩短或在不使用 /debug 的情况下编译。</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong_Title"> <source>Local name is too long for PDB</source> <target state="translated">本地名称对于 PDB 太长</target> <note /> </trans-unit> <trans-unit id="WRN_PdbUsingNameTooLong"> <source>Import string '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source> <target state="translated">导入字符串“{0}”对于 PDB 太长。请考虑缩短或在不使用 /debug 的情况下编译。</target> <note /> </trans-unit> <trans-unit id="WRN_PdbUsingNameTooLong_Title"> <source>Import string is too long for PDB</source> <target state="translated">导入字符串对 PDB 而言太长</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefToTypeParameter"> <source>XML comment has a tag with a 'cref' attribute '{0}' that bound to a type parameter. Use the &lt;typeparamref&gt; tag instead.</source> <target state="translated">XML 注释中的一个标记具有绑定到类型参数的“cref”特性“{0}”。请改用 &lt;typeparamref&gt; 标记。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefToTypeParameter_Title"> <source>XML comment has a tag with a 'cref' attribute that bound to a type parameter</source> <target state="translated">XML 注释包含的一个标记具有绑定到类型参数的 "cref" 属性</target> <note /> </trans-unit> <trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage"> <source>Linked netmodule metadata must provide a full PE image: '{0}'.</source> <target state="translated">链接 netmodule 元数据必须提供完整 PE 映像:“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated"> <source>An instance of analyzer {0} cannot be created from {1} : {2}.</source> <target state="translated">无法从 {1} 创建分析器 {0} 的实例: {2}。</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated_Title"> <source>Instance of analyzer cannot be created</source> <target state="translated">无法创建分析器实例</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly"> <source>The assembly {0} does not contain any analyzers.</source> <target state="translated">程序集 {0} 不包含任何分析器。</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly_Title"> <source>Assembly does not contain any analyzers</source> <target state="translated">程序集不包含任何分析器</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer"> <source>Unable to load analyzer assembly {0} : {1}.</source> <target state="translated">无法加载分析器程序集 {0}: {1}。</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer_Title"> <source>Unable to load analyzer assembly</source> <target state="translated">无法加载分析器程序集</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer"> <source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source> <target state="translated">正在跳过分析器程序集 {0} 中的某些类型,因为出现 ReflectionTypeLoadException: {1}。</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title"> <source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source> <target state="translated">跳过加载分析器程序集中因 ReflectionTypeLoadException 而失败的类型</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadRulesetFile"> <source>Error reading ruleset file {0} - {1}</source> <target state="translated">读取规则集文件 {0} 时出错 - {1}</target> <note /> </trans-unit> <trans-unit id="ERR_PlatformDoesntSupport"> <source>{0} is not supported in current project type.</source> <target state="translated">当前项目类型不支持 {0}。</target> <note /> </trans-unit> <trans-unit id="ERR_CantUseRequiredAttribute"> <source>The RequiredAttribute attribute is not permitted on Visual Basic types.</source> <target state="translated">Visual Basic 类型上不允许有 RequiredAttribute 特性。</target> <note /> </trans-unit> <trans-unit id="ERR_EncodinglessSyntaxTree"> <source>Cannot emit debug information for a source text without encoding.</source> <target state="translated">无法在不进行编码的情况下发出源文本的调试信息。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFormatSpecifier"> <source>'{0}' is not a valid format specifier</source> <target state="translated">“{0}”不是有效的格式说明符</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPreprocessorConstantType"> <source>Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed.</source> <target state="translated">不支持“{1}”类型的预处理器常数“{0}”,仅允许使用基元类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedWarningKeyword"> <source>'Warning' expected.</source> <target state="translated">'应为“Warning”。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotBeMadeNullable1"> <source>'{0}' cannot be made nullable.</source> <target state="translated">“{0}”不可以为 Null。</target> <note /> </trans-unit> <trans-unit id="ERR_BadConditionalWithRef"> <source>Leading '?' can only appear inside a 'With' statement, but not inside an object member initializer.</source> <target state="translated">以 "?" 开头的情况只能出现在“With”语句中,不能出现在对象成员初始值设定项中。</target> <note /> </trans-unit> <trans-unit id="ERR_NullPropagatingOpInExpressionTree"> <source>A null propagating operator cannot be converted into an expression tree.</source> <target state="translated">无法将 null 传播运算符转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_TooLongOrComplexExpression"> <source>An expression is too long or complex to compile</source> <target state="translated">表达式太长或者过于复杂,无法编译</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionDoesntHaveName"> <source>This expression does not have a name.</source> <target state="translated">该表达式不具有名称。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNameOfSubExpression"> <source>This sub-expression cannot be used inside NameOf argument.</source> <target state="translated">此子表达式不能在 NameOf 参数中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodTypeArgsUnexpected"> <source>Method type arguments unexpected.</source> <target state="translated">意外的方法类型参数。</target> <note /> </trans-unit> <trans-unit id="NoNoneSearchCriteria"> <source>SearchCriteria is expected.</source> <target state="translated">需要 SearchCriteria。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCulture"> <source>Assembly culture strings may not contain embedded NUL characters.</source> <target state="translated">程序集区域性字符串可能不包含嵌入式 NUL 字符。</target> <note /> </trans-unit> <trans-unit id="ERR_InReferencedAssembly"> <source>There is an error in a referenced assembly '{0}'.</source> <target state="translated">引用的程序集“{0}”中有错误。</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolationFormatWhitespace"> <source>Format specifier may not contain trailing whitespace.</source> <target state="translated">格式说明符可能不包含尾随空格。</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolationAlignmentOutOfRange"> <source>Alignment value is outside of the supported range.</source> <target state="translated">对齐值不在支持的范围内。</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringFactoryError"> <source>There were one or more errors emitting a call to {0}.{1}. Method or its return type may be missing or malformed.</source> <target state="translated">向 {0}.{1} 发出调用时出现一个或多个错误。方法或其返回类型可能缺失或格式不正确。</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportClause_Title"> <source>Unused import clause</source> <target state="translated">未使用 import 子句</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportStatement_Title"> <source>Unused import statement</source> <target state="translated">未使用 import 语句</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantStringTooLong"> <source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source> <target state="translated">由串联所得的字符串常量长度超过了 System.Int32.MaxValue。请尝试将字符串拆分为多个常量。</target> <note /> </trans-unit> <trans-unit id="ERR_LanguageVersion"> <source>Visual Basic {0} does not support {1}.</source> <target state="translated">Visual Basic {0} 不支持 {1}。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPdbData"> <source>Error reading debug information for '{0}'</source> <target state="translated">读取“{0}”的调试信息时出错</target> <note /> </trans-unit> <trans-unit id="FEATURE_ArrayLiterals"> <source>array literal expressions</source> <target state="translated">数组文本表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_AsyncExpressions"> <source>async methods or lambdas</source> <target state="translated">异步方法或 lambda</target> <note /> </trans-unit> <trans-unit id="FEATURE_AutoProperties"> <source>auto-implemented properties</source> <target state="translated">自动实现的属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_ReadonlyAutoProperties"> <source>readonly auto-implemented properties</source> <target state="translated">自动实现的只读属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_CoContraVariance"> <source>variance</source> <target state="translated">变型</target> <note /> </trans-unit> <trans-unit id="FEATURE_CollectionInitializers"> <source>collection initializers</source> <target state="translated">集合初始值设定项</target> <note /> </trans-unit> <trans-unit id="FEATURE_GlobalNamespace"> <source>declaring a Global namespace</source> <target state="translated">声明全局命名空间</target> <note /> </trans-unit> <trans-unit id="FEATURE_Iterators"> <source>iterators</source> <target state="translated">迭代器</target> <note /> </trans-unit> <trans-unit id="FEATURE_LineContinuation"> <source>implicit line continuation</source> <target state="translated">隐式行继续符</target> <note /> </trans-unit> <trans-unit id="FEATURE_StatementLambdas"> <source>multi-line lambda expressions</source> <target state="translated">多行 lambda 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_SubLambdas"> <source>'Sub' lambda expressions</source> <target state="translated">'“Sub”lambda 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_NullPropagatingOperator"> <source>null conditional operations</source> <target state="translated">空条件操作</target> <note /> </trans-unit> <trans-unit id="FEATURE_NameOfExpressions"> <source>'nameof' expressions</source> <target state="translated">'"nameof" 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_RegionsEverywhere"> <source>region directives within method bodies or regions crossing boundaries of declaration blocks</source> <target state="translated">方法主体内的 region 指令或跨声明块边界的 region</target> <note /> </trans-unit> <trans-unit id="FEATURE_MultilineStringLiterals"> <source>multiline string literals</source> <target state="translated">多行字符串文本</target> <note /> </trans-unit> <trans-unit id="FEATURE_CObjInAttributeArguments"> <source>CObj in attribute arguments</source> <target state="translated">属性参数中的 CObj</target> <note /> </trans-unit> <trans-unit id="FEATURE_LineContinuationComments"> <source>line continuation comments</source> <target state="translated">行延续注释</target> <note /> </trans-unit> <trans-unit id="FEATURE_TypeOfIsNot"> <source>TypeOf IsNot expression</source> <target state="translated">TypeOf IsNot 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_YearFirstDateLiterals"> <source>year-first date literals</source> <target state="translated">年份在最前面的日期文本</target> <note /> </trans-unit> <trans-unit id="FEATURE_WarningDirectives"> <source>warning directives</source> <target state="translated">warning 指令</target> <note /> </trans-unit> <trans-unit id="FEATURE_PartialModules"> <source>partial modules</source> <target state="translated">部分模块</target> <note /> </trans-unit> <trans-unit id="FEATURE_PartialInterfaces"> <source>partial interfaces</source> <target state="translated">部分接口</target> <note /> </trans-unit> <trans-unit id="FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite"> <source>implementing read-only or write-only property with read-write property</source> <target state="translated">使用读写属性实现只读或只写属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_DigitSeparators"> <source>digit separators</source> <target state="translated">数字分隔符</target> <note /> </trans-unit> <trans-unit id="FEATURE_BinaryLiterals"> <source>binary literals</source> <target state="translated">二进制文字</target> <note /> </trans-unit> <trans-unit id="FEATURE_Tuples"> <source>tuples</source> <target state="translated">元组</target> <note /> </trans-unit> <trans-unit id="FEATURE_PrivateProtected"> <source>Private Protected</source> <target state="translated">Private Protected</target> <note /> </trans-unit> <trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition"> <source>Debug entry point must be a definition of a method declared in the current compilation.</source> <target state="translated">调试入口点必须是当前编译中声明的方法的定义。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPathMap"> <source>The pathmap option was incorrectly formatted.</source> <target state="translated">路径映射选项的格式不正确。</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeIsNotASubmission"> <source>Syntax tree should be created from a submission.</source> <target state="translated">应从提交创建语法树。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyUserStrings"> <source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string or XML literals.</source> <target state="translated">该程序所使用的用户字符串的合并后长度超出所允许的限制。请尝试减少字符串文本或 XML 文本的使用。</target> <note /> </trans-unit> <trans-unit id="ERR_PeWritingFailure"> <source>An error occurred while writing the output file: {0}</source> <target state="translated">写入输出文件时出错: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_OptionMustBeAbsolutePath"> <source>Option '{0}' must be an absolute path.</source> <target state="translated">选项“{0}”必须是绝对路径。</target> <note /> </trans-unit> <trans-unit id="ERR_SourceLinkRequiresPdb"> <source>/sourcelink switch is only supported when emitting PDB.</source> <target state="translated">只在发出 PDB 时才支持 /sourcelink 开关。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleDuplicateElementName"> <source>Tuple element names must be unique.</source> <target state="translated">元组元素名称必须是唯一的。</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch"> <source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source> <target state="translated">由于目标类型“{1}”指定了其他名称或未指定名称,因此元组元素名称“{0}”被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch_Title"> <source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source> <target state="translated">由于分配目标指定了其他名称或未指定名称,因此元组元素名称被忽略。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementName"> <source>Tuple element name '{0}' is only allowed at position {1}.</source> <target state="translated">只允许位置 {1} 使用元组元素名称“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementNameAnyPosition"> <source>Tuple element name '{0}' is disallowed at any position.</source> <target state="translated">任何位置都不允许使用元组元素名称“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleTooFewElements"> <source>Tuple must contain at least two elements.</source> <target state="translated">元组必须包含至少两个元素。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNamesAttributeMissing"> <source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source> <target state="translated">由于找不到编译器必需的类型“{0}”,因此无法使用元组来定义类或成员。是否缺少引用?</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitTupleElementNamesAttribute"> <source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source> <target state="translated">无法显式引用 "System.Runtime.CompilerServices.TupleElementNamesAttribute"。请使用元组语法指定元组名称。</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturningCallInExpressionTree"> <source>An expression tree may not contain a call to a method or property that returns by reference.</source> <target state="translated">表达式树不能包含对引用所返回的方法或属性的调用。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotEmbedWithoutPdb"> <source>/embed switch is only supported when emitting a PDB.</source> <target state="translated">仅在发出 PDB 时才支持 /embed 开关。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInstrumentationKind"> <source>Invalid instrumentation kind: {0}</source> <target state="translated">无效的检测类型: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DocFileGen"> <source>Error writing to XML documentation file: {0}</source> <target state="translated">写入 XML 文档文件时出错: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAssemblyName"> <source>Invalid assembly name: {0}</source> <target state="translated">无效的程序集名称: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_TypeForwardedToMultipleAssemblies"> <source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source> <target state="translated">程序集“{1}”中的模块“{0}”将类型“{2}”转发到多个程序集: “{3}”和“{4}”。</target> <note /> </trans-unit> <trans-unit id="ERR_Merge_conflict_marker_encountered"> <source>Merge conflict marker encountered</source> <target state="translated">遇到合并冲突标记</target> <note /> </trans-unit> <trans-unit id="ERR_NoRefOutWhenRefOnly"> <source>Do not use refout when using refonly.</source> <target state="translated">不要在使用 refonly 时使用 refout。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly"> <source>Cannot compile net modules when using /refout or /refonly.</source> <target state="translated">无法在使用 /refout 或 /refonly 时编译 Net 模块。</target> <note /> </trans-unit> <trans-unit id="ERR_BadNonTrailingNamedArgument"> <source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source> <target state="translated">命名参数“{0}”的使用位置不当,但后跟一个未命名参数</target> <note /> </trans-unit> <trans-unit id="ERR_BadDocumentationMode"> <source>Provided documentation mode is unsupported or invalid: '{0}'.</source> <target state="translated">提供的文档模式不受支持或无效:“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadLanguageVersion"> <source>Provided language version is unsupported or invalid: '{0}'.</source> <target state="translated">提供的语言版本不受支持或无效:“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadSourceCodeKind"> <source>Provided source code kind is unsupported or invalid: '{0}'</source> <target state="translated">提供的源代码类型不受支持或无效:“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_TupleInferredNamesNotAvailable"> <source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source> <target state="translated">推断出元组元素名称“{0}”。请使用语言版本 {1} 或更高版本按推断名称访问元素。</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental"> <source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">“{0}”仅用于评估,在将来的更新中可能会被更改或删除。</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental_Title"> <source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">类型仅用于评估,在将来的更新中可能会被更改或删除。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInfo"> <source>Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}'</source> <target state="translated">无法从程序集“{2}”读取方法“{0}”(令牌 0x{1})的调试信息</target> <note /> </trans-unit> <trans-unit id="IConversionExpressionIsNotVisualBasicConversion"> <source>{0} is not a valid Visual Basic conversion expression</source> <target state="translated">{0} 不是有效的 Visual Basic 转换表达式</target> <note /> </trans-unit> <trans-unit id="IArgumentIsNotVisualBasicArgument"> <source>{0} is not a valid Visual Basic argument</source> <target state="translated">{0} 不是有效的 Visual Basic 参数</target> <note /> </trans-unit> <trans-unit id="FEATURE_LeadingDigitSeparator"> <source>leading digit separator</source> <target state="translated">前导数字分隔符</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTupleResolutionAmbiguous3"> <source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source> <target state="translated">已在多个引用的程序集(“{1}”和“{2}”)中声明了预定义类型“{0}”</target> <note /> </trans-unit> <trans-unit id="ICompoundAssignmentOperationIsNotVisualBasicCompoundAssignment"> <source>{0} is not a valid Visual Basic compound assignment operation</source> <target state="translated">{0} 不是有效的 Visual Basic 复合赋值运算</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidHashAlgorithmName"> <source>Invalid hash algorithm name: '{0}'</source> <target state="translated">无效的哈希算法名称:“{0}”</target> <note /> </trans-unit> <trans-unit id="FEATURE_InterpolatedStrings"> <source>interpolated strings</source> <target state="translated">内插字符串</target> <note /> </trans-unit> <trans-unit id="FTL_InvalidInputFileName"> <source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source> <target state="translated">文件名“{0}”为空、包含无效字符、未使用绝对路径指定驱动器或太长</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeNotSupportedInVB"> <source>'{0}' is not supported in VB.</source> <target state="translated">VB 中不支持“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeNotSupportedInVB_Title"> <source>Attribute is not supported in VB</source> <target state="translated">VB 中不支持属性</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../VBResources.resx"> <body> <trans-unit id="ERR_AssignmentInitOnly"> <source>Init-only property '{0}' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor.</source> <target state="translated">Init only 属性 "{0}" 只能由对象成员初始值设定项分配,或在实例构造函数中的 "Me"、"MyClass" 或 "MyBase" 上分配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadSwitchValue"> <source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source> <target state="translated">命令行语法错误:“{0}”不是“{1}”选项的有效值。值的格式必须为 "{2}"。</target> <note /> </trans-unit> <trans-unit id="ERR_CommentsAfterLineContinuationNotAvailable1"> <source>Please use language version {0} or greater to use comments after line continuation character.</source> <target state="translated">请使用语言版本 {0} 或更高版本,以在行继续符后使用注释。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">无法嵌入类型“{0}”,因为它有非抽象成员。请考虑将“嵌入互操作类型”属性设置为 false。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir"> <source>Multiple analyzer config files cannot be in the same directory ('{0}').</source> <target state="translated">多个分析器配置文件不能位于同一目录({0})中。</target> <note /> </trans-unit> <trans-unit id="ERR_OverridingInitOnlyProperty"> <source>'{0}' cannot override init-only '{1}'.</source> <target state="translated">"{0}" 无法重写 init-only "{1}"。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyDoesntImplementInitOnly"> <source>Init-only '{0}' cannot be implemented.</source> <target state="translated">无法实现 init-only "{0}"。</target> <note /> </trans-unit> <trans-unit id="ERR_ReAbstractionInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">无法嵌入类型“{0}”,因为它有基本接口成员的重新抽象。请考虑将“嵌入互操作类型”属性设置为 false。</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation"> <source>Target runtime doesn't support default interface implementation.</source> <target state="translated">目标运行时不支持默认接口实现。</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember"> <source>Target runtime doesn't support 'Protected', 'Protected Friend', or 'Private Protected' accessibility for a member of an interface.</source> <target state="translated">目标运行时不支持对接口的成员使用 "Protected"、"Protected Friend" 或 "Private Protected" 辅助功能。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedEventNeedsHandlerInTheSameType"> <source>Events of shared WithEvents variables cannot be handled by methods in a different type.</source> <target state="translated">共享 WithEvents 变量的事件不能由其他类型的方法处理。</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyNotSupported"> <source>'UnmanagedCallersOnly' attribute is not supported.</source> <target state="translated">不支持 "UnmanagedCallersOnly" 属性。</target> <note /> </trans-unit> <trans-unit id="FEATURE_CallerArgumentExpression"> <source>caller argument expression</source> <target state="new">caller argument expression</target> <note /> </trans-unit> <trans-unit id="FEATURE_CommentsAfterLineContinuation"> <source>comments after line continuation</source> <target state="translated">行继续符之后的注释</target> <note /> </trans-unit> <trans-unit id="FEATURE_InitOnlySettersUsage"> <source>assigning to or passing 'ByRef' properties with init-only setters</source> <target state="translated">通过 init-only 资源库分配或传递 "ByRef" 属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_UnconstrainedTypeParameterInConditional"> <source>unconstrained type parameters in binary conditional expressions</source> <target state="translated">二进制条件表达式中的无约束类型参数</target> <note /> </trans-unit> <trans-unit id="IDS_VBCHelp"> <source> Visual Basic Compiler Options - OUTPUT FILE - -out:&lt;file&gt; Specifies the output file name. -target:exe Create a console application (default). (Short form: -t) -target:winexe Create a Windows application. -target:library Create a library assembly. -target:module Create a module that can be added to an assembly. -target:appcontainerexe Create a Windows application that runs in AppContainer. -target:winmdobj Create a Windows Metadata intermediate file -doc[+|-] Generates XML documentation file. -doc:&lt;file&gt; Generates XML documentation file to &lt;file&gt;. -refout:&lt;file&gt; Reference assembly output to generate - INPUT FILES - -addmodule:&lt;file_list&gt; Reference metadata from the specified modules -link:&lt;file_list&gt; Embed metadata from the specified interop assembly. (Short form: -l) -recurse:&lt;wildcard&gt; Include all files in the current directory and subdirectories according to the wildcard specifications. -reference:&lt;file_list&gt; Reference metadata from the specified assembly. (Short form: -r) -analyzer:&lt;file_list&gt; Run the analyzers from this assembly (Short form: -a) -additionalfile:&lt;file list&gt; Additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings. - RESOURCES - -linkresource:&lt;resinfo&gt; Links the specified file as an external assembly resource. resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (Short form: -linkres) -nowin32manifest The default manifest should not be embedded in the manifest section of the output PE. -resource:&lt;resinfo&gt; Adds the specified file as an embedded assembly resource. resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (Short form: -res) -win32icon:&lt;file&gt; Specifies a Win32 icon file (.ico) for the default Win32 resources. -win32manifest:&lt;file&gt; The provided file is embedded in the manifest section of the output PE. -win32resource:&lt;file&gt; Specifies a Win32 resource file (.res). - CODE GENERATION - -optimize[+|-] Enable optimizations. -removeintchecks[+|-] Remove integer checks. Default off. -debug[+|-] Emit debugging information. -debug:full Emit full debugging information (default). -debug:pdbonly Emit full debugging information. -debug:portable Emit cross-platform debugging information. -debug:embedded Emit cross-platform debugging information into the target .dll or .exe. -deterministic Produce a deterministic assembly (including module version GUID and timestamp) -refonly Produce a reference assembly in place of the main output -instrument:TestCoverage Produce an assembly instrumented to collect coverage information -sourcelink:&lt;file&gt; Source link info to embed into PDB. - ERRORS AND WARNINGS - -nowarn Disable all warnings. -nowarn:&lt;number_list&gt; Disable a list of individual warnings. -warnaserror[+|-] Treat all warnings as errors. -warnaserror[+|-]:&lt;number_list&gt; Treat a list of warnings as errors. -ruleset:&lt;file&gt; Specify a ruleset file that disables specific diagnostics. -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] Specify a file to log all compiler and analyzer diagnostics in SARIF format. sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 both mean SARIF version 2.1.0. -reportanalyzer Report additional analyzer information, such as execution time. -skipanalyzers[+|-] Skip execution of diagnostic analyzers. - LANGUAGE - -define:&lt;symbol_list&gt; Declare global conditional compilation symbol(s). symbol_list:name=value,... (Short form: -d) -imports:&lt;import_list&gt; Declare global Imports for namespaces in referenced metadata files. import_list:namespace,... -langversion:? Display the allowed values for language version -langversion:&lt;string&gt; Specify language version such as `default` (latest major version), or `latest` (latest version, including minor versions), or specific versions like `14` or `15.3` -optionexplicit[+|-] Require explicit declaration of variables. -optioninfer[+|-] Allow type inference of variables. -rootnamespace:&lt;string&gt; Specifies the root Namespace for all type declarations. -optionstrict[+|-] Enforce strict language semantics. -optionstrict:custom Warn when strict language semantics are not respected. -optioncompare:binary Specifies binary-style string comparisons. This is the default. -optioncompare:text Specifies text-style string comparisons. - MISCELLANEOUS - -help Display this usage message. (Short form: -?) -noconfig Do not auto-include VBC.RSP file. -nologo Do not display compiler copyright banner. -quiet Quiet output mode. -verbose Display verbose messages. -parallel[+|-] Concurrent build. -version Display the compiler version number and exit. - ADVANCED - -baseaddress:&lt;number&gt; The base address for a library or module (hex). -checksumalgorithm:&lt;alg&gt; Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default). -codepage:&lt;number&gt; Specifies the codepage to use when opening source files. -delaysign[+|-] Delay-sign the assembly using only the public portion of the strong name key. -publicsign[+|-] Public-sign the assembly using only the public portion of the strong name key. -errorreport:&lt;string&gt; Specifies how to handle internal compiler errors; must be prompt, send, none, or queue (default). -filealign:&lt;number&gt; Specify the alignment used for output file sections. -highentropyva[+|-] Enable high-entropy ASLR. -keycontainer:&lt;string&gt; Specifies a strong name key container. -keyfile:&lt;file&gt; Specifies a strong name key file. -libpath:&lt;path_list&gt; List of directories to search for metadata references. (Semi-colon delimited.) -main:&lt;class&gt; Specifies the Class or Module that contains Sub Main. It can also be a Class that inherits from System.Windows.Forms.Form. (Short form: -m) -moduleassemblyname:&lt;string&gt; Name of the assembly which this module will be a part of. -netcf Target the .NET Compact Framework. -nostdlib Do not reference standard libraries (system.dll and VBC.RSP file). -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... Specify a mapping for source path names output by the compiler. -platform:&lt;string&gt; Limit which platforms this code can run on; must be x86, x64, Itanium, arm, arm64 AnyCPU32BitPreferred or anycpu (default). -preferreduilang Specify the preferred output language name. -nosdkpath Disable searching the default SDK path for standard library assemblies. -sdkpath:&lt;path&gt; Location of the .NET Framework SDK directory (mscorlib.dll). -subsystemversion:&lt;version&gt; Specify subsystem version of the output PE. version:&lt;number&gt;[.&lt;number&gt;] -utf8output[+|-] Emit compiler output in UTF8 character encoding. @&lt;file&gt; Insert command-line settings from a text file -vbruntime[+|-|*] Compile with/without the default Visual Basic runtime. -vbruntime:&lt;file&gt; Compile with the alternate Visual Basic runtime in &lt;file&gt;. </source> <target state="translated"> Visual Basic 编译器选项 - 输出文件 - -out:&lt;file&gt; 指定输出文件名称。 -target:exe 创建控制台应用程序(默认)。 (缩写: -t) -target:winexe 创建 Windows 应用程序。 -target:library 创建库程序集。 -target:module 创建可添加到程序集的 模块。 -target:appcontainerexe 创建在 AppContainer 中运行的 Windows 应用程序。 -target:winmdobj 创建 Windows 元数据中间文件 -doc[+|-] 生成 XML 文档文件。 -doc:&lt;file&gt; 将 XML 文档文件生成到 &lt;file&gt; -refout:&lt;file&gt; 引用要生成的引用程序集 - 输入文件 - -addmodule:&lt;file_list&gt; 从指定模块中引用元数据 -link:&lt;file_list&gt; 嵌入指定互操作程序集中的 元数据。(缩写: -l) -recurse:&lt;wildcard&gt; 根据通配符规范包括 当前目录和子目录中 的所有文件。 -reference:&lt;file_list&gt; 从指定程序集中引用 元数据。(缩写: -r) -analyzer:&lt;file_list&gt; 运行此程序集的分析器 (缩写: -a) -additionalfile:&lt;file list&gt; 不直接影响代码 生成但可能被分析器用于生成 错误或警告的其他文件。 - 资源 - -linkresource:&lt;resinfo&gt; 将指定文件作为外部 程序集资源进行链接。 resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (缩写: -linkres) -nowin32manifest 默认清单不应嵌入 输出 PE 的清单部分。 -resource:&lt;resinfo&gt; 将指定文件作为嵌入式 程序集资源进行添加。 resinfo:&lt;file&gt;[,&lt;name&gt;[,public|private]] (缩写: -res) -win32icon:&lt;file&gt; 为默认的 Win32 资源 指定 Win32 图标文件(.ico)。 -win32manifest:&lt;file&gt; 提供的文件嵌入在 输出 PE 的清单部分。 -win32resource:&lt;file&gt; 指定 Win32 资源文件(.res)。 - 代码生成 - -optimize[+|-] 启用优化。 -removeintchecks[+|-] 删除整数检查。默认为“关”。 -debug[+|-] 发出调试信息。 -debug:full 发出完全调试信息(默认)。 -debug:pdbonly 发出完全调试信息。 -debug:portable 发出跨平台调试信息。 -debug:embedded 发出跨平台调试信息到 目标 .dll 或 .exe. -deterministic 生成确定性程序集 (包括模块版本 GUID 和时间戳) -refonly 生成引用程序集来替代主要输出 -instrument:TestCoverage 生成对其检测以收集覆盖率信息的t 程序集 -sourcelink:&lt;file&gt; 要嵌入到 PDB 中的源链接信息。 - 错误和警告 - -nowarn 禁用所有警告。 -nowarn:&lt;number_list&gt; 禁用个人警告列表。 -warnaserror[+|-] 将所有警告视为错误。 -warnaserror[+|-]:&lt;number_list&gt; 将警告列表视为错误。 -ruleset:&lt;file&gt; 指定禁用特定诊断的 规则集文件。 -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] 指定用于以 SARIF 格式记录所有编译器和分析器诊断的 文件。 sarif_version:{1|2|2.1} 默认为 1. 2 和 2.1 两者均表示 SARIF 版本 2.1.0。 -reportanalyzer 报告其他分析器信息,如 执行时间。 -skipanalyzers[+|-] 跳过诊断分析器的执行。 - 语言 - -define:&lt;symbol_list&gt; 声明全局条件编译 符号。symbol_list:name=value,... (缩写: -d) -imports:&lt;import_list&gt; 为引用的元数据文件中的命名空间声明 全局导入。 import_list:namespace,... -langversion:? 显示允许的语言版本值 -langversion:&lt;string&gt; 指定语言版本,如 “default” (最新主要版本)、 “latest” (最新版本,包括次要版本) 或 “14”、”15.3”等特定版本 -optionexplicit[+|-] 需要显示声明变量。 -optioninfer[+|-] 允许变量的类型推理。 -rootnamespace:&lt;string&gt; 指定所有类型声明的根 命名空间。 -optionstrict[+|-] 强制严格语言语义。 -optionstrict:custom 不遵从严格语言语义时 发出警告。 -optioncompare:binary 指定二进制样式的字符串比较。 这是默认设置。 -optioncompare:text 指定文本样式字符串比较。 - 杂项 - -help 显示此用法消息。(缩写: -?) -noconfig 不自动包括 VBC.RSP 文件。 -nologo 不显示编译器版权横幅。 -quiet 安静输出模式。 -verbose 显示详细消息。 -parallel[+|-] 并发生成。 -version 显示编译器版本号并退出。 - 高级 - -baseaddress:&lt;number&gt; 库或模块的基址 (十六进制)。 -checksumalgorithm:&lt;alg&gt; 指定计算存储在 PDB 中的源文件校验和 的算法。支持的值是: SHA1 或 SHA256 (默认)。 -codepage:&lt;number&gt; 指定打开源文件时要使用的 代码页。 -delaysign[+|-] 仅使用强名称密钥的公共部分 对程序集进行延迟签名。 -publicsign[+|-] 仅使用强名称密钥的公共部分 对程序集进行公共签名 -errorreport:&lt;string&gt; 指定处理内部编译器错误的方式; 必须是 prompt、send、none 或 queue (默认)。 -filealign:&lt;number&gt; 指定用于输出文件节的对齐 方式。 -highentropyva[+|-] 启用高平均信息量的 ASLR。 -keycontainer:&lt;string&gt; 指定强名称密钥容器。 -keyfile:&lt;file&gt; 指定强名称密钥文件。 -libpath:&lt;path_list&gt; 搜索元数据引用的目录 列表。(分号分隔。) -main:&lt;class&gt; 指定包含 Sub Main 的类 或模块。也可为从 System.Windows.Forms.Form 继承的类。 (缩写: -m) -moduleassemblyname:&lt;string&gt; 此模块所属程序集 的名称。 -netcf 以 .NET Compact Framework 为目标。 -nostdlib 不引用标准库 (system.dll 和 VBC.RSP 文件)。 -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... 按编译器指定源路径名称输出的 映射。 -platform:&lt;string&gt; 限制此代码可以在其上运行的平台; 必须是 x86、x64、Itanium、arm、arm64、 AnyCPU32BitPreferred 或 anycpu (默认)。 -preferreduilang 指定首选输出语言名称。 -nosdkpath 禁用搜索标准库程序集的默认 SDK 路径 -sdkpath:&lt;path&gt; .NET Framework SDK 目录的位置 (mscorlib.dll). -subsystemversion:&lt;version&gt; 指定输出 PE 的子系统版本。 version:&lt;number&gt;[.&lt;number&gt;] -utf8output[+|-] 以 UTF8 字符编码格式 发出编译器输出。 @&lt;file&gt; 从文本文件插入命令行设置 -vbruntime[+|-|*] 用/不用默认的 Visual Basic 运行时进行编译。 -vbruntime:&lt;file&gt; 使用 &lt;file&gt; 中的备用 Visual Basic 运行时 进行编译。 </target> <note /> </trans-unit> <trans-unit id="ThereAreNoFunctionPointerTypesInVB"> <source>There are no function pointer types in VB.</source> <target state="translated">VB 中没有任何函数指针类型。</target> <note /> </trans-unit> <trans-unit id="ThereAreNoNativeIntegerTypesInVB"> <source>There are no native integer types in VB.</source> <target state="translated">VB 中没有任何本机整数类型。</target> <note /> </trans-unit> <trans-unit id="Trees0"> <source>trees({0})</source> <target state="translated">树({0})</target> <note /> </trans-unit> <trans-unit id="TreesMustHaveRootNode"> <source>trees({0}) must have root node with SyntaxKind.CompilationUnit.</source> <target state="translated">树({0}) 必须具有带 SyntaxKind.CompilationUnit 的根节点。</target> <note /> </trans-unit> <trans-unit id="CannotAddCompilerSpecialTree"> <source>Cannot add compiler special tree</source> <target state="translated">无法添加特定于编译器的树</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeAlreadyPresent"> <source>Syntax tree already present</source> <target state="translated">语法树已存在</target> <note /> </trans-unit> <trans-unit id="SubmissionCanHaveAtMostOneSyntaxTree"> <source>Submission can have at most one syntax tree.</source> <target state="translated">提交最多可以具有一个语法树。</target> <note /> </trans-unit> <trans-unit id="CannotRemoveCompilerSpecialTree"> <source>Cannot remove compiler special tree</source> <target state="translated">无法移除特定于编译器的树</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeNotFoundToRemove"> <source>SyntaxTree '{0}' not found to remove</source> <target state="translated">未找到要删除的 SyntaxTree“{0}”</target> <note /> </trans-unit> <trans-unit id="TreeMustHaveARootNodeWithCompilationUnit"> <source>Tree must have a root node with SyntaxKind.CompilationUnit</source> <target state="translated">树必须具有带 SyntaxKind.CompilationUnit 的根节点</target> <note /> </trans-unit> <trans-unit id="CompilationVisualBasic"> <source>Compilation (Visual Basic): </source> <target state="translated">编译(Visual Basic):</target> <note /> </trans-unit> <trans-unit id="NodeIsNotWithinSyntaxTree"> <source>Node is not within syntax tree</source> <target state="translated">节点不在语法树中</target> <note /> </trans-unit> <trans-unit id="CantReferenceCompilationFromTypes"> <source>Can't reference compilation of type '{0}' from {1} compilation.</source> <target state="translated">无法从 {1} 编译引用类型为“{0}”的编译。</target> <note /> </trans-unit> <trans-unit id="PositionOfTypeParameterTooLarge"> <source>position of type parameter too large</source> <target state="translated">类型参数的位置太大</target> <note /> </trans-unit> <trans-unit id="AssociatedTypeDoesNotHaveTypeParameters"> <source>Associated type does not have type parameters</source> <target state="translated">关联类型没有类型参数</target> <note /> </trans-unit> <trans-unit id="IDS_FunctionReturnType"> <source>function return type</source> <target state="translated">函数返回类型</target> <note /> </trans-unit> <trans-unit id="TypeArgumentCannotBeNothing"> <source>Type argument cannot be Nothing</source> <target state="translated">类型参数不能是任何内容</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework"> <source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source> <target state="translated">包含类型“{1}”的程序集“{0}”引用了 .NET Framework,而此操作不受支持。</target> <note>{1} is the type that was loaded, {0} is the containing assembly.</note> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework_Title"> <source>The loaded assembly references .NET Framework, which is not supported.</source> <target state="translated">加载的程序集引用了 .NET Framework,而此操作不受支持。</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title"> <source>The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title"> <source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration"> <source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">生成器“{0}”未能生成源。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}”</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">生成器引发以下异常: “{0}”。</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Title"> <source>Generator failed to generate source.</source> <target state="translated">生成器无法生成源。</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization"> <source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">生成器“{0}”未能初始化。它不会影响输出,因此可能会造成编译错误。异常的类型为“{1}”,显示消息“{2}”</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">生成器引发以下异常: “{0}”。</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Title"> <source>Generator failed to initialize.</source> <target state="translated">生成器初始化失败。</target> <note /> </trans-unit> <trans-unit id="WrongNumberOfTypeArguments"> <source>Wrong number of type arguments</source> <target state="translated">类型参数的数目不正确</target> <note /> </trans-unit> <trans-unit id="ERR_FileNotFound"> <source>file '{0}' could not be found</source> <target state="translated">找不到文件“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_NoResponseFile"> <source>unable to open response file '{0}'</source> <target state="translated">无法打开响应文件“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentRequired"> <source>option '{0}' requires '{1}'</source> <target state="translated">选项“{0}”需要“{1}”</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchNeedsBool"> <source>option '{0}' can be followed only by '+' or '-'</source> <target state="translated">选项“{0}”后面只能跟“+”或“-”</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSwitchValue"> <source>the value '{1}' is invalid for option '{0}'</source> <target state="translated">值“{1}”对选项“{0}”无效</target> <note /> </trans-unit> <trans-unit id="ERR_MutuallyExclusiveOptions"> <source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source> <target state="translated">无法同时指定编译选项“{0}”和“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang"> <source>The language name '{0}' is invalid.</source> <target state="translated">语言名“{0}”无效。</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang_Title"> <source>The language name for /preferreduilang is invalid</source> <target state="translated">/preferreduilang 的语言名称无效</target> <note /> </trans-unit> <trans-unit id="ERR_VBCoreNetModuleConflict"> <source>The options /vbruntime* and /target:module cannot be combined.</source> <target state="translated">/vbruntime* 选项不能与 /target:module 选项组合。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFormatForGuidForOption"> <source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source> <target state="translated">命令行语法错误: Guid 格式“{0}”对于选项“{1}”无效</target> <note /> </trans-unit> <trans-unit id="ERR_MissingGuidForOption"> <source>Command-line syntax error: Missing Guid for option '{1}'</source> <target state="translated">命令行语法错误: 选项“{1}”缺少 Guid</target> <note /> </trans-unit> <trans-unit id="ERR_BadChecksumAlgorithm"> <source>Algorithm '{0}' is not supported</source> <target state="translated">不支持算法“{0}”</target> <note /> </trans-unit> <trans-unit id="WRN_BadSwitch"> <source>unrecognized option '{0}'; ignored</source> <target state="translated">无法识别的选项“{0}”;已忽略</target> <note /> </trans-unit> <trans-unit id="WRN_BadSwitch_Title"> <source>Unrecognized command-line option</source> <target state="translated">无法识别的命令行选项</target> <note /> </trans-unit> <trans-unit id="ERR_NoSources"> <source>no input sources specified</source> <target state="translated">未指定输入源</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded"> <source>source file '{0}' specified multiple times</source> <target state="translated">源文件“{0}”指定了多次</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded_Title"> <source>Source file specified multiple times</source> <target state="translated">多次指定源文件</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenFileWrite"> <source>can't open '{0}' for writing: {1}</source> <target state="translated">无法打开“{0}”进行写入: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadCodepage"> <source>code page '{0}' is invalid or not installed</source> <target state="translated">代码页“{0}”无效或未安装</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryFile"> <source>the file '{0}' is not a text file</source> <target state="translated">文件“{0}”不是文本文件</target> <note /> </trans-unit> <trans-unit id="ERR_LibNotFound"> <source>could not find library '{0}'</source> <target state="translated">找不到库“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataReferencesNotSupported"> <source>Metadata references not supported.</source> <target state="translated">不支持元数据引用。</target> <note /> </trans-unit> <trans-unit id="ERR_IconFileAndWin32ResFile"> <source>cannot specify both /win32icon and /win32resource</source> <target state="translated">不能同时指定 /win32icon 和 /win32resource</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigInResponseFile"> <source>ignoring /noconfig option because it was specified in a response file</source> <target state="translated">/noconfig 选项是在响应文件中指定的,因此被忽略</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigInResponseFile_Title"> <source>Ignoring /noconfig option because it was specified in a response file</source> <target state="translated">/noconfig 选项是在响应文件中指定的,因此被忽略</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidWarningId"> <source>warning number '{0}' for the option '{1}' is either not configurable or not valid</source> <target state="translated">选项“{1}”的警告编号“{0}”不可配置或无效</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidWarningId_Title"> <source>Warning number is either not configurable or not valid</source> <target state="translated">警告编号不可配置或无效</target> <note /> </trans-unit> <trans-unit id="ERR_NoSourcesOut"> <source>cannot infer an output file name from resource only input files; provide the '/out' option</source> <target state="translated">无法从仅资源输入文件推理出输出文件名;提供“/out”选项</target> <note /> </trans-unit> <trans-unit id="ERR_NeedModule"> <source>the /moduleassemblyname option may only be specified when building a target of type 'module'</source> <target state="translated">只有在生成“module”类型的目标时才能指定 /moduleassemblyname 选项</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyName"> <source>'{0}' is not a valid value for /moduleassemblyname</source> <target state="translated">“{0}”不是 /moduleassemblyname 的有效值</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingManifestSwitches"> <source>Error embedding Win32 manifest: Option /win32manifest conflicts with /nowin32manifest.</source> <target state="translated">嵌入 Win32 清单时出错: 选项 /win32manifest 与 /nowin32manifest 冲突。</target> <note /> </trans-unit> <trans-unit id="WRN_IgnoreModuleManifest"> <source>Option /win32manifest ignored. It can be specified only when the target is an assembly.</source> <target state="translated">已忽略选项 /win32manifest。只有在目标是程序集时才能指定该选项。</target> <note /> </trans-unit> <trans-unit id="WRN_IgnoreModuleManifest_Title"> <source>Option /win32manifest ignored</source> <target state="translated">/win32manifest 选项已忽略</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInNamespace"> <source>Statement is not valid in a namespace.</source> <target state="translated">语句在命名空间中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_UndefinedType1"> <source>Type '{0}' is not defined.</source> <target state="translated">未定义类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingNext"> <source>'Next' expected.</source> <target state="translated">'应为 "Next"。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalCharConstant"> <source>Character constant must contain exactly one character.</source> <target state="translated">字符常量必须正好包含一个字符。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedAssemblyEvent3"> <source>Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project.</source> <target state="translated">需要对程序集“{0}”(包含事件“{1}”的定义)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedModuleEvent3"> <source>Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project.</source> <target state="translated">需要对模块“{0}”(包含事件“{1}”的定义)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_LbExpectedEndIf"> <source>'#If' block must end with a matching '#End If'.</source> <target state="translated">'"#If" 块必须以匹配的 "#End If" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_LbNoMatchingIf"> <source>'#ElseIf', '#Else', or '#End If' must be preceded by a matching '#If'.</source> <target state="translated">'"#ElseIf"、"#Else" 或 "#End If" 前面必须是匹配的 "#If"。</target> <note /> </trans-unit> <trans-unit id="ERR_LbBadElseif"> <source>'#ElseIf' must be preceded by a matching '#If' or '#ElseIf'.</source> <target state="translated">'"#ElseIf" 前面必须是匹配的 "#If" 或 "#ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromRestrictedType1"> <source>Inheriting from '{0}' is not valid.</source> <target state="translated">从“{0}”继承无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvOutsideProc"> <source>Labels are not valid outside methods.</source> <target state="translated">标签在方法外部无效。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateCantImplement"> <source>Delegates cannot implement interface methods.</source> <target state="translated">委托无法实现接口方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateCantHandleEvents"> <source>Delegates cannot handle events.</source> <target state="translated">委托无法处理事件。</target> <note /> </trans-unit> <trans-unit id="ERR_IsOperatorRequiresReferenceTypes1"> <source>'Is' operator does not accept operands of type '{0}'. Operands must be reference or nullable types.</source> <target state="translated">'“Is”运算符不接受类型为“{0}”的操作数。操作数必须是引用类型或可以为 null 的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOfRequiresReferenceType1"> <source>'TypeOf ... Is' requires its left operand to have a reference type, but this operand has the value type '{0}'.</source> <target state="translated">'“TypeOf ... Is”要求它的左操作数具有引用类型,但此操作数具有值类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyHasSet"> <source>Properties declared 'ReadOnly' cannot have a 'Set'.</source> <target state="translated">声明为 "ReadOnly" 的属性不能有 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_WriteOnlyHasGet"> <source>Properties declared 'WriteOnly' cannot have a 'Get'.</source> <target state="translated">声明为 "WriteOnly" 的属性不能有 "Get"。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideProc"> <source>Statement is not valid inside a method.</source> <target state="translated">语句在方法内部无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideBlock"> <source>Statement is not valid inside '{0}' block.</source> <target state="translated">语句在“{0}”块内部无效。</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedExpressionStatement"> <source>Expression statement is only allowed at the end of an interactive submission.</source> <target state="translated">只允许在交互提交结尾处使用表达式语句。</target> <note /> </trans-unit> <trans-unit id="ERR_EndProp"> <source>Property missing 'End Property'.</source> <target state="translated">Property 缺少 "End Property"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndSubExpected"> <source>'End Sub' expected.</source> <target state="translated">'应为 "End Sub"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndFunctionExpected"> <source>'End Function' expected.</source> <target state="translated">'应为 "End Function"。</target> <note /> </trans-unit> <trans-unit id="ERR_LbElseNoMatchingIf"> <source>'#Else' must be preceded by a matching '#If' or '#ElseIf'.</source> <target state="translated">'"#Else" 前面必须是匹配的 "#If" 或 "#ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_CantRaiseBaseEvent"> <source>Derived classes cannot raise base class events.</source> <target state="translated">派生类不能引发基类事件。</target> <note /> </trans-unit> <trans-unit id="ERR_TryWithoutCatchOrFinally"> <source>Try must have at least one 'Catch' or a 'Finally'.</source> <target state="translated">Try 必须至少有一个 "Catch" 或 "Finally"。</target> <note /> </trans-unit> <trans-unit id="ERR_EventsCantBeFunctions"> <source>Events cannot have a return type.</source> <target state="translated">事件不能有返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndBrack"> <source>Bracketed identifier is missing closing ']'.</source> <target state="translated">用括号标识的标识符缺少右边的 "]"。</target> <note /> </trans-unit> <trans-unit id="ERR_Syntax"> <source>Syntax error.</source> <target state="translated">语法错误。</target> <note /> </trans-unit> <trans-unit id="ERR_Overflow"> <source>Overflow.</source> <target state="translated">溢出。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalChar"> <source>Character is not valid.</source> <target state="translated">字符无效。</target> <note /> </trans-unit> <trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected"> <source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source> <target state="translated">已指定 stdin 参数 "-",但尚未从标准输入流重定向输入。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsObjectOperand1"> <source>Option Strict On prohibits operands of type Object for operator '{0}'.</source> <target state="translated">Option Strict On 禁止将 Object 类型的操作数用于运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_LoopControlMustNotBeProperty"> <source>Loop control variable cannot be a property or a late-bound indexed array.</source> <target state="translated">循环控制变量不能是属性或后期绑定索引数组。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodBodyNotAtLineStart"> <source>First statement of a method body cannot be on the same line as the method declaration.</source> <target state="translated">方法主体的第一条语句和方法声明不能位于同一行。</target> <note /> </trans-unit> <trans-unit id="ERR_MaximumNumberOfErrors"> <source>Maximum number of errors has been exceeded.</source> <target state="translated">已超出最大错误数。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfKeywordNotInInstanceMethod1"> <source>'{0}' is valid only within an instance method.</source> <target state="translated">“{0}”仅在实例方法中有效。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfKeywordFromStructure1"> <source>'{0}' is not valid within a structure.</source> <target state="translated">“{0}”在结构中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeConstructor1"> <source>Attribute constructor has a parameter of type '{0}', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types.</source> <target state="translated">特性构造函数具有“{0}”类型的参数,此参数不是整型、浮点型或枚举类型,也不是 Object、Char、String、Boolean、System.Type 之一或这些类型的一维数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayWithOptArgs"> <source>Method cannot have both a ParamArray and Optional parameters.</source> <target state="translated">方法不能同时具有 ParamArray 和 Optional 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedArray1"> <source>'{0}' statement requires an array.</source> <target state="translated">“{0}”语句需要数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayNotArray"> <source>ParamArray parameter must be an array.</source> <target state="translated">ParamArray 参数必须是一个数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayRank"> <source>ParamArray parameter must be a one-dimensional array.</source> <target state="translated">ParamArray 参数必须是一维数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayRankLimit"> <source>Array exceeds the limit of 32 dimensions.</source> <target state="translated">数组超过了 32 维数限制。</target> <note /> </trans-unit> <trans-unit id="ERR_AsNewArray"> <source>Arrays cannot be declared with 'New'.</source> <target state="translated">不能用 "New" 声明数组。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyArgs1"> <source>Too many arguments to '{0}'.</source> <target state="translated">“{0}”的参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedCase"> <source>Statements and labels are not valid between 'Select Case' and first 'Case'.</source> <target state="translated">位于 "Select Case" 与第一个 "Case" 之间的语句和标签无效。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredConstExpr"> <source>Constant expression is required.</source> <target state="translated">要求常量表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredConstConversion2"> <source>Conversion from '{0}' to '{1}' cannot occur in a constant expression.</source> <target state="translated">常量表达式中不能发生从“{0}”到“{1}”的转换。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMe"> <source>'Me' cannot be the target of an assignment.</source> <target state="translated">'"Me" 不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyAssignment"> <source>'ReadOnly' variable cannot be the target of an assignment.</source> <target state="translated">'"ReadOnly" 变量不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitSubOfFunc"> <source>'Exit Sub' is not valid in a Function or Property.</source> <target state="translated">'"Exit Sub" 在函数或属性中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitPropNot"> <source>'Exit Property' is not valid in a Function or Sub.</source> <target state="translated">'“Exit Property”在函数或 Sub 中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitFuncOfSub"> <source>'Exit Function' is not valid in a Sub or Property.</source> <target state="translated">'"Exit Function" 在 Sub 或属性中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_LValueRequired"> <source>Expression is a value and therefore cannot be the target of an assignment.</source> <target state="translated">表达式是一个值,因此不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ForIndexInUse1"> <source>For loop control variable '{0}' already in use by an enclosing For loop.</source> <target state="translated">For 循环控制变量“{0}”已由封闭 For 循环使用。</target> <note /> </trans-unit> <trans-unit id="ERR_NextForMismatch1"> <source>Next control variable does not match For loop control variable '{0}'.</source> <target state="translated">Next 控制变量与 For 循环控制变量“{0}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_CaseElseNoSelect"> <source>'Case Else' can only appear inside a 'Select Case' statement.</source> <target state="translated">'“Case Else”只能出现在“Select Case”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_CaseNoSelect"> <source>'Case' can only appear inside a 'Select Case' statement.</source> <target state="translated">'“Case”只能出现在“Select Case”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_CantAssignToConst"> <source>Constant cannot be the target of an assignment.</source> <target state="translated">常量不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedSubscript"> <source>Named arguments are not valid as array subscripts.</source> <target state="translated">命名参数作为数组下标无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndIf"> <source>'If' must end with a matching 'End If'.</source> <target state="translated">'“If”必须以匹配的“End If”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndWhile"> <source>'While' must end with a matching 'End While'.</source> <target state="translated">'“While”必须以匹配的“End While”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLoop"> <source>'Do' must end with a matching 'Loop'.</source> <target state="translated">'"Do" 必须以匹配的 "Loop" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedNext"> <source>'For' must end with a matching 'Next'.</source> <target state="translated">'"For" 必须以匹配的 "Next" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndWith"> <source>'With' must end with a matching 'End With'.</source> <target state="translated">'“With”必须以匹配的“End With”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ElseNoMatchingIf"> <source>'Else' must be preceded by a matching 'If' or 'ElseIf'.</source> <target state="translated">'"Else" 前面必须是匹配的 "If" 或 "ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndIfNoMatchingIf"> <source>'End If' must be preceded by a matching 'If'.</source> <target state="translated">'"End If" 前面必须是匹配的 "If"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndSelectNoSelect"> <source>'End Select' must be preceded by a matching 'Select Case'.</source> <target state="translated">'"End Select" 前面必须是匹配的 "Select Case"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitDoNotWithinDo"> <source>'Exit Do' can only appear inside a 'Do' statement.</source> <target state="translated">'"Exit Do" 只能出现在 "Do" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_EndWhileNoWhile"> <source>'End While' must be preceded by a matching 'While'.</source> <target state="translated">'“End While”前面必须是匹配的“While”。</target> <note /> </trans-unit> <trans-unit id="ERR_LoopNoMatchingDo"> <source>'Loop' must be preceded by a matching 'Do'.</source> <target state="translated">'"Loop" 前面必须是匹配的 "Do"。</target> <note /> </trans-unit> <trans-unit id="ERR_NextNoMatchingFor"> <source>'Next' must be preceded by a matching 'For'.</source> <target state="translated">'"Next" 前面必须是匹配的 "For"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndWithWithoutWith"> <source>'End With' must be preceded by a matching 'With'.</source> <target state="translated">'“End With”前面必须是匹配的“With”。</target> <note /> </trans-unit> <trans-unit id="ERR_MultiplyDefined1"> <source>Label '{0}' is already defined in the current method.</source> <target state="translated">当前方法中已定义了标签“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndSelect"> <source>'Select Case' must end with a matching 'End Select'.</source> <target state="translated">'“Select Case”必须以匹配的“End Select”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitForNotWithinFor"> <source>'Exit For' can only appear inside a 'For' statement.</source> <target state="translated">'"Exit For" 只能出现在 "For" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitWhileNotWithinWhile"> <source>'Exit While' can only appear inside a 'While' statement.</source> <target state="translated">'"Exit While" 只能出现在 "While" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyProperty1"> <source>'ReadOnly' property '{0}' cannot be the target of an assignment.</source> <target state="translated">'“ReadOnly”属性“{0}”不能作为赋值目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitSelectNotWithinSelect"> <source>'Exit Select' can only appear inside a 'Select' statement.</source> <target state="translated">'"Exit Select" 只能出现在 "Select" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_BranchOutOfFinally"> <source>Branching out of a 'Finally' is not valid.</source> <target state="translated">从“Finally”中分支无效。</target> <note /> </trans-unit> <trans-unit id="ERR_QualNotObjectRecord1"> <source>'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'.</source> <target state="translated">'“!”要求其左操作数具有类型参数、类或接口类型,但此操作数的类型为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TooFewIndices"> <source>Number of indices is less than the number of dimensions of the indexed array.</source> <target state="translated">索引数少于索引数组的维数。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyIndices"> <source>Number of indices exceeds the number of dimensions of the indexed array.</source> <target state="translated">索引数超过索引数组的维数。</target> <note /> </trans-unit> <trans-unit id="ERR_EnumNotExpression1"> <source>'{0}' is an Enum type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个枚举类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeNotExpression1"> <source>'{0}' is a type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassNotExpression1"> <source>'{0}' is a class type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个类类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_StructureNotExpression1"> <source>'{0}' is a structure type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个结构类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceNotExpression1"> <source>'{0}' is an interface type and cannot be used as an expression.</source> <target state="translated">“{0}”是一个接口类型,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotExpression1"> <source>'{0}' is a namespace and cannot be used as an expression.</source> <target state="translated">“{0}”是一个命名空间,不能用作表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamespaceName1"> <source>'{0}' is not a valid name and cannot be used as the root namespace name.</source> <target state="translated">“{0}”不是有效名称,不能用作根命名空间名称。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlPrefixNotExpression"> <source>'{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object.</source> <target state="translated">“{0}”是 XML 前缀,不能用作表达式。请使用 GetXmlNamespace 运算符创建命名空间对象。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleExtends"> <source>'Inherits' can appear only once within a 'Class' statement and can only specify one class.</source> <target state="translated">'"Inherits" 只能在 "Class" 语句中出现一次,并且只能指定一个类。</target> <note /> </trans-unit> <trans-unit id="ERR_PropMustHaveGetSet"> <source>Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.</source> <target state="translated">不带 "ReadOnly" 或 "WriteOnly" 说明符的属性必须同时提供 "Get" 和 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_WriteOnlyHasNoWrite"> <source>'WriteOnly' property must provide a 'Set'.</source> <target state="translated">'"WriteOnly" 属性必须提供 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyHasNoGet"> <source>'ReadOnly' property must provide a 'Get'.</source> <target state="translated">'"ReadOnly" 属性必须提供 "Get"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttribute1"> <source>Attribute '{0}' is not valid: Incorrect argument value.</source> <target state="translated">特性“{0}”无效: 参数值不正确。</target> <note /> </trans-unit> <trans-unit id="ERR_LabelNotDefined1"> <source>Label '{0}' is not defined.</source> <target state="translated">未定义标签“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorCreatingWin32ResourceFile"> <source>Error creating Win32 resources: {0}</source> <target state="translated">创建 Win32 资源时出错: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_UnableToCreateTempFile"> <source>Cannot create temporary file: {0}</source> <target state="translated">无法创建临时文件: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNewCall2"> <source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">“{1}”的基类“{0}”没有不使用参数就可以调用的可访问“Sub New”,因此该“Sub New”的第一个语句必须是对“MyBase.New”或“MyClass.New”的调用。</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedMember3"> <source>{0} '{1}' must implement '{2}' for interface '{3}'.</source> <target state="translated">{0}“{1}”必须为接口“{3}”实现“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadWithRef"> <source>Leading '.' or '!' can only appear inside a 'With' statement.</source> <target state="translated">前导“.”或“!”只能出现在“With”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAccessCategoryUsed"> <source>Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.</source> <target state="translated">只能指定 "Public"、"Private"、"Protected"、"Friend"、"Protected Friend" 或 "Private Protected" 中的一个。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateModifierCategoryUsed"> <source>Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.</source> <target state="translated">只能指定 "NotOverridable"、"MustOverride" 或 "Overridable" 中的一个。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateSpecifier"> <source>Specifier is duplicated.</source> <target state="translated">说明符重复。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeConflict6"> <source>{0} '{1}' and {2} '{3}' conflict in {4} '{5}'.</source> <target state="translated">{0}“{1}”和 {2}“{3}”在 {4}“{5}”中冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedTypeKeyword"> <source>Keyword does not name a type.</source> <target state="translated">关键字没有指定类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtraSpecifiers"> <source>Specifiers valid only at the beginning of a declaration.</source> <target state="translated">说明符仅在声明的开始处有效。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedType"> <source>Type expected.</source> <target state="translated">应为类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidUseOfKeyword"> <source>Keyword is not valid as an identifier.</source> <target state="translated">关键字作为标识符无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndEnum"> <source>'End Enum' must be preceded by a matching 'Enum'.</source> <target state="translated">'“End Enum”前面必须是匹配的“Enum”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndEnum"> <source>'Enum' must end with a matching 'End Enum'.</source> <target state="translated">'"Enum" 必须以匹配的 "End Enum" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDeclaration"> <source>Declaration expected.</source> <target state="translated">应为声明。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayMustBeLast"> <source>End of parameter list expected. Cannot define parameters after a paramarray parameter.</source> <target state="translated">应为参数列表的结尾。不能在 Paramarray 参数后定义参数。</target> <note /> </trans-unit> <trans-unit id="ERR_SpecifiersInvalidOnInheritsImplOpt"> <source>Specifiers and attributes are not valid on this statement.</source> <target state="translated">说明符和特性在此语句上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSpecifier"> <source>Expected one of 'Dim', 'Const', 'Public', 'Private', 'Protected', 'Friend', 'Shadows', 'ReadOnly' or 'Shared'.</source> <target state="translated">应为“Dim”、“Const”、“Public”、“Private”、“Protected”、“Friend”、“Shadows”、“ReadOnly”或“Shared”中的一个。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedComma"> <source>Comma expected.</source> <target state="translated">应为逗号。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAs"> <source>'As' expected.</source> <target state="translated">'应为 "As"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedRparen"> <source>')' expected.</source> <target state="translated">'应为 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLparen"> <source>'(' expected.</source> <target state="translated">'应为“(”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNewInType"> <source>'New' is not valid in this context.</source> <target state="translated">'"New" 在此上下文中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedExpression"> <source>Expression expected.</source> <target state="translated">应为表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedOptional"> <source>'Optional' expected.</source> <target state="translated">'应为 "Optional"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIdentifier"> <source>Identifier expected.</source> <target state="translated">应为标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIntLiteral"> <source>Integer constant expected.</source> <target state="translated">应为整数常量。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEOS"> <source>End of statement expected.</source> <target state="translated">应为语句结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedForOptionStmt"> <source>'Option' must be followed by 'Compare', 'Explicit', 'Infer', or 'Strict'.</source> <target state="translated">'“Option”的后面必须跟有“Compare”、“Explicit”、“Infer”或“Strict”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionCompare"> <source>'Option Compare' must be followed by 'Text' or 'Binary'.</source> <target state="translated">'"Option Compare" 的后面必须跟有 "Text" 或 "Binary"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedOptionCompare"> <source>'Compare' expected.</source> <target state="translated">'应为 "Compare"。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowImplicitObject"> <source>Option Strict On requires all variable declarations to have an 'As' clause.</source> <target state="translated">Option Strict On 要求所有变量声明都有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsImplicitProc"> <source>Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.</source> <target state="translated">Option Strict On 要求所有函数、属性和运算符声明都有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsImplicitArgs"> <source>Option Strict On requires that all method parameters have an 'As' clause.</source> <target state="translated">Option Strict On 要求所有方法参数都有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidParameterSyntax"> <source>Comma or ')' expected.</source> <target state="translated">应为逗号或 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSubFunction"> <source>'Sub' or 'Function' expected.</source> <target state="translated">'应为“Sub”或“Function”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedStringLiteral"> <source>String constant expected.</source> <target state="translated">应为字符串常量。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingLibInDeclare"> <source>'Lib' expected.</source> <target state="translated">'应为 "Lib"。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateNoInvoke1"> <source>Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call.</source> <target state="translated">委托类“{0}”没有 Invoke 方法,所以此类型的表达式不能作为方法调用的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingIsInTypeOf"> <source>'Is' expected.</source> <target state="translated">'应为 "Is"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateOption1"> <source>'Option {0}' statement can only appear once per file.</source> <target state="translated">'每个文件中只能出现一次“Option {0}”语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantInherit"> <source>'Inherits' not valid in Modules.</source> <target state="translated">'"Inherits" 在模块中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantImplement"> <source>'Implements' not valid in Modules.</source> <target state="translated">'"Implements" 在模块中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadImplementsType"> <source>Implemented type must be an interface.</source> <target state="translated">已实现的类型必须是接口。</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstFlags1"> <source>'{0}' is not valid on a constant declaration.</source> <target state="translated">“{0}”在常量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadWithEventsFlags1"> <source>'{0}' is not valid on a WithEvents declaration.</source> <target state="translated">“{0}”在 WithEvents 声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadDimFlags1"> <source>'{0}' is not valid on a member variable declaration.</source> <target state="translated">“{0}”在成员变量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateParamName1"> <source>Parameter already declared with name '{0}'.</source> <target state="translated">已用名称“{0}”声明了参数。</target> <note /> </trans-unit> <trans-unit id="ERR_LoopDoubleCondition"> <source>'Loop' cannot have a condition if matching 'Do' has one.</source> <target state="translated">'"Loop" 和匹配的 "Do" 不能同时具有条件。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedRelational"> <source>Relational operator expected.</source> <target state="translated">应为关系运算符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedExitKind"> <source>'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'.</source> <target state="translated">'“Exit”的后面必须跟有“Sub”、“Function”、“Property”、“Do”、“For”、“While”、“Select”或“Try”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedNamedArgumentInAttributeList"> <source>Named argument expected.</source> <target state="translated">应为命名参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation"> <source>Named argument specifications must appear after all fixed arguments have been specified in a late bound invocation.</source> <target state="translated">命名参数规范必须出现在已在后期绑定调用中指定的所有固定参数之后。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedNamedArgument"> <source>Named argument expected. Please use language version {0} or greater to use non-trailing named arguments.</source> <target state="translated">需要命名参数。请使用语言版本 {0} 或更高版本,以使用非尾随命名参数。</target> <note /> </trans-unit> <trans-unit id="ERR_BadMethodFlags1"> <source>'{0}' is not valid on a method declaration.</source> <target state="translated">“{0}”在方法声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadEventFlags1"> <source>'{0}' is not valid on an event declaration.</source> <target state="translated">“{0}”在事件声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadDeclareFlags1"> <source>'{0}' is not valid on a Declare.</source> <target state="translated">“{0}”在 Declare 中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadLocalConstFlags1"> <source>'{0}' is not valid on a local constant declaration.</source> <target state="translated">“{0}”在局部常量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadLocalDimFlags1"> <source>'{0}' is not valid on a local variable declaration.</source> <target state="translated">“{0}”在局部变量声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedConditionalDirective"> <source>'If', 'ElseIf', 'Else', 'Const', 'Region', 'ExternalSource', 'ExternalChecksum', 'Enable', 'Disable', 'End' or 'R' expected.</source> <target state="translated">'应为“If”、“ElseIf”、“Else”、“Const”、“Region”、“ExternalSource”、“ExternalChecksum”、“Enable”、“Disable”、“End”或“R”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEQ"> <source>'=' expected.</source> <target state="translated">'应为 "="。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorNotFound1"> <source>Type '{0}' has no constructors.</source> <target state="translated">类型“{0}”没有构造函数。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndInterface"> <source>'End Interface' must be preceded by a matching 'Interface'.</source> <target state="translated">'“End Interface”前面必须是匹配的“Interface”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndInterface"> <source>'Interface' must end with a matching 'End Interface'.</source> <target state="translated">'"Interface" 必须以匹配的 "End Interface" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFrom2"> <source> '{0}' inherits from '{1}'.</source> <target state="translated"> “{0}”从“{1}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNestedIn2"> <source> '{0}' is nested in '{1}'.</source> <target state="translated"> “{0}”嵌套在“{1}”中。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceCycle1"> <source>Class '{0}' cannot inherit from itself: {1}</source> <target state="translated">类“{0}”不能从自身继承: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromNonClass"> <source>Classes can inherit only from other classes.</source> <target state="translated">类只能从其他类继承。</target> <note /> </trans-unit> <trans-unit id="ERR_MultiplyDefinedType3"> <source>'{0}' is already declared as '{1}' in this {2}.</source> <target state="translated">“{0}”已在此 {2} 中声明为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadOverrideAccess2"> <source>'{0}' cannot override '{1}' because they have different access levels.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们具有不同的访问级别。</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNotOverridable2"> <source>'{0}' cannot override '{1}' because it is declared 'NotOverridable'.</source> <target state="translated">“{0}”无法重写“{1}”,因为后者已声明为“NotOverridable”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateProcDef1"> <source>'{0}' has multiple definitions with identical signatures.</source> <target state="translated">“{0}”具有多个带相同签名的定义。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateProcDefWithDifferentTupleNames2"> <source>'{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'.</source> <target state="translated">“{0}”具有多个带不同元组元素名称却有相同签名的定义,包括“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceMethodFlags1"> <source>'{0}' is not valid on an interface method declaration.</source> <target state="translated">“{0}”在接口方法声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamNotFound2"> <source>'{0}' is not a parameter of '{1}'.</source> <target state="translated">“{0}”不是“{1}”的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfacePropertyFlags1"> <source>'{0}' is not valid on an interface property declaration.</source> <target state="translated">“{0}”在接口属性声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgUsedTwice2"> <source>Parameter '{0}' of '{1}' already has a matching argument.</source> <target state="translated">“{1}”的参数“{0}”已有匹配的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceCantUseEventSpecifier1"> <source>'{0}' is not valid on an interface event declaration.</source> <target state="translated">“{0}”在接口事件声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_TypecharNoMatch2"> <source>Type character '{0}' does not match declared data type '{1}'.</source> <target state="translated">类型字符“{0}”与声明的数据类型“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSubOrFunction"> <source>'Sub' or 'Function' expected after 'Delegate'.</source> <target state="translated">'“Delegate”后面应为“Sub”或“Function”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmptyEnum1"> <source>Enum '{0}' must contain at least one member.</source> <target state="translated">枚举“{0}”必须至少包含一个成员。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidConstructorCall"> <source>Constructor call is valid only as the first statement in an instance constructor.</source> <target state="translated">构造函数调用仅作为实例构造函数中的第一条语句有效。</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideConstructor"> <source>'Sub New' cannot be declared 'Overrides'.</source> <target state="translated">'“Sub New”不能声明为“Overrides”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorCannotBeDeclaredPartial"> <source>'Sub New' cannot be declared 'Partial'.</source> <target state="translated">'“Sub New”不能声明为“Partial”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleEmitFailure"> <source>Failed to emit module '{0}': {1}</source> <target state="translated">未能发出模块“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_EncUpdateFailedMissingAttribute"> <source>Cannot update '{0}'; attribute '{1}' is missing.</source> <target state="translated">无法更新“{0}”;特性“{1}”缺失。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideNotNeeded3"> <source>{0} '{1}' cannot be declared 'Overrides' because it does not override a {0} in a base class.</source> <target state="translated">{0}“{1}”不能声明为“Overrides”,因为它不重写基类中的 {0}。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDot"> <source>'.' expected.</source> <target state="translated">'应为“.”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLocals1"> <source>Local variable '{0}' is already declared in the current block.</source> <target state="translated">当前块中已声明了局部变量“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsProc"> <source>Statement cannot appear within a method body. End of method assumed.</source> <target state="translated">语句不能出现在方法主体内。假定为方法末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalSameAsFunc"> <source>Local variable cannot have the same name as the function containing it.</source> <target state="translated">局部变量不能与包含它的函数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_RecordEmbeds2"> <source> '{0}' contains '{1}' (variable '{2}').</source> <target state="translated"> “{0}”包含“{1}”(变量“{2}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_RecordCycle2"> <source>Structure '{0}' cannot contain an instance of itself: {1}</source> <target state="translated">结构“{0}”不能包含自身的实例: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceCycle1"> <source>Interface '{0}' cannot inherit from itself: {1}</source> <target state="translated">接口“{0}”不能从自身继承: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_SubNewCycle2"> <source> '{0}' calls '{1}'.</source> <target state="translated"> “{0}”调用“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SubNewCycle1"> <source>Constructor '{0}' cannot call itself: {1}</source> <target state="translated">构造函数“{0}”不能调用自身: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromCantInherit3"> <source>'{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'.</source> <target state="translated">“{1}”已声明为“NotInheritable”,因此“{0}”无法从 {2}“{1}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithOptional2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by optional parameters.</source> <target state="translated">“{0}” 和“{1}”的差异仅在于可选参数,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithReturnType2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by return types.</source> <target state="translated">“{0}”和“{1}”的差异仅在于返回类型,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharWithType1"> <source>Type character '{0}' cannot be used in a declaration with an explicit type.</source> <target state="translated">在具有显式类型的声明中不能使用类型字符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharOnSub"> <source>Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.</source> <target state="translated">"Sub" 不返回值,因此在 "Sub" 声明中不能使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithDefault2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters.</source> <target state="translated">“{0}”和“{1}”的差异仅在于可选参数的默认值,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingSubscript"> <source>Array subscript expression missing.</source> <target state="translated">缺少数组下标表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithDefault2"> <source>'{0}' cannot override '{1}' because they differ by the default values of optional parameters.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在可选参数的默认值上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithOptional2"> <source>'{0}' cannot override '{1}' because they differ by optional parameters.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在可选参数上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_FieldOfValueFieldOfMarshalByRef3"> <source>Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class.</source> <target state="translated">“{0}”,是使用“System.MarshalByRefObject”作为基类的类“{2}”的值类型字段“{1}”的成员,无法引用。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeMismatch2"> <source>Value of type '{0}' cannot be converted to '{1}'.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_CaseAfterCaseElse"> <source>'Case' cannot follow a 'Case Else' in the same 'Select' statement.</source> <target state="translated">'在同一“Select”语句中,“Case”不能位于“Case Else”之后。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertArrayMismatch4"> <source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”,因为“{2}”不是从“{3}”派生的。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertObjectArrayMismatch3"> <source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”,因为“{2}”不是引用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ForLoopType1"> <source>'For' loop control variable cannot be of type '{0}' because the type does not support the required operators.</source> <target state="translated">'“For”循环控制变量的类型不能是“{0}”,因为该类型不支持所需的运算符。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithByref2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.</source> <target state="translated">“{0}”和“{1}”的差异仅在于声明为“ByRef”或“ByVal”的参数,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsFromNonInterface"> <source>Interface can inherit only from another interface.</source> <target state="translated">接口只能从其他接口继承。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceOrderOnInherits"> <source>'Inherits' statements must precede all declarations in an interface.</source> <target state="translated">'“Inherits”语句必须位于接口中的所有声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateDefaultProps1"> <source>'Default' can be applied to only one property name in a {0}.</source> <target state="translated">'“Default”只可应用于“{0}”中的一个属性名称。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultMissingFromProperty2"> <source>'{0}' and '{1}' cannot overload each other because only one is declared 'Default'.</source> <target state="translated">“{0}”和“{1}”中只有一个声明为“Default”,因此它们无法相互重载。</target> <note /> </trans-unit> <trans-unit id="ERR_OverridingPropertyKind2"> <source>'{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在是“ReadOnly”还是“WriteOnly”上不同。</target> <note /> </trans-unit> <trans-unit id="ERR_NewInInterface"> <source>'Sub New' cannot be declared in an interface.</source> <target state="translated">'"Sub New" 不能在接口中声明。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnNew1"> <source>'Sub New' cannot be declared '{0}'.</source> <target state="translated">'“Sub New”不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadingPropertyKind2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.</source> <target state="translated">“{0}” 和“{1}”的差异仅在于“ReadOnly”和“WriteOnly”,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_NoDefaultNotExtend1"> <source>Class '{0}' cannot be indexed because it has no default property.</source> <target state="translated">无法为类“{0}”编制索引,因为它没有默认属性。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadWithArrayVsParamArray2"> <source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'.</source> <target state="translated">“{0}”和“{1}”的差异仅在于声明为 "ParamArray" 的参数,因此它们无法重载对方。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInstanceMemberAccess"> <source>Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.</source> <target state="translated">没有类的显式实例,就无法从共享方法或共享成员初始值设定项中引用该类的实例成员。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedRbrace"> <source>'}' expected.</source> <target state="translated">'应为 "}"。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleAsType1"> <source>Module '{0}' cannot be used as a type.</source> <target state="translated">模块“{0}”不能用作类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NewIfNullOnNonClass"> <source>'New' cannot be used on an interface.</source> <target state="translated">'"New"不能在接口上使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchAfterFinally"> <source>'Catch' cannot appear after 'Finally' within a 'Try' statement.</source> <target state="translated">'在“Try”语句中,“Catch”不能出现在“Finally”之后。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchNoMatchingTry"> <source>'Catch' cannot appear outside a 'Try' statement.</source> <target state="translated">'“Catch”不能出现在“Try”语句之外。</target> <note /> </trans-unit> <trans-unit id="ERR_FinallyAfterFinally"> <source>'Finally' can only appear once in a 'Try' statement.</source> <target state="translated">'“Finally”只能在“Try”语句中出现一次。</target> <note /> </trans-unit> <trans-unit id="ERR_FinallyNoMatchingTry"> <source>'Finally' cannot appear outside a 'Try' statement.</source> <target state="translated">'“Finally”不能出现在“Try”语句之外。</target> <note /> </trans-unit> <trans-unit id="ERR_EndTryNoTry"> <source>'End Try' must be preceded by a matching 'Try'.</source> <target state="translated">'“End Try”前面必须是匹配的“Try”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndTry"> <source>'Try' must end with a matching 'End Try'.</source> <target state="translated">'“Try”必须以匹配的“End Try”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelegateFlags1"> <source>'{0}' is not valid on a Delegate declaration.</source> <target state="translated">“{0}”在委托声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NoConstructorOnBase2"> <source>Class '{0}' must declare a 'Sub New' because its base class '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,原因是它的基类“{1}”没有不使用参数就可以调用的可访问“Sub New”。</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleSymbol2"> <source>'{0}' is not accessible in this context because it is '{1}'.</source> <target state="translated">“{0}”是“{1}”,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleMember3"> <source>'{0}.{1}' is not accessible in this context because it is '{2}'.</source> <target state="translated">“{0}.{1}”是“{2}” ,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchNotException1"> <source>'Catch' cannot catch type '{0}' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.</source> <target state="translated">'“Catch”无法捕捉类型“{0}”,因为该类型既不是“System.Exception”也不是从“System.Exception”继承的类。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitTryNotWithinTry"> <source>'Exit Try' can only appear inside a 'Try' statement.</source> <target state="translated">'"Exit Try" 只能出现在 "Try" 语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_BadRecordFlags1"> <source>'{0}' is not valid on a Structure declaration.</source> <target state="translated">“{0}”在结构声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadEnumFlags1"> <source>'{0}' is not valid on an Enum declaration.</source> <target state="translated">“{0}”在枚举声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceFlags1"> <source>'{0}' is not valid on an Interface declaration.</source> <target state="translated">“{0}”在接口声明中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithByref2"> <source>'{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在某个参数上存在差异,一个被标记为“ByRef”,而另一个被标记为“ByVal”。</target> <note /> </trans-unit> <trans-unit id="ERR_MyBaseAbstractCall1"> <source>'MyBase' cannot be used with method '{0}' because it is declared 'MustOverride'.</source> <target state="translated">'“MyBase”不能用和方法“{0}”一起使用,因为它被声明为“MustOverride”。</target> <note /> </trans-unit> <trans-unit id="ERR_IdentNotMemberOfInterface4"> <source>'{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'.</source> <target state="translated">“{0}”无法实现“{1}”,因为接口“{3}”上不存在匹配的 {2}。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementingInterfaceWithDifferentTupleNames5"> <source>'{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'.</source> <target state="translated">“{0}”不能在接口“{3}”上实现{1}“{2}”,因为“{4}”中的元组元素名称与“{5}”中的名称不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_WithEventsRequiresClass"> <source>'WithEvents' variables must have an 'As' clause.</source> <target state="translated">'"WithEvents" 变量必须有 "As" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_WithEventsAsStruct"> <source>'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.</source> <target state="translated">'"WithEvents" 变量只能类型化为具有类约束的类、接口或类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertArrayRankMismatch2"> <source>Value of type '{0}' cannot be converted to '{1}' because the array types have different numbers of dimensions.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”,原因是数组类型的维数不同。</target> <note /> </trans-unit> <trans-unit id="ERR_RedimRankMismatch"> <source>'ReDim' cannot change the number of dimensions of an array.</source> <target state="translated">'"ReDim" 无法更改数组的维数。</target> <note /> </trans-unit> <trans-unit id="ERR_StartupCodeNotFound1"> <source>'Sub Main' was not found in '{0}'.</source> <target state="translated">“{0}”中找不到“Sub Main”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstAsNonConstant"> <source>Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.</source> <target state="translated">常量必须是内部类型或者枚举类型,不能是类、结构、类型参数或数组类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndSub"> <source>'End Sub' must be preceded by a matching 'Sub'.</source> <target state="translated">'“End Sub”前面必须是匹配的“Sub”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndFunction"> <source>'End Function' must be preceded by a matching 'Function'.</source> <target state="translated">'“End Function”前面必须是匹配的“Function”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndProperty"> <source>'End Property' must be preceded by a matching 'Property'.</source> <target state="translated">'“End Property”前面必须是匹配的“Property”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseMethodSpecifier1"> <source>Methods in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的方法不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseEventSpecifier1"> <source>Events in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的事件不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StructCantUseVarSpecifier1"> <source>Members in a Structure cannot be declared '{0}'.</source> <target state="translated">结构中的成员不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOverrideDueToReturn2"> <source>'{0}' cannot override '{1}' because they differ by their return types.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们的返回类型不同。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidOverrideDueToTupleNames2"> <source>'{0}' cannot override '{1}' because they differ by their tuple element names.</source> <target state="translated">“{0}”不能替代“{1}”,因为它们的元组元素名称不同。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidOverrideDueToTupleNames2_Title"> <source>Member cannot override because it differs by its tuple element names.</source> <target state="translated">成员不能替代,因为它的元组元素名称不同。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantWithNoValue"> <source>Constants must have a value.</source> <target state="translated">常量必须具有值。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionOverflow1"> <source>Constant expression not representable in type '{0}'.</source> <target state="translated">常量表达式无法在类型“{0}”中表示。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertyGet"> <source>'Get' is already declared.</source> <target state="translated">'已声明 "Get"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertySet"> <source>'Set' is already declared.</source> <target state="translated">'已声明 "Set"。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotDeclared1"> <source>'{0}' is not declared. It may be inaccessible due to its protection level.</source> <target state="translated">'未声明“{0}”。由于其保护级别,它可能无法访问。</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryOperands3"> <source>Operator '{0}' is not defined for types '{1}' and '{2}'.</source> <target state="translated">没有为类型“{1}”和“{2}”定义运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedProcedure"> <source>Expression is not a method.</source> <target state="translated">表达式不是方法。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedArgument2"> <source>Argument not specified for parameter '{0}' of '{1}'.</source> <target state="translated">没有为“{1}”的形参“{0}”指定实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotMember2"> <source>'{0}' is not a member of '{1}'.</source> <target state="translated">“{0}”不是“{1}”的成员。</target> <note /> </trans-unit> <trans-unit id="ERR_EndClassNoClass"> <source>'End Class' must be preceded by a matching 'Class'.</source> <target state="translated">'"End Class" 前面必须是匹配的 "Class"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadClassFlags1"> <source>Classes cannot be declared '{0}'.</source> <target state="translated">类不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ImportsMustBeFirst"> <source>'Imports' statements must precede any declarations.</source> <target state="translated">'“Imports”语句前面必须是声明。</target> <note /> </trans-unit> <trans-unit id="ERR_NonNamespaceOrClassOnImport2"> <source>'{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module.</source> <target state="translated">'Imports “{0}”的“{1}”不引用命名空间、类、结构、枚举或模块。</target> <note /> </trans-unit> <trans-unit id="ERR_TypecharNotallowed"> <source>Type declaration characters are not valid in this context.</source> <target state="translated">类型声明字符在此上下文中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectReferenceNotSupplied"> <source>Reference to a non-shared member requires an object reference.</source> <target state="translated">对非共享成员的引用要求对象引用。</target> <note /> </trans-unit> <trans-unit id="ERR_MyClassNotInClass"> <source>'MyClass' cannot be used outside of a class.</source> <target state="translated">'"MyClass" 不能在类的外部使用。</target> <note /> </trans-unit> <trans-unit id="ERR_IndexedNotArrayOrProc"> <source>Expression is not an array or a method, and cannot have an argument list.</source> <target state="translated">表达式不是数组或方法,不能具有参数列表。</target> <note /> </trans-unit> <trans-unit id="ERR_EventSourceIsArray"> <source>'WithEvents' variables cannot be typed as arrays.</source> <target state="translated">'“WithEvents”变量不能类型化为数组。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedConstructorWithParams"> <source>Shared 'Sub New' cannot have any parameters.</source> <target state="translated">共享的 "Sub New" 不能具有任何参数。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedConstructorIllegalSpec1"> <source>Shared 'Sub New' cannot be declared '{0}'.</source> <target state="translated">共享的“Sub New”不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndClass"> <source>'Class' statement must end with a matching 'End Class'.</source> <target state="translated">'“Class”语句必须以匹配的“End Class”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_UnaryOperand2"> <source>Operator '{0}' is not defined for type '{1}'.</source> <target state="translated">没有为类型“{1}”定义运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsWithDefault1"> <source>'Default' cannot be combined with '{0}'.</source> <target state="translated">'“Default”不能与“{0}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_VoidValue"> <source>Expression does not produce a value.</source> <target state="translated">表达式不产生值。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorFunction"> <source>Constructor must be declared as a Sub, not as a Function.</source> <target state="translated">构造函数必须声明为 Sub,而不是 Function。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidLiteralExponent"> <source>Exponent is not valid.</source> <target state="translated">指数无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NewCannotHandleEvents"> <source>'Sub New' cannot handle events.</source> <target state="translated">'"Sub New" 无法处理事件。</target> <note /> </trans-unit> <trans-unit id="ERR_CircularEvaluation1"> <source>Constant '{0}' cannot depend on its own value.</source> <target state="translated">常量“{0}”不能依赖自身的值。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnSharedMeth1"> <source>'Shared' cannot be combined with '{0}' on a method declaration.</source> <target state="translated">'“Shared”不能与方法声明上的“{0}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnSharedProperty1"> <source>'Shared' cannot be combined with '{0}' on a property declaration.</source> <target state="translated">'“Shared”不能与属性声明上的“{0}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnStdModuleProperty1"> <source>Properties in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的属性不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedOnProcThatImpl"> <source>Methods or events that implement interface members cannot be declared 'Shared'.</source> <target state="translated">实现接口成员的方法或事件不能声明为 "Shared"。</target> <note /> </trans-unit> <trans-unit id="ERR_NoWithEventsVarOnHandlesList"> <source>Handles clause requires a WithEvents variable defined in the containing type or one of its base types.</source> <target state="translated">Handles 子句要求一个在包含类型或它的某个基类型中定义的 WithEvents 变量。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceAccessMismatch5"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'.</source> <target state="translated">“{0}”将对基 {1} 的访问扩展到 {3}“{4}”,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_NarrowingConversionDisallowed2"> <source>Option Strict On disallows implicit conversions from '{0}' to '{1}'.</source> <target state="translated">Option Strict On 不允许从“{0}”到“{1}”的隐式转换。</target> <note /> </trans-unit> <trans-unit id="ERR_NoArgumentCountOverloadCandidates1"> <source>Overload resolution failed because no accessible '{0}' accepts this number of arguments.</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”接受此数目的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NoViableOverloadCandidates1"> <source>Overload resolution failed because no '{0}' is accessible.</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoCallableOverloadCandidates2"> <source>Overload resolution failed because no accessible '{0}' can be called with these arguments:{1}</source> <target state="translated">重载决策失败,因为没有可使用这些参数调用的可访问“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadOverloadCandidates2"> <source>Overload resolution failed because no accessible '{0}' can be called:{1}</source> <target state="translated">重载决策失败,原因是没有可访问的“{0}”可以进行调用:{1}</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonNarrowingOverloadCandidates2"> <source>Overload resolution failed because no accessible '{0}' can be called without a narrowing conversion:{1}</source> <target state="translated">重载决策失败,因为没有不使用收缩转换即可调用的可访问重载“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentNarrowing3"> <source>Argument matching parameter '{0}' narrows from '{1}' to '{2}'.</source> <target state="translated">与形参“{0}”匹配的实参从“{1}”收缩到“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoMostSpecificOverload2"> <source>Overload resolution failed because no accessible '{0}' is most specific for these arguments:{1}</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”最适合这些参数: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_NotMostSpecificOverload"> <source>Not most specific.</source> <target state="translated">不是最适合。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadCandidate2"> <source> '{0}': {1}</source> <target state="translated"> “{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_NoGetProperty1"> <source>Property '{0}' is 'WriteOnly'.</source> <target state="translated">属性“{0}”为“WriteOnly”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoSetProperty1"> <source>Property '{0}' is 'ReadOnly'.</source> <target state="translated">属性“{0}”为“ReadOnly”。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamTypingInconsistency"> <source>All parameters must be explicitly typed if any of them are explicitly typed.</source> <target state="translated">如果任何一个参数已显式类型化,则所有参数都必须显式类型化。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamNameFunctionNameCollision"> <source>Parameter cannot have the same name as its defining function.</source> <target state="translated">参数不能与它的定义函数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_DateToDoubleConversion"> <source>Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method.</source> <target state="translated">从“Date”到“Double”的转换需要调用“Date.ToOADate”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DoubleToDateConversion"> <source>Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method.</source> <target state="translated">从 "Double" 到 "Date" 的转换需要调用 "Date.FromOADate" 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ZeroDivide"> <source>Division by zero occurred while evaluating this expression.</source> <target state="translated">计算此表达式时出现被零除的情况。</target> <note /> </trans-unit> <trans-unit id="ERR_TryAndOnErrorDoNotMix"> <source>Method cannot contain both a 'Try' statement and an 'On Error' or 'Resume' statement.</source> <target state="translated">方法不能既包含 "Try" 语句,又包含 "On Error" 或 "Resume" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyAccessIgnored"> <source>Property access must assign to the property or use its value.</source> <target state="translated">属性访问必须分配给属性或使用属性值。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceNoDefault1"> <source>'{0}' cannot be indexed because it has no default property.</source> <target state="translated">'无法为“{0}”编制索引,因为它没有默认属性。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyAttribute1"> <source>Attribute '{0}' cannot be applied to an assembly.</source> <target state="translated">属性“{0}”不能应用于程序集。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidModuleAttribute1"> <source>Attribute '{0}' cannot be applied to a module.</source> <target state="translated">属性“{0}”不能应用于模块。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInUnnamedNamespace1"> <source>'{0}' is ambiguous.</source> <target state="translated">“{0}”不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultMemberNotProperty1"> <source>Default member of '{0}' is not a property.</source> <target state="translated">“{0}”的默认成员不是属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInNamespace2"> <source>'{0}' is ambiguous in the namespace '{1}'.</source> <target state="translated">“{1}”在命名空间中“{0}”不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInImports2"> <source>'{0}' is ambiguous, imported from the namespaces or types '{1}'.</source> <target state="translated">“{0}”不明确,从命名空间或类型“{1}”导入。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInModules2"> <source>'{0}' is ambiguous between declarations in Modules '{1}'.</source> <target state="translated">“{0}”在模块“{1}”中的声明之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousInNamespaces2"> <source>'{0}' is ambiguous between declarations in namespaces '{1}'.</source> <target state="translated">“{0}”在命名空间“{1}”中的声明之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerTooFewDimensions"> <source>Array initializer has too few dimensions.</source> <target state="translated">数组初始值设定项的维数太少。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerTooManyDimensions"> <source>Array initializer has too many dimensions.</source> <target state="translated">数组初始值设定项的维数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerTooFewElements1"> <source>Array initializer is missing {0} elements.</source> <target state="translated">数组初始值设定项缺少 {0} 个元素。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerTooManyElements1"> <source>Array initializer has {0} too many elements.</source> <target state="translated">数组初始值设定项拥有的元素太多({0}个)。</target> <note /> </trans-unit> <trans-unit id="ERR_NewOnAbstractClass"> <source>'New' cannot be used on a class that is declared 'MustInherit'.</source> <target state="translated">'"New" 不能在声明为 "MustInherit" 的类上使用。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNamedImportAlias1"> <source>Alias '{0}' is already declared.</source> <target state="translated">已声明别名“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePrefix"> <source>XML namespace prefix '{0}' is already declared.</source> <target state="translated">已声明 XML 命名空间前缀“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsLateBinding"> <source>Option Strict On disallows late binding.</source> <target state="translated">Option Strict On 不允许后期绑定。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfOperandNotMethod"> <source>'AddressOf' operand must be the name of a method (without parentheses).</source> <target state="translated">'“AddressOf”操作数必须是某个方法的名称(不带圆括号)。</target> <note /> </trans-unit> <trans-unit id="ERR_EndExternalSource"> <source>'#End ExternalSource' must be preceded by a matching '#ExternalSource'.</source> <target state="translated">'"#End ExternalSource" 前面必须是匹配的 "#ExternalSource"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndExternalSource"> <source>'#ExternalSource' statement must end with a matching '#End ExternalSource'.</source> <target state="translated">'“#ExternalSource”语句必须以匹配的“#End ExternalSource”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedExternalSource"> <source>'#ExternalSource' directives cannot be nested.</source> <target state="translated">'"#ExternalSource" 指令不能嵌套。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfNotDelegate1"> <source>'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source> <target state="translated">'“AddressOf”表达式无法转换为“{0} ”,因为“{0}”不是委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_SyncLockRequiresReferenceType1"> <source>'SyncLock' operand cannot be of type '{0}' because '{0}' is not a reference type.</source> <target state="translated">'"SyncLock" 操作数不能是“{0}”类型,因为“{0}”不是引用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodAlreadyImplemented2"> <source>'{0}.{1}' cannot be implemented more than once.</source> <target state="translated">“{0}.{1}”不能多次实现。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInInherits1"> <source>'{0}' cannot be inherited more than once.</source> <target state="translated">“{0}”不能被继承多次。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamArrayArgument"> <source>Named argument cannot match a ParamArray parameter.</source> <target state="translated">命名实参不能匹配 ParamArray 形参。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedParamArrayArgument"> <source>Omitted argument cannot match a ParamArray parameter.</source> <target state="translated">省略的实参不能匹配 ParamArray 形参。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayArgumentMismatch"> <source>Argument cannot match a ParamArray parameter.</source> <target state="translated">参数不能匹配 ParamArray 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_EventNotFound1"> <source>Event '{0}' cannot be found.</source> <target state="translated">找不到事件“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseVariableSpecifier1"> <source>Variables in Modules cannot be declared '{0}'.</source> <target state="translated">模块中的变量不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedEventNeedsSharedHandler"> <source>Events of shared WithEvents variables cannot be handled by non-shared methods.</source> <target state="translated">共享 WithEvents 变量的事件不能由非共享方法处理。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedMinus"> <source>'-' expected.</source> <target state="translated">'应为“-”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceMemberSyntax"> <source>Interface members must be methods, properties, events, or type definitions.</source> <target state="translated">接口成员必须是方法、属性、事件或类型定义。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideInterface"> <source>Statement cannot appear within an interface body.</source> <target state="translated">语句不能出现在接口体内。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsInterface"> <source>Statement cannot appear within an interface body. End of interface assumed.</source> <target state="translated">语句不能出现在接口体内。假定为接口末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsInNotInheritableClass1"> <source>'NotInheritable' classes cannot have members declared '{0}'.</source> <target state="translated">'“NotInheritable”类不能有声明为“{0}”的成员。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseOnlyClassesMustBeExplicit2"> <source>Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}.</source> <target state="translated">类“{0}”必须声明为“MustInherit”或重写以下继承的“MustOverride”成员: {1}。</target> <note /> </trans-unit> <trans-unit id="ERR_MustInheritEventNotOverridden"> <source>'{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit.</source> <target state="translated">“{0}”是基类“{1}” 中的 MustOverride 事件。Visual Basic 不支持事件替代。必须提供基类中事件的实现或让类“{2}“成为 MustInherit。</target> <note /> </trans-unit> <trans-unit id="ERR_NegativeArraySize"> <source>Array dimensions cannot have a negative size.</source> <target state="translated">数组维数的大小不能为负。</target> <note /> </trans-unit> <trans-unit id="ERR_MyClassAbstractCall1"> <source>'MustOverride' method '{0}' cannot be called with 'MyClass'.</source> <target state="translated">'无法用“MyClass”调用“MustOverride”方法“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_EndDisallowedInDllProjects"> <source>'End' statement cannot be used in class library projects.</source> <target state="translated">'在类库项目中不能使用 "End" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_BlockLocalShadowing1"> <source>Variable '{0}' hides a variable in an enclosing block.</source> <target state="translated">变量“{0}”在封闭块中隐藏变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleNotAtNamespace"> <source>'Module' statements can occur only at file or namespace level.</source> <target state="translated">'"Module" 语句只能出现在文件级或命名空间级。</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotAtNamespace"> <source>'Namespace' statements can occur only at file or namespace level.</source> <target state="translated">'"Namespace" 语句只能出现在文件级或命名空间级。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEnum"> <source>Statement cannot appear within an Enum body.</source> <target state="translated">语句不能出现在枚举体内。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsEnum"> <source>Statement cannot appear within an Enum body. End of Enum assumed.</source> <target state="translated">语句不能出现在枚举体内。假定已到达枚举末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionStrict"> <source>'Option Strict' can be followed only by 'On' or 'Off'.</source> <target state="translated">'"Option Strict" 的后面只能跟 "On" 或 "Off"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndStructureNoStructure"> <source>'End Structure' must be preceded by a matching 'Structure'.</source> <target state="translated">'"End Structure" 前面必须是匹配的 "Structure"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndModuleNoModule"> <source>'End Module' must be preceded by a matching 'Module'.</source> <target state="translated">'"End Module" 前面必须是匹配的 "Module"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndNamespaceNoNamespace"> <source>'End Namespace' must be preceded by a matching 'Namespace'.</source> <target state="translated">'"End Namespace" 前面必须是匹配的 "Namespace"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndStructure"> <source>'Structure' statement must end with a matching 'End Structure'.</source> <target state="translated">'“Structure”语句必须以匹配的“End Structure”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndModule"> <source>'Module' statement must end with a matching 'End Module'.</source> <target state="translated">'“Module”语句必须以匹配的“End Module”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndNamespace"> <source>'Namespace' statement must end with a matching 'End Namespace'.</source> <target state="translated">'“Namespace”语句必须以匹配的“End Namespace”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_OptionStmtWrongOrder"> <source>'Option' statements must precede any declarations or 'Imports' statements.</source> <target state="translated">'"Option" 语句必须位于任何声明或 "Imports" 语句之前。</target> <note /> </trans-unit> <trans-unit id="ERR_StructCantInherit"> <source>Structures cannot have 'Inherits' statements.</source> <target state="translated">结构不能有 "Inherits" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_NewInStruct"> <source>Structures cannot declare a non-shared 'Sub New' with no parameters.</source> <target state="translated">结构不能声明没有参数的非共享 "Sub New"。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndGet"> <source>'End Get' must be preceded by a matching 'Get'.</source> <target state="translated">'“End Get”前面必须是匹配的“Get”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndGet"> <source>'Get' statement must end with a matching 'End Get'.</source> <target state="translated">'"Get" 语句必须以匹配的 "End Get" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndSet"> <source>'End Set' must be preceded by a matching 'Set'.</source> <target state="translated">'“End Set”前面必须是匹配的“Set”。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndSet"> <source>'Set' statement must end with a matching 'End Set'.</source> <target state="translated">'"Set" 语句必须以匹配的 "End Set" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsProperty"> <source>Statement cannot appear within a property body. End of property assumed.</source> <target state="translated">语句不能出现在属性体内。假定为属性末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateWriteabilityCategoryUsed"> <source>'ReadOnly' and 'WriteOnly' cannot be combined.</source> <target state="translated">'"ReadOnly" 不能与 "WriteOnly" 组合。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedGreater"> <source>'&gt;' expected.</source> <target state="translated">'应为“&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeStmtWrongOrder"> <source>Assembly or Module attribute statements must precede any declarations in a file.</source> <target state="translated">Assembly 或 Module 特性语句必须位于文件中的任何声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_NoExplicitArraySizes"> <source>Array bounds cannot appear in type specifiers.</source> <target state="translated">数组界限不能出现在类型说明符中。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyFlags1"> <source>Properties cannot be declared '{0}'.</source> <target state="translated">属性不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionExplicit"> <source>'Option Explicit' can be followed only by 'On' or 'Off'.</source> <target state="translated">'"Option Explicit" 的后面只能跟 "On" 或 "Off"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleParameterSpecifiers"> <source>'ByVal' and 'ByRef' cannot be combined.</source> <target state="translated">'“ByVal”不能与“ByRef”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleOptionalParameterSpecifiers"> <source>'Optional' and 'ParamArray' cannot be combined.</source> <target state="translated">"Optional" 不能与 "ParamArray" 组合。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedProperty1"> <source>Property '{0}' is of an unsupported type.</source> <target state="translated">属性“{0}”的类型不受支持。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionalParameterUsage1"> <source>Attribute '{0}' cannot be applied to a method with optional parameters.</source> <target state="translated">属性“{0}”不能应用于具有可选参数的方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnFromNonFunction"> <source>'Return' statement in a Sub or a Set cannot return a value.</source> <target state="translated">'Sub 或 Set 中的 "Return" 语句不能返回值。</target> <note /> </trans-unit> <trans-unit id="ERR_UnterminatedStringLiteral"> <source>String constants must end with a double quote.</source> <target state="translated">字符串常量必须以双引号结束。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedType1"> <source>'{0}' is an unsupported type.</source> <target state="translated">“{0}”是不受支持的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEnumBase"> <source>Enums must be declared as an integral type.</source> <target state="translated">枚举必须声明为整型。</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefIllegal1"> <source>{0} parameters cannot be declared 'ByRef'.</source> <target state="translated">{0} 参数不能声明为“ByRef”。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedAssembly3"> <source>Reference required to assembly '{0}' containing the type '{1}'. Add one to your project.</source> <target state="translated">需要对程序集“{0}”(包含类型“{1}”)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_UnreferencedModule3"> <source>Reference required to module '{0}' containing the type '{1}'. Add one to your project.</source> <target state="translated">需要对模块“{0}”(包含类型“{1}”)的引用。请在项目中添加一个。</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnWithoutValue"> <source>'Return' statement in a Function, Get, or Operator must return a value.</source> <target state="translated">'Function、Get 或 Operator 中的 "Return" 语句必须返回值。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedField1"> <source>Field '{0}' is of an unsupported type.</source> <target state="translated">字段“{0}”的类型不受支持。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedMethod1"> <source>'{0}' has a return type that is not supported or parameter types that are not supported.</source> <target state="translated">“{0}”有不受支持的返回类型或不受支持的参数类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonIndexProperty1"> <source>Property '{0}' with no parameters cannot be found.</source> <target state="translated">无法找到不带参数的属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributePropertyType1"> <source>Property or field '{0}' does not have a valid attribute type.</source> <target state="translated">属性或字段“{0}”没有有效的特性类型。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalsCannotHaveAttributes"> <source>Attributes cannot be applied to local variables.</source> <target state="translated">特性不能应用于局部变量。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyOrFieldNotDefined1"> <source>Field or property '{0}' is not found.</source> <target state="translated">找不到字段或属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeUsage2"> <source>Attribute '{0}' cannot be applied to '{1}' because the attribute is not valid on this declaration type.</source> <target state="translated">属性“{0}”不能应用于“{1}”,因为该属性在此声明类型中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeUsageOnAccessor"> <source>Attribute '{0}' cannot be applied to '{1}' of '{2}' because the attribute is not valid on this declaration type.</source> <target state="translated">属性“{0}”不能应用于“{2}”的“{1}”,因为该属性在此声明类型中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedTypeInInheritsClause2"> <source>Class '{0}' cannot reference its nested type '{1}' in Inherits clause.</source> <target state="translated">类“{0}”无法在 Inherits 子句中引用其嵌套类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInItsInheritsClause1"> <source>Class '{0}' cannot reference itself in Inherits clause.</source> <target state="translated">类“{0}”不能在 Inherits 子句中引用自己。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseTypeReferences2"> <source> Base type of '{0}' needs '{1}' to be resolved.</source> <target state="translated"> “{0}”基类型需要解析“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalBaseTypeReferences3"> <source>Inherits clause of {0} '{1}' causes cyclic dependency: {2}</source> <target state="translated">{0}“{1}”的继承子句会导致循环依赖: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMultipleAttributeUsage1"> <source>Attribute '{0}' cannot be applied multiple times.</source> <target state="translated">属性“{0}”不能应用多次。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMultipleAttributeUsageInNetModule2"> <source>Attribute '{0}' in '{1}' cannot be applied multiple times.</source> <target state="translated">“{1}”中的属性“{0}”不能应用多次。</target> <note /> </trans-unit> <trans-unit id="ERR_CantThrowNonException"> <source>'Throw' operand must derive from 'System.Exception'.</source> <target state="translated">'“Throw”操作数必须从“System.Exception”派生。</target> <note /> </trans-unit> <trans-unit id="ERR_MustBeInCatchToRethrow"> <source>'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.</source> <target state="translated">'"Throw" 语句在 "Catch" 语句外或 "Finally" 语句内不能省略操作数。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayMustBeByVal"> <source>ParamArray parameters must be declared 'ByVal'.</source> <target state="translated">ParamArray 参数必须声明为 "ByVal"。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoleteSymbol2"> <source>'{0}' is obsolete: '{1}'.</source> <target state="translated">“{0}”已过时:“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_RedimNoSizes"> <source>'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.</source> <target state="translated">"ReDim" 语句需要一个带圆括号的列表,该列表列出数组每个维度的新界限。</target> <note /> </trans-unit> <trans-unit id="ERR_InitWithMultipleDeclarators"> <source>Explicit initialization is not permitted with multiple variables declared with a single type specifier.</source> <target state="translated">不允许通过用单个类型说明符声明多个变量来进行显式初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_InitWithExplicitArraySizes"> <source>Explicit initialization is not permitted for arrays declared with explicit bounds.</source> <target state="translated">对于用显式界限声明的数组不允许进行显式初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_EndSyncLockNoSyncLock"> <source>'End SyncLock' must be preceded by a matching 'SyncLock'.</source> <target state="translated">'“End SyncLock”前面必须是匹配的“SyncLock”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndSyncLock"> <source>'SyncLock' statement must end with a matching 'End SyncLock'.</source> <target state="translated">'“SyncLock”语句必须以匹配的“End SyncLock”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotEvent2"> <source>'{0}' is not an event of '{1}'.</source> <target state="translated">“{0}”不是“{1}”的事件。</target> <note /> </trans-unit> <trans-unit id="ERR_AddOrRemoveHandlerEvent"> <source>'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.</source> <target state="translated">'“AddHandler”或“RemoveHandler”语句事件操作数必须是以点限定的表达式或者是简单的名称。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedEnd"> <source>'End' statement not valid.</source> <target state="translated">'"End" 语句无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitForNonArray2"> <source>Array initializers are valid only for arrays, but the type of '{0}' is '{1}'.</source> <target state="translated">数组初始值设定项仅对数组有效,但“{0}”的类型是“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_EndRegionNoRegion"> <source>'#End Region' must be preceded by a matching '#Region'.</source> <target state="translated">'"#End Region" 前面必须是匹配的 "#Region"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndRegion"> <source>'#Region' statement must end with a matching '#End Region'.</source> <target state="translated">'"#Region" 语句必须以匹配的 "#End Region" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsStmtWrongOrder"> <source>'Inherits' statement must precede all declarations in a class.</source> <target state="translated">'“Inherits”语句必须位于类中的所有声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousAcrossInterfaces3"> <source>'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'.</source> <target state="translated">“{0}”在继承接口“{1}”和“{2}”之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultPropertyAmbiguousAcrossInterfaces4"> <source>Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'.</source> <target state="translated">默认属性访问在接口“{1}”的继承接口成员“{0}”和接口“{3}”的继承接口成员“{2}”之间不明确。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceEventCantUse1"> <source>Events in interfaces cannot be declared '{0}'.</source> <target state="translated">接口中的事件无法声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExecutableAsDeclaration"> <source>Statement cannot appear outside of a method body.</source> <target state="translated">语句不能出现在方法主体外。</target> <note /> </trans-unit> <trans-unit id="ERR_StructureNoDefault1"> <source>Structure '{0}' cannot be indexed because it has no default property.</source> <target state="translated">无法为结构“{0}”编制索引,因为它没有默认属性。</target> <note /> </trans-unit> <trans-unit id="ERR_MustShadow2"> <source>{0} '{1}' must be declared 'Shadows' because another member with this name is declared 'Shadows'.</source> <target state="translated">{0}“{1}”必须声明为“Shadows”,因为具有此名称的另一个成员被声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithOptionalTypes2"> <source>'{0}' cannot override '{1}' because they differ by the types of optional parameters.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在可选参数类型上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndOfExpression"> <source>End of expression expected.</source> <target state="translated">应为表达式结尾。</target> <note /> </trans-unit> <trans-unit id="ERR_StructsCannotHandleEvents"> <source>Methods declared in structures cannot have 'Handles' clauses.</source> <target state="translated">结构中声明的方法不能有 "Handles" 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_OverridesImpliesOverridable"> <source>Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.</source> <target state="translated">声明为 "Overrides" 的方法是隐式可重写的,因此它们不能声明为 "Overridable"。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalNamedSameAsParam1"> <source>'{0}' is already declared as a parameter of this method.</source> <target state="translated">“{0}”已声明为此方法的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalNamedSameAsParamInLambda1"> <source>Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression.</source> <target state="translated">变量“{0}”已声明为此 lambda 表达式或某个封闭 lambda 表达式的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseTypeSpecifier1"> <source>Type in a Module cannot be declared '{0}'.</source> <target state="translated">模块中的类型不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InValidSubMainsFound1"> <source>No accessible 'Main' method with an appropriate signature was found in '{0}'.</source> <target state="translated">“{0}”中找不到带有适当签名的可访问“Main”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_MoreThanOneValidMainWasFound2"> <source>'Sub Main' is declared more than once in '{0}': {1}</source> <target state="translated">'在“{0}”中多次声明了“Sub Main”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_CannotConvertValue2"> <source>Value '{0}' cannot be converted to '{1}'.</source> <target state="translated">值“{0}”无法转换为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OnErrorInSyncLock"> <source>'On Error' statements are not valid within 'SyncLock' statements.</source> <target state="translated">'"On Error" 语句在 "SyncLock" 语句内无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NarrowingConversionCollection2"> <source>Option Strict On disallows implicit conversions from '{0}' to '{1}'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type.</source> <target state="translated">Option Strict On 不允许从“{0}”到“{1}”的隐式转换;Visual Basic 6.0 集合类型与 .NET Framework 集合类型不兼容。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoTryHandler"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”语句无效,因为“{0}”位于不包含此语句的“Try”、“Catch”或“Finally”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoSyncLock"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'SyncLock' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“SyncLock”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoWith"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'With' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“With”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoFor"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'For' or 'For Each' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“For”或“For Each”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicConstructor"> <source>Attribute cannot be used because it does not have a Public constructor.</source> <target state="translated">特性没有 Public 构造函数,因此不能使用。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultEventNotFound1"> <source>Event '{0}' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.</source> <target state="translated">由“DefaultEvent”属性指定的事件“{0}”不是该类的公共可访问事件。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNonSerializedUsage"> <source>'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.</source> <target state="translated">'"NonSerialized" 特性对此成员无效,因为它的包含类不作为 "Serializable" 公开。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContinueKind"> <source>'Continue' must be followed by 'Do', 'For' or 'While'.</source> <target state="translated">'“Continue”的后面必须跟有“Do”、“For”或“While”。</target> <note /> </trans-unit> <trans-unit id="ERR_ContinueDoNotWithinDo"> <source>'Continue Do' can only appear inside a 'Do' statement.</source> <target state="translated">'“Continue Do”只能出现在“Do”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ContinueForNotWithinFor"> <source>'Continue For' can only appear inside a 'For' statement.</source> <target state="translated">'“Continue For”只能出现在“For”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_ContinueWhileNotWithinWhile"> <source>'Continue While' can only appear inside a 'While' statement.</source> <target state="translated">'“Continue While”只能出现在“While”语句内。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateParameterSpecifier"> <source>Parameter specifier is duplicated.</source> <target state="translated">参数说明符重复。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleCantUseDLLDeclareSpecifier1"> <source>'Declare' statements in a Module cannot be declared '{0}'.</source> <target state="translated">'模块中的“Declare”语句不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StructCantUseDLLDeclareSpecifier1"> <source>'Declare' statements in a structure cannot be declared '{0}'.</source> <target state="translated">'结构中的“Declare”语句不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TryCastOfValueType1"> <source>'TryCast' operand must be reference type, but '{0}' is a value type.</source> <target state="translated">'“TryCast”操作数必须是引用类型,但“{0}”是值类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TryCastOfUnconstrainedTypeParam1"> <source>'TryCast' operands must be class-constrained type parameter, but '{0}' has no class constraint.</source> <target state="translated">'“TryCast”操作数必须是类约束类型参数,但“{0}”没有类约束。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousDelegateBinding2"> <source>No accessible '{0}' is most specific: {1}</source> <target state="translated">没有非常明确的可访问“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_SharedStructMemberCannotSpecifyNew"> <source>Non-shared members in a Structure cannot be declared 'New'.</source> <target state="translated">Structure 中的非共享成员不能声明为 "New"。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericSubMainsFound1"> <source>None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types.</source> <target state="translated">在“{0}”中找到的带有适当签名的可访问“Main”方法要么都是泛型方法,要么嵌套在泛型类型中,因此均不能用作启动方法。</target> <note /> </trans-unit> <trans-unit id="ERR_GeneralProjectImportsError3"> <source>Error in project-level import '{0}' at '{1}' : {2}</source> <target state="translated">项目级 import“{0}”中的“{1}”位置出错: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidTypeForAliasesImport2"> <source>'{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.</source> <target state="translated">“{0}”的 Imports 别名的“{1}”不引用命名空间、类、结构、接口、枚举或模块。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedConstant2"> <source>Field '{0}.{1}' has an invalid constant value.</source> <target state="translated">字段“{0}.{1}”具有无效常量值。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteArgumentsNeedParens"> <source>Method arguments must be enclosed in parentheses.</source> <target state="translated">方法参数必须括在括号中。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteLineNumbersAreLabels"> <source>Labels that are numbers must be followed by colons.</source> <target state="translated">数字标签后面必须跟冒号。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteStructureNotType"> <source>'Type' statements are no longer supported; use 'Structure' statements instead.</source> <target state="translated">'不再支持 "Type" 语句;请改用 "Structure" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteObjectNotVariant"> <source>'Variant' is no longer a supported type; use the 'Object' type instead.</source> <target state="translated">'"Variant" 不再是受支持的类型;请改用 "Object" 类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteLetSetNotNeeded"> <source>'Let' and 'Set' assignment statements are no longer supported.</source> <target state="translated">'不再支持 "Let" 和 "Set" 赋值语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoletePropertyGetLetSet"> <source>Property Get/Let/Set are no longer supported; use the new Property declaration syntax.</source> <target state="translated">不再支持 Property Get/Let/Set;请使用新的 Property 声明语法。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteWhileWend"> <source>'Wend' statements are no longer supported; use 'End While' statements instead.</source> <target state="translated">'不再支持 "Wend" 语句;请改用 "End While" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteRedimAs"> <source>'ReDim' statements can no longer be used to declare array variables.</source> <target state="translated">'"ReDim" 语句不能再用于声明数组变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteOptionalWithoutValue"> <source>Optional parameters must specify a default value.</source> <target state="translated">可选参数必须指定默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteGosub"> <source>'GoSub' statements are no longer supported.</source> <target state="translated">'不再支持 "GoSub" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteOnGotoGosub"> <source>'On GoTo' and 'On GoSub' statements are no longer supported.</source> <target state="translated">'不再支持 "On GoTo" 和 "On GoSub" 语句。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteEndIf"> <source>'EndIf' statements are no longer supported; use 'End If' instead.</source> <target state="translated">'不再支持 "EndIf" 语句;请改用 "End If"。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteExponent"> <source>'D' can no longer be used to indicate an exponent, use 'E' instead.</source> <target state="translated">'"D" 不能再用来表示指数;请改用 "E"。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteAsAny"> <source>'As Any' is not supported in 'Declare' statements.</source> <target state="translated">'"Declare" 语句中不支持 "As Any"。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteGetStatement"> <source>'Get' statements are no longer supported. File I/O functionality is available in the 'Microsoft.VisualBasic' namespace.</source> <target state="translated">'不再支持 "Get" 语句。"Microsoft.VisualBasic" 命名空间中有文件 I/O 功能。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithArrayVsParamArray2"> <source>'{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在声明为 "ParamArray" 的参数上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_CircularBaseDependencies4"> <source>This inheritance causes circular dependencies between {0} '{1}' and its nested or base type '{2}'.</source> <target state="translated">此继承将导致在 {0}“{1}”及其嵌套类型或基类型“{2}”之间产生循环依赖项。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedBase2"> <source>{0} '{1}' cannot inherit from a type nested within it.</source> <target state="translated">{0}“{1}”不能从嵌套在它里面的类型继承。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatchOutsideAssembly4"> <source>'{0}' cannot expose type '{1}' outside the project through {2} '{3}'.</source> <target state="translated">“{0}”不能通过 {2}“{3}”在项目外部公开类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceAccessMismatchOutside3"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly.</source> <target state="translated">“{0}”将对基 {1} 的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoletePropertyAccessor3"> <source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source> <target state="translated">“{1}”的“{0}”访问器已过时:“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoletePropertyAccessor2"> <source>'{0}' accessor of '{1}' is obsolete.</source> <target state="translated">“{1}”的“{0}”访问器已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatchImplementedEvent6"> <source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'.</source> <target state="translated">“{0}”不能通过 {4}“{5}”向 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatchImplementedEvent4"> <source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'.</source> <target state="translated">“{0}”不能通过 {2}“{3}”公开它正在实现的事件的基础委托类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritanceCycleInImportedType1"> <source>Type '{0}' is not supported because it either directly or indirectly inherits from itself.</source> <target state="translated">类型“{0}”直接或者间接从自身继承,因此不受支持。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonObsoleteConstructorOnBase3"> <source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,因为它的基类“{2}”中的“{1}”被标记为已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNonObsoleteConstructorOnBase4"> <source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,因为它的基类“{2}”中的“{1}”被标记为已过时:“{3}”。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNonObsoleteNewCall3"> <source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source> <target state="translated">此“Sub New”的第一条语句必须是对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标为已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNonObsoleteNewCall4"> <source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'.</source> <target state="translated">此“Sub New”的第一条语句必须是对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标为已过时:“{3}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsTypeArgAccessMismatch7"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'.</source> <target state="translated">“{0}”将对类型“{3}”的访问扩展到{4}“{5}”,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_InheritsTypeArgAccessMismatchOutside5"> <source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly.</source> <target state="translated">“{0}”将对类型“{3}”的访问扩展到程序集之外,因此无法从 {1}“{2}”继承。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeAccessMismatch3"> <source>Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types.</source> <target state="translated">“{1}”的指定访问“{0}”与它的一个其他分部类型上指定的访问“{2}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeBadMustInherit1"> <source>'MustInherit' cannot be specified for partial type '{0}' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.</source> <target state="translated">'“MustInherit”不能为分部类型“{0}”指定,因为它不能与为该类型的某个其他分部类型指定的“NotInheritable”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_MustOverOnNotInheritPartClsMem1"> <source>'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.</source> <target state="translated">'不能在此成员上指定“MustOverride”,因为它所在的分部类型在另一个分部定义中被声明为“NotInheritable”。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseMismatchForPartialClass3"> <source>Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types.</source> <target state="translated">为类“{1}”指定的基类“{0}”不能与它的其他分部类型之一的基类“{2}”不同。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeTypeParamNameMismatch3"> <source>Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'.</source> <target state="translated">类型参数名“{0}”与在“{2}”的某个其他分部类型上定义的相应类型参数的名称“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeConstraintMismatch1"> <source>Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'.</source> <target state="translated">此类型参数的约束与在“{0}”的某个其他分部类型上定义的相应类型参数的约束不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_LateBoundOverloadInterfaceCall1"> <source>Late bound overload resolution cannot be applied to '{0}' because the accessing instance is an interface type.</source> <target state="translated">后期绑定重载决策不能应用于“{0}”,因为访问实例是一个接口类型。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredAttributeConstConversion2"> <source>Conversion from '{0}' to '{1}' cannot occur in a constant expression used as an argument to an attribute.</source> <target state="translated">在用作属性参数的常量表达式中不能发生从“{0}”到“{1}”的转换。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousOverrides3"> <source>Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2}</source> <target state="translated">无法重写与此签名匹配的成员“{0}”,因为类“{1}”包含多个具有此相同名称和签名的成员: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_OverriddenCandidate1"> <source> '{0}'</source> <target state="translated"> “{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousImplements3"> <source>Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature: '{3}' '{4}'</source> <target state="translated">无法实现与此签名匹配的成员“{0}.{1}”,因为接口“{2}”包含多个具有此相同名称和签名的成员: '{3}' '{4}'</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfNotCreatableDelegate1"> <source>'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source> <target state="translated">'“AddressOf”表达式无法转换为“{0}”,因为类型“{0}”已声明为“MustInherit”,无法创建。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassGenericMethod"> <source>Generic methods cannot be exposed to COM.</source> <target state="translated">泛型方法不能向 COM 公开。</target> <note /> </trans-unit> <trans-unit id="ERR_SyntaxInCastOp"> <source>Syntax error in cast operator; two arguments separated by comma are required.</source> <target state="translated">强制转换运算符中有语法错误;需要两个用逗号分隔的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerForNonConstDim"> <source>Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'.</source> <target state="translated">无法为不定维度指定数组初始值设定项;请使用空初始值设定项“{}”。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingFailure3"> <source>No accessible method '{0}' has a signature compatible with delegate '{1}':{2}</source> <target state="translated">没有任何可访问的方法“{0}”具有与委托“{1}”兼容的签名: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_StructLayoutAttributeNotAllowed"> <source>Attribute 'StructLayout' cannot be applied to a generic type.</source> <target state="translated">特性 "StructLayout" 不能应用于泛型类型。</target> <note /> </trans-unit> <trans-unit id="ERR_IterationVariableShadowLocal1"> <source>Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression.</source> <target state="translated">范围变量“{0}”隐藏封闭块中的某个变量或以前在查询表达式中定义的某个范围变量。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionInfer"> <source>'Option Infer' can be followed only by 'On' or 'Off'.</source> <target state="translated">'"Option Infer" 后面只能跟 "On" 或 "Off"。</target> <note /> </trans-unit> <trans-unit id="ERR_CircularInference1"> <source>Type of '{0}' cannot be inferred from an expression containing '{0}'.</source> <target state="translated">无法从包含“{0}”的表达式中推断“{0}”的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_InAccessibleOverridingMethod5"> <source>'{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible.</source> <target state="translated">'类“{1}”中的“{0}”不能重写类“{3}”中的“{2}”,因为中间类“{4}”重写了类“{3}”中的“{2}”,但不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuitableWidestType1"> <source>Type of '{0}' cannot be inferred because the loop bounds and the step clause do not convert to the same type.</source> <target state="translated">无法推断“{0}”的类型,因为循环边界和 step 子句不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousWidestType3"> <source>Type of '{0}' is ambiguous because the loop bounds and the step clause do not convert to the same type.</source> <target state="translated">“{0}”的类型不明确,因为循环边界和 step 子句不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAssignmentOperatorInInit"> <source>'=' expected (object initializer).</source> <target state="translated">'应为 "="(对象初始值设定项)。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedQualifiedNameInInit"> <source>Name of field or property being initialized in an object initializer must start with '.'.</source> <target state="translated">正在对象初始值设定项中初始化的字段或属性的名称必须以 "."开头。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLbrace"> <source>'{' expected.</source> <target state="translated">'应为 "{"。</target> <note /> </trans-unit> <trans-unit id="ERR_UnrecognizedTypeOrWith"> <source>Type or 'With' expected.</source> <target state="translated">应为类型或 "With"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAggrMemberInit1"> <source>Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression.</source> <target state="translated">多次初始化“{0}”的。字段和属性只能在对象初始值设定项表达式中初始化一次。</target> <note /> </trans-unit> <trans-unit id="ERR_NonFieldPropertyAggrMemberInit1"> <source>Member '{0}' cannot be initialized in an object initializer expression because it is not a field or property.</source> <target state="translated">无法在对象初始值设定项表达式中初始化成员“{0}”,因为它不是一个字段或属性。</target> <note /> </trans-unit> <trans-unit id="ERR_SharedMemberAggrMemberInit1"> <source>Member '{0}' cannot be initialized in an object initializer expression because it is shared.</source> <target state="translated">无法在对象初始值设定项表达式中初始化成员“{0}”,因为它是共享的。</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterizedPropertyInAggrInit1"> <source>Property '{0}' cannot be initialized in an object initializer expression because it requires arguments.</source> <target state="translated">无法在对象初始值设定项表达式中初始化属性“{0}”,因为它需要参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NoZeroCountArgumentInitCandidates1"> <source>Property '{0}' cannot be initialized in an object initializer expression because all accessible overloads require arguments.</source> <target state="translated">无法在对象初始值设定项表达式中初始化属性“{0}”,因为所有可访问的重载都需要参数。</target> <note /> </trans-unit> <trans-unit id="ERR_AggrInitInvalidForObject"> <source>Object initializer syntax cannot be used to initialize an instance of 'System.Object'.</source> <target state="translated">不能使用对象初始值设定项语法初始化“System.Object”的实例。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerExpected"> <source>Initializer expected.</source> <target state="translated">应为初始值设定项。</target> <note /> </trans-unit> <trans-unit id="ERR_LineContWithCommentOrNoPrecSpace"> <source>The line continuation character '_' must be preceded by at least one white space and it must be followed by a comment or the '_' must be the last character on the line.</source> <target state="translated">行继续符 "_" 前面必须至少有一个空格,且其后必须有注释或 "_" 必须是该行的最后一个字符。</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleFile1"> <source>Unable to load module file '{0}': {1}</source> <target state="translated">无法加载模块文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadRefLib1"> <source>Unable to load referenced library '{0}': {1}</source> <target state="translated">无法加载引用的库“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_EventHandlerSignatureIncompatible2"> <source>Method '{0}' cannot handle event '{1}' because they do not have a compatible signature.</source> <target state="translated">方法“{0}”无法处理事件“{1}”,因为它们的签名不兼容。</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalCompilationConstantNotValid"> <source>Conditional compilation constant '{1}' is not valid: {0}</source> <target state="translated">条件编译常数“{1}”无效: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwice1"> <source>Interface '{0}' can be implemented only once by this type.</source> <target state="translated">接口“{0}”只能由此类型实现一次。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames2"> <source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'.</source> <target state="translated">接口“{0}”只能通过此类型实现一次,但已显示有不同的元组元素名称,如“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames3"> <source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}').</source> <target state="translated">接口“{0}”只能通过此类型实现一次,但已显示有不同的元组元素名称,如“{1}”(通过“{2}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3"> <source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'.</source> <target state="translated">接口“{0}”只能通过此类型实现一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames4"> <source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}').</source> <target state="translated">接口“{0}”只能通过此类型实现一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”(通过“{3}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames2"> <source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'.</source> <target state="translated">接口“{0}”只能通过此接口继承一次,但已显示有不同的元组元素名称,如“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames3"> <source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}').</source> <target state="translated">接口“{0}”只能通过此接口继承一次,但已显示有不同的元组元素名称,如“{1}”(通过“{2}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3"> <source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'.</source> <target state="translated">接口“{0}”只能通过此接口继承一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames4"> <source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}').</source> <target state="translated">接口“{0}”只能通过此接口继承一次(通过“{1}”),但已显示有不同的元组元素名称,如“{2}”(通过“{3}”)。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceNotImplemented1"> <source>Interface '{0}' is not implemented by this class.</source> <target state="translated">接口“{0}”不是由此类实现的。</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousImplementsMember3"> <source>'{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface.</source> <target state="translated">“{0}”存在于多个基接口中。请使用在“Implements”子句中声明“{0}”的接口的名称,而不要使用派生接口的名称。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsOnNew"> <source>'Sub New' cannot implement interface members.</source> <target state="translated">'“Sub New”无法实现接口成员。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitInStruct"> <source>Arrays declared as structure members cannot be declared with an initial size.</source> <target state="translated">声明为结构成员的数组不能用初始大小声明。</target> <note /> </trans-unit> <trans-unit id="ERR_EventTypeNotDelegate"> <source>Events declared with an 'As' clause must have a delegate type.</source> <target state="translated">用 "As" 子句声明的事件必须有委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ProtectedTypeOutsideClass"> <source>Protected types can only be declared inside of a class.</source> <target state="translated">受保护的类型只能在类内部声明。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultPropertyWithNoParams"> <source>Properties with no required parameters cannot be declared 'Default'.</source> <target state="translated">不带必选参数的属性不能声明为“Default”。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerInStruct"> <source>Initializers on structure members are valid only for 'Shared' members and constants.</source> <target state="translated">结构成员上的初始值设定项仅对“Shared”成员和常量有效。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateImport1"> <source>Namespace or type '{0}' has already been imported.</source> <target state="translated">已导入命名空间或类型呢“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleFlags1"> <source>Modules cannot be declared '{0}'.</source> <target state="translated">模块不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsStmtWrongOrder"> <source>'Implements' statements must follow any 'Inherits' statement and precede all declarations in a class.</source> <target state="translated">'“Implements”语句在类中必须位于任何“Inherits”语句之后,所有声明之前。</target> <note /> </trans-unit> <trans-unit id="ERR_SynthMemberClashesWithSynth7"> <source>{0} '{1}' implicitly defines '{2}', which conflicts with a member implicitly declared for {3} '{4}' in {5} '{6}'.</source> <target state="translated">{0}“{1}”隐式定义的“{2}”与为 {5}“{6}”中的 {3}“{4}”隐式声明的成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_SynthMemberClashesWithMember5"> <source>{0} '{1}' implicitly defines '{2}', which conflicts with a member of the same name in {3} '{4}'.</source> <target state="translated">{0}“{1}”隐式定义的“{2}”与 {3}“{4}”中的同名成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_MemberClashesWithSynth6"> <source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in {4} '{5}'.</source> <target state="translated">{0}“{1}”与为 {4}“{5}”中的 {2}“{3}”隐式声明的成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeClashesWithVbCoreType4"> <source>{0} '{1}' conflicts with a Visual Basic Runtime {2} '{3}'.</source> <target state="translated">{0}“{1}”与 Visual Basic 运行时 {2}“{3}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeMissingAction"> <source>First argument to a security attribute must be a valid SecurityAction.</source> <target state="translated">安全属性的第一个参数必须是有效的 SecurityAction。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidAction"> <source>Security attribute '{0}' has an invalid SecurityAction value '{1}'.</source> <target state="translated">安全属性“{0}”具有无效的 SecurityAction 值“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionAssembly"> <source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly.</source> <target state="translated">SecurityAction 值“{0}”对应用于程序集的安全属性无效。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod"> <source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method.</source> <target state="translated">SecurityAction 值“{0}”对应用于类型或方法的安全属性无效。</target> <note /> </trans-unit> <trans-unit id="ERR_PrincipalPermissionInvalidAction"> <source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute.</source> <target state="translated">SecurityAction 值“{0}”对 PrincipalPermission 属性无效。</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeInvalidFile"> <source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute.</source> <target state="translated">无法解析为 PermissionSet 属性的命名参数“{1}”指定的文件路径“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeFileReadError"> <source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'.</source> <target state="translated">读取为 PermissionSet 属性的命名参数“{1}”指定的文件“'{0}' ”时出错:“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_SetHasOnlyOneParam"> <source>'Set' method cannot have more than one parameter.</source> <target state="translated">'"Set" 方法不能有一个以上的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_SetValueNotPropertyType"> <source>'Set' parameter must have the same type as the containing property.</source> <target state="translated">'"Set" 参数必须与包含属性的类型相同。</target> <note /> </trans-unit> <trans-unit id="ERR_SetHasToBeByVal1"> <source>'Set' parameter cannot be declared '{0}'.</source> <target state="translated">'“Set”参数不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_StructureCantUseProtected"> <source>Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.</source> <target state="translated">结构中的方法不能声明为 "Protected"、"Protected Friend" 或 "Private Protected"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceDelegateSpecifier1"> <source>Delegate in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的委托不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceEnumSpecifier1"> <source>Enum in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的枚举不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceClassSpecifier1"> <source>Class in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的类不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceStructSpecifier1"> <source>Structure in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的结构不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadInterfaceInterfaceSpecifier1"> <source>Interface in an interface cannot be declared '{0}'.</source> <target state="translated">接口中的接口不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfObsoleteSymbolNoMessage1"> <source>'{0}' is obsolete.</source> <target state="translated">“{0}”已过时。</target> <note /> </trans-unit> <trans-unit id="ERR_MetaDataIsNotAssembly"> <source>'{0}' is a module and cannot be referenced as an assembly.</source> <target state="translated">“{0}”是一个模块,不能作为程序集引用。</target> <note /> </trans-unit> <trans-unit id="ERR_MetaDataIsNotModule"> <source>'{0}' is an assembly and cannot be referenced as a module.</source> <target state="translated">“{0}”是一个程序集,不能作为模块引用。</target> <note /> </trans-unit> <trans-unit id="ERR_ReferenceComparison3"> <source>Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types.</source> <target state="translated">没有为类型“{1}”和“{2}”定义运算符“{0}”。请使用“Is”运算符比较两个引用的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CatchVariableNotLocal1"> <source>'{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.</source> <target state="translated">“{0}”不是局部变量或参数,因此不能用作“Catch”变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleMemberCantImplement"> <source>Members in a Module cannot implement interface members.</source> <target state="translated">模块中的成员无法实现接口成员。</target> <note /> </trans-unit> <trans-unit id="ERR_EventDelegatesCantBeFunctions"> <source>Events cannot be declared with a delegate type that has a return type.</source> <target state="translated">事件不能用具有返回类型的委托类型声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDate"> <source>Date constant is not valid.</source> <target state="translated">日期常量无效。</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverride4"> <source>'{0}' cannot override '{1}' because it is not declared 'Overridable'.</source> <target state="translated">“{0}”无法重写“{1}”,因为后者未声明为“Overridable”。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyArraysOnBoth"> <source>Array modifiers cannot be specified on both a variable and its type.</source> <target state="translated">不能在变量及其类型上同时指定数组修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_NotOverridableRequiresOverrides"> <source>'NotOverridable' cannot be specified for methods that do not override another method.</source> <target state="translated">'不能为不重写另一个方法的方法指定 "NotOverridable"。</target> <note /> </trans-unit> <trans-unit id="ERR_PrivateTypeOutsideType"> <source>Types declared 'Private' must be inside another type.</source> <target state="translated">声明为 "Private" 的类型必须在另一个类型内。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeRefResolutionError3"> <source>Import of type '{0}' from assembly or module '{1}' failed.</source> <target state="translated">从程序集或模块“{1}”导入类型“{0}”失败。</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTupleTypeRefResolutionError1"> <source>Predefined type '{0}' is not defined or imported.</source> <target state="translated">预定义的类型“{0}”未定义或未导入。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayWrongType"> <source>ParamArray parameters must have an array type.</source> <target state="translated">ParamArray 参数必须有数组类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CoClassMissing2"> <source>Implementing class '{0}' for interface '{1}' cannot be found.</source> <target state="translated">无法找到接口“{1}”的实现类“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidCoClass1"> <source>Type '{0}' cannot be used as an implementing class.</source> <target state="translated">类型“{0}”不能用作实现类。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMeReference"> <source>Reference to object under construction is not valid when calling another constructor.</source> <target state="translated">调用另一个构造函数时引用尚未完成的对象是无效的。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidImplicitMeReference"> <source>Implicit reference to object under construction is not valid when calling another constructor.</source> <target state="translated">调用另一个构造函数时隐式引用尚未完成的对象是无效的。</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeMemberNotFound2"> <source>Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'.</source> <target state="translated">类“{1}”中找不到成员“{0}”。此情况通常是由于不匹配的“Microsoft.VisualBasic.dll”造成的。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags"> <source>Property accessors cannot be declared '{0}'.</source> <target state="translated">不能将属性访问器声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlagsRestrict"> <source>Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.</source> <target state="translated">访问修饰符“{0}”无效。“Get”和“Set”的访问修饰符的限制性应该比属性访问级别更强。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyOneAccessorForGetSet"> <source>Access modifier can only be applied to either 'Get' or 'Set', but not both.</source> <target state="translated">访问修饰符只能用于 "Get" 或者 "Set",但不能同时用于这二者。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAccessibleSet"> <source>'Set' accessor of property '{0}' is not accessible.</source> <target state="translated">'属性“{0}”的“Set”访问器不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAccessibleGet"> <source>'Get' accessor of property '{0}' is not accessible.</source> <target state="translated">'属性“{0}”的“Get”访问器不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_WriteOnlyNoAccessorFlag"> <source>'WriteOnly' properties cannot have an access modifier on 'Set'.</source> <target state="translated">'"WriteOnly" 属性在 "Set" 上不能有访问修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyNoAccessorFlag"> <source>'ReadOnly' properties cannot have an access modifier on 'Get'.</source> <target state="translated">'"ReadOnly" 属性在 "Get" 上不能有访问修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags1"> <source>Property accessors cannot be declared '{0}' in a 'NotOverridable' property.</source> <target state="translated">属性访问器不能在“NotOverridable”属性中声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags2"> <source>Property accessors cannot be declared '{0}' in a 'Default' property.</source> <target state="translated">属性访问器不能在“Default”属性中声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPropertyAccessorFlags3"> <source>Property cannot be declared '{0}' because it contains a 'Private' accessor.</source> <target state="translated">属性包含“Private”访问器,因此不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InAccessibleCoClass3"> <source>Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'.</source> <target state="translated">接口“{1}”的实现类“{0}”是“{2}”,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingValuesForArraysInApplAttrs"> <source>Arrays used as attribute arguments are required to explicitly specify values for all elements.</source> <target state="translated">必须有用作特性参数的数组才能显式指定所有元素的值。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitEventMemberNotInvalid"> <source>'Exit AddHandler', 'Exit RemoveHandler' and 'Exit RaiseEvent' are not valid. Use 'Return' to exit from event members.</source> <target state="translated">'"Exit AddHandler"、"Exit RemoveHandler" 和 "Exit RaiseEvent" 无效。请使用 "Return" 从事件成员中退出。</target> <note /> </trans-unit> <trans-unit id="ERR_InvInsideEndsEvent"> <source>Statement cannot appear within an event body. End of event assumed.</source> <target state="translated">语句不能出现在事件体内。假定为事件末尾。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndEvent"> <source>'Custom Event' must end with a matching 'End Event'.</source> <target state="translated">'Custom Event 必须以匹配的 "End Event" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndAddHandler"> <source>'AddHandler' declaration must end with a matching 'End AddHandler'.</source> <target state="translated">'"AddHandler" 声明必须以匹配的 "End AddHandler" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndRemoveHandler"> <source>'RemoveHandler' declaration must end with a matching 'End RemoveHandler'.</source> <target state="translated">'"RemoveHandler" 声明必须以匹配的 "End RemoveHandler" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingEndRaiseEvent"> <source>'RaiseEvent' declaration must end with a matching 'End RaiseEvent'.</source> <target state="translated">'"RaiseEvent" 声明必须以匹配的 "End RaiseEvent" 结束。</target> <note /> </trans-unit> <trans-unit id="ERR_CustomEventInvInInterface"> <source>'Custom' modifier is not valid on events declared in interfaces.</source> <target state="translated">'“Custom”修饰符在接口中声明的事件上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_CustomEventRequiresAs"> <source>'Custom' modifier is not valid on events declared without explicit delegate types.</source> <target state="translated">'“Custom”修饰符在未用显式委托类型声明的事件上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndEvent"> <source>'End Event' must be preceded by a matching 'Custom Event'.</source> <target state="translated">'“End Event”前面必须是匹配的“Custom Event”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndAddHandler"> <source>'End AddHandler' must be preceded by a matching 'AddHandler' declaration.</source> <target state="translated">'“End AddHandler”前面必须是匹配的“AddHandler”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndRemoveHandler"> <source>'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.</source> <target state="translated">'“End RemoveHandler”前面必须是匹配的“RemoveHandler”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndRaiseEvent"> <source>'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.</source> <target state="translated">'“End RaiseEvent”前面必须是匹配的“RaiseEvent”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAddHandlerDef"> <source>'AddHandler' is already declared.</source> <target state="translated">'已经声明 "AddHandler"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateRemoveHandlerDef"> <source>'RemoveHandler' is already declared.</source> <target state="translated">'已经声明 "RemoveHandler"。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateRaiseEventDef"> <source>'RaiseEvent' is already declared.</source> <target state="translated">'已经声明 "RaiseEvent"。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingAddHandlerDef1"> <source>'AddHandler' definition missing for event '{0}'.</source> <target state="translated">'缺少事件“{0}”的“AddHandler”定义。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingRemoveHandlerDef1"> <source>'RemoveHandler' definition missing for event '{0}'.</source> <target state="translated">'缺少事件“{0}”的“RemoveHandler”定义。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingRaiseEventDef1"> <source>'RaiseEvent' definition missing for event '{0}'.</source> <target state="translated">'缺少事件“{0}”的“RaiseEvent”定义。</target> <note /> </trans-unit> <trans-unit id="ERR_EventAddRemoveHasOnlyOneParam"> <source>'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.</source> <target state="translated">'“AddHandler”和“RemoveHandler”方法必须正好有一个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_EventAddRemoveByrefParamIllegal"> <source>'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.</source> <target state="translated">'“AddHandler”和“RemoveHandler”方法参数不能声明为“ByRef”。</target> <note /> </trans-unit> <trans-unit id="ERR_SpecifiersInvOnEventMethod"> <source>Specifiers are not valid on 'AddHandler', 'RemoveHandler' and 'RaiseEvent' methods.</source> <target state="translated">说明符在 "AddHandler"、"RemoveHandler" 和 "RaiseEvent" 方法上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_AddRemoveParamNotEventType"> <source>'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.</source> <target state="translated">'“AddHandler”和“RemoveHandler”方法参数必须与包含事件具有相同的委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_RaiseEventShapeMismatch1"> <source>'RaiseEvent' method must have the same signature as the containing event's delegate type '{0}'.</source> <target state="translated">'“RaiseEvent”方法必须具有与包含事件的委托类型“{0}”相同的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_EventMethodOptionalParamIllegal1"> <source>'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared '{0}'.</source> <target state="translated">'“AddHandler”、“RemoveHandler”和“RaiseEvent”方法参数不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_CantReferToMyGroupInsideGroupType1"> <source>'{0}' cannot refer to itself through its default instance; use 'Me' instead.</source> <target state="translated">“{0}”不能通过其默认实例指代自身;请改用“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidUseOfCustomModifier"> <source>'Custom' modifier can only be used immediately before an 'Event' declaration.</source> <target state="translated">'"Custom" 修饰符只能在紧靠 "Event" 声明之前使用。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOptionStrictCustom"> <source>Option Strict Custom can only be used as an option to the command-line compiler (vbc.exe).</source> <target state="translated">Option Strict Custom 只能用作命令行编译器(vbc.exe)的选项。</target> <note /> </trans-unit> <trans-unit id="ERR_ObsoleteInvalidOnEventMember"> <source>'{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.</source> <target state="translated">“{0}”不能应用于“'AddHandler”、“RemoveHandler”或“'RaiseEvent”定义。如有必要,请将该属性直接应用于事件。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingIncompatible2"> <source>Method '{0}' does not have a signature compatible with delegate '{1}'.</source> <target state="translated">方法“{0}”没有与委托“{1}”兼容的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlName"> <source>XML name expected.</source> <target state="translated">应为 XML 名称。</target> <note /> </trans-unit> <trans-unit id="ERR_UndefinedXmlPrefix"> <source>XML namespace prefix '{0}' is not defined.</source> <target state="translated">未定义 XML 命名空间前缀“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateXmlAttribute"> <source>Duplicate XML attribute '{0}'.</source> <target state="translated">重复的 XML 属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_MismatchedXmlEndTag"> <source>End tag &lt;/{0}{1}{2}&gt; expected.</source> <target state="translated">应为结束标记 &lt;/{0}{1}{2}&gt;。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingXmlEndTag"> <source>Element is missing an end tag.</source> <target state="translated">元素缺少结束标记。</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedXmlPrefix"> <source>XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed.</source> <target state="translated">XML 命名空间前缀“{0}”已保留供 XML 使用,并且命名空间 URI 不能更改。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingVersionInXmlDecl"> <source>Required attribute 'version' missing from XML declaration.</source> <target state="translated">XML 声明中缺少必需的特性 "version"。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalAttributeInXmlDecl"> <source>XML declaration does not allow attribute '{0}{1}{2}'.</source> <target state="translated">XML 声明不允许属性“{0}{1}{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_QuotedEmbeddedExpression"> <source>Embedded expression cannot appear inside a quoted attribute value. Try removing quotes.</source> <target state="translated">带引号的特性值内不能出现嵌入式表达式。请尝试移除引号。</target> <note /> </trans-unit> <trans-unit id="ERR_VersionMustBeFirstInXmlDecl"> <source>XML attribute 'version' must be the first attribute in XML declaration.</source> <target state="translated">XML 特性 "version" 必须是 XML 声明中的第一个特性。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeOrder"> <source>XML attribute '{0}' must appear before XML attribute '{1}'.</source> <target state="translated">XML 特性“{0}”必须出现在 XML 特性“{1}”之前。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndEmbedded"> <source>Expected closing '%&gt;' for embedded expression.</source> <target state="translated">应为嵌入表达式的结束标记“%&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndPI"> <source>Expected closing '?&gt;' for XML processor instruction.</source> <target state="translated">应为 XML 处理器指令的结束标记“?&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndComment"> <source>Expected closing '--&gt;' for XML comment.</source> <target state="translated">应为 XML 注释的结束标记“--&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlEndCData"> <source>Expected closing ']]&gt;' for XML CDATA section.</source> <target state="translated">应为 XML CDATA 部分的结束标记“]]&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSQuote"> <source>Expected matching closing single quote for XML attribute value.</source> <target state="translated">XML 特性值应有匹配的右单引号。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedQuote"> <source>Expected matching closing double quote for XML attribute value.</source> <target state="translated">XML 特性值应有匹配的右双引号。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedLT"> <source>Expected beginning '&lt;' for an XML tag.</source> <target state="translated">XML 标记前应有 "&lt;"。</target> <note /> </trans-unit> <trans-unit id="ERR_StartAttributeValue"> <source>Expected quoted XML attribute value or embedded expression.</source> <target state="translated">应为带引号的 XML 特性值或嵌入式表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDiv"> <source>Expected '/' for XML end tag.</source> <target state="translated">应使用“/”作为 XML 结束标记。</target> <note /> </trans-unit> <trans-unit id="ERR_NoXmlAxesLateBinding"> <source>XML axis properties do not support late binding.</source> <target state="translated">XML 轴属性不支持后期绑定。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlStartNameChar"> <source>Character '{0}' ({1}) is not allowed at the beginning of an XML name.</source> <target state="translated">XML 名称的开头不允许出现字符“{0}”({1})。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlNameChar"> <source>Character '{0}' ({1}) is not allowed in an XML name.</source> <target state="translated">XML 名称中允许字符“{0}”({1})。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlCommentChar"> <source>Character sequence '--' is not allowed in an XML comment.</source> <target state="translated">XML 注释中不允许出现字符序列“--”。</target> <note /> </trans-unit> <trans-unit id="ERR_EmbeddedExpression"> <source>An embedded expression cannot be used here.</source> <target state="translated">不能在此处使用嵌入式表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlWhiteSpace"> <source>Missing required white space.</source> <target state="translated">缺少必需的空白。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalProcessingInstructionName"> <source>XML processing instruction name '{0}' is not valid.</source> <target state="translated">XML 处理指令名称“{0}”无效。</target> <note /> </trans-unit> <trans-unit id="ERR_DTDNotSupported"> <source>XML DTDs are not supported.</source> <target state="translated">不支持 XML DTD。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlWhiteSpace"> <source>White space cannot appear here.</source> <target state="translated">此处不能使用空白。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSColon"> <source>Expected closing ';' for XML entity.</source> <target state="translated">应为 XML 实体的结束标记“;”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlBeginEmbedded"> <source>Expected '%=' at start of an embedded expression.</source> <target state="translated">嵌入表达式的开头应为“%=”。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlEntityReference"> <source>XML entity references are not supported.</source> <target state="translated">不支持 XML 实体引用。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeValue1"> <source>Attribute value is not valid; expecting '{0}'.</source> <target state="translated">属性值无效;应为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeValue2"> <source>Attribute value is not valid; expecting '{0}' or '{1}'.</source> <target state="translated">属性值无效;应为“{0}”或“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedXmlNamespace"> <source>Prefix '{0}' cannot be bound to namespace name reserved for '{1}'.</source> <target state="translated">不能将前缀“{0}”绑定到为“{1}”保留的命名空间名称。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalDefaultNamespace"> <source>Namespace declaration with prefix cannot have an empty value inside an XML literal.</source> <target state="translated">带前缀的命名空间声明在 XML 文本中不能有空值。</target> <note /> </trans-unit> <trans-unit id="ERR_QualifiedNameNotAllowed"> <source>':' is not allowed. XML qualified names cannot be used in this context.</source> <target state="translated">'不允许使用 ":"。不能在此上下文中使用 XML 限定名称。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedXmlns"> <source>Namespace declaration must start with 'xmlns'.</source> <target state="translated">命名空间声明必须以“xmlns”开头。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalXmlnsPrefix"> <source>Element names cannot use the 'xmlns' prefix.</source> <target state="translated">元素名不能使用“xmlns”前缀。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlFeaturesNotAvailable"> <source>XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.</source> <target state="translated">XML 文本和 XML 轴属性不可用。添加对 System.Xml、System.Xml.Linq 和 System.Core 的引用,或其他声明 System.Linq.Enumerable、System.Xml.Linq.XElement、System.Xml.Linq.XName、System.Xml.Linq.XAttribute 和 System.Xml.Linq.XNamespace 类型的程序集。</target> <note /> </trans-unit> <trans-unit id="ERR_UnableToReadUacManifest2"> <source>Unable to open Win32 manifest file '{0}' : {1}</source> <target state="translated">无法打开 Win32 清单文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="WRN_UseValueForXmlExpression3"> <source>Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source> <target state="translated">无法将“{0}”转换为“{1}”。可使用“Value”属性来获取“{2}”的第一个元素的字符串值。</target> <note /> </trans-unit> <trans-unit id="WRN_UseValueForXmlExpression3_Title"> <source>Cannot convert IEnumerable(Of XElement) to String</source> <target state="translated">无法将 IEnumerable(Of XElement) 转换为字符串</target> <note /> </trans-unit> <trans-unit id="ERR_TypeMismatchForXml3"> <source>Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source> <target state="translated">类型“{0}”的值无法转换为“{1}”。可使用“Value”属性来获取“{2}”的第一个元素的字符串值。</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryOperandsForXml4"> <source>Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'.</source> <target state="translated">没有为类型“{1}”和“{2}”定义运算符“{0}”。可使用“Value”属性来获取“{3}”的第一个元素的字符串值。</target> <note /> </trans-unit> <trans-unit id="ERR_FullWidthAsXmlDelimiter"> <source>Full width characters are not valid as XML delimiters.</source> <target state="translated">全角字符不能用作 XML 分隔符。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSubsystemVersion"> <source>The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise.</source> <target state="translated">值“{0}”不是有效的子系统版本。对于 ARM 或 AppContainerExe,版本必须为 6.02 或更高版本,对于其他内容,版本必须为 4.00 或更高版本。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFileAlignment"> <source>Invalid file section alignment '{0}'</source> <target state="translated">无效的文件节对齐方式“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOutputName"> <source>Invalid output name: {0}</source> <target state="translated">无效输出名: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInformationFormat"> <source>Invalid debug information format: {0}</source> <target state="translated">无效的调试信息格式: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_LibAnycpu32bitPreferredConflict"> <source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe.</source> <target state="translated">/platform:anycpu32bitpreferred 只能与 /t:exe、/t:winexe 和 /t:appcontainerexe 一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedAccess"> <source>Expression has the type '{0}' which is a restricted type and cannot be used to access members inherited from 'Object' or 'ValueType'.</source> <target state="translated">表达式的类型为“{0}”,这是受限类型,不能用于访问从“Object”或“ValueType”继承的成员。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedConversion1"> <source>Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'.</source> <target state="translated">类型“{0}”的表达式无法转换为“Object”或“ValueType”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypecharInLabel"> <source>Type characters are not allowed in label identifiers.</source> <target state="translated">标签标识符中不允许使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedType1"> <source>'{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.</source> <target state="translated">“{0}”不能设置为可以为 null,而且不能用作数组元素、字段、匿名类型成员、类型参数、"ByRef" 参数或 return 语句的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypecharInAlias"> <source>Type characters are not allowed on Imports aliases.</source> <target state="translated">在 Imports 别名上不允许使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAccessibleConstructorOnBase"> <source>Class '{0}' has no accessible 'Sub New' and cannot be inherited.</source> <target state="translated">类“{0}”没有可访问的“Sub New”,不能被继承。</target> <note /> </trans-unit> <trans-unit id="ERR_BadStaticLocalInStruct"> <source>Local variables within methods of structures cannot be declared 'Static'.</source> <target state="translated">结构方法内部的局部变量不能声明为“Static”。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLocalStatic1"> <source>Static local variable '{0}' is already declared.</source> <target state="translated">已声明静态局部变量“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ImportAliasConflictsWithType2"> <source>Imports alias '{0}' conflicts with '{1}' declared in the root namespace.</source> <target state="translated">Imports 别名“{0}”与根命名空间中声明的“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_CantShadowAMustOverride1"> <source>'{0}' cannot shadow a method declared 'MustOverride'.</source> <target state="translated">“{0}”不能隐藏声明为“MustOverride”的方法。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleEventImplMismatch3"> <source>Event '{0}' cannot implement event '{2}.{1}' because its delegate type does not match the delegate type of another event implemented by '{0}'.</source> <target state="translated">事件“{0}”不能实现事件“{2}.{1}”,因为其委托类型与“{0}”实现的另一个事件的委托类型不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadSpecifierCombo2"> <source>'{0}' and '{1}' cannot be combined.</source> <target state="translated">“{0}”不能与“{1}”组合。</target> <note /> </trans-unit> <trans-unit id="ERR_MustBeOverloads2"> <source>{0} '{1}' must be declared 'Overloads' because another '{1}' is declared 'Overloads' or 'Overrides'.</source> <target state="translated">{0}“{1}”必须声明为“Overloads”,因为另一个“{1}”声明为“Overloads”或“Overrides”。</target> <note /> </trans-unit> <trans-unit id="ERR_MustOverridesInClass1"> <source>'{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.</source> <target state="translated">“{0}”包含声明为“MustOverride”的方法,因此它必须声明为“MustInherit”。</target> <note /> </trans-unit> <trans-unit id="ERR_HandlesSyntaxInClass"> <source>'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.</source> <target state="translated">'类中的“Handles”必须指定用单个标识符限定的“WithEvents”变量、“MyBase”、“MyClass”或“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_SynthMemberShadowsMustOverride5"> <source>'{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'.</source> <target state="translated">'为 {1}“{2}”隐式声明的“{0}”不能隐藏基 {3}“{4}”中的“MustOverride”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotOverrideInAccessibleMember"> <source>'{0}' cannot override '{1}' because it is not accessible in this context.</source> <target state="translated">“{0}”无法重写“{1}”,因为它在此上下文中是无法访问的。</target> <note /> </trans-unit> <trans-unit id="ERR_HandlesSyntaxInModule"> <source>'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.</source> <target state="translated">'模块中的“Handles”必须指定用单个标识符限定的“WithEvents”变量。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNotOpRequiresReferenceTypes1"> <source>'IsNot' requires operands that have reference types, but this operand has the value type '{0}'.</source> <target state="translated">'“IsNot”要求具有引用类型的操作数,但此操作数的值类型为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ClashWithReservedEnumMember1"> <source>'{0}' conflicts with the reserved member by this name that is implicitly declared in all enums.</source> <target state="translated">“{0}”与在所有枚举中隐式声明的同名保留成员冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_MultiplyDefinedEnumMember2"> <source>'{0}' is already declared in this {1}.</source> <target state="translated">'此 {1} 中已声明了“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadUseOfVoid"> <source>'System.Void' can only be used in a GetType expression.</source> <target state="translated">'“System.Void”只能在 GetType 表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_EventImplMismatch5"> <source>Event '{0}' cannot implement event '{1}' on interface '{2}' because their delegate types '{3}' and '{4}' do not match.</source> <target state="translated">事件“{0}”无法实现接口“{2}”上的事件“{1}”,因为其委托类型“{3}”和“{4}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeUnavailable3"> <source>Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'.</source> <target state="translated">程序集“{1}”中的类型“{0}”已转发到程序集“{2}”。您的项目中缺少对“{2}”的引用或者程序集中“{2}”缺少类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeFwdCycle2"> <source>'{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type.</source> <target state="translated">'程序集“{1}”中的“{0}”已被转发给自身,因此它是一种不受支持的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeInCCExpression"> <source>Non-intrinsic type names are not allowed in conditional compilation expressions.</source> <target state="translated">在条件编译表达式中不允许有非内部的类型名。</target> <note /> </trans-unit> <trans-unit id="ERR_BadCCExpression"> <source>Syntax error in conditional compilation expression.</source> <target state="translated">条件编译表达式中有语法错误。</target> <note /> </trans-unit> <trans-unit id="ERR_VoidArrayDisallowed"> <source>Arrays of type 'System.Void' are not allowed in this expression.</source> <target state="translated">此表达式中不允许使用 "System.Void" 类型的数组。</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataMembersAmbiguous3"> <source>'{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'.</source> <target state="translated">“{0}”不明确,因为 {1}“{2}”中存在多种具有此名称的成员</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOfExprAlwaysFalse2"> <source>Expression of type '{0}' can never be of type '{1}'.</source> <target state="translated">类型“{0}”的表达式永远不能为类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyPrivatePartialMethods1"> <source>Partial methods must be declared 'Private' instead of '{0}'.</source> <target state="translated">必须将分部方法声明为“Private”,而不是“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodsMustBePrivate"> <source>Partial methods must be declared 'Private'.</source> <target state="translated">必须将分部方法声明为 "Private"。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyOnePartialMethodAllowed2"> <source>Method '{0}' cannot be declared 'Partial' because only one method '{1}' can be marked 'Partial'.</source> <target state="translated">方法“{0}”不能声明为“Partial”,因为只有一个方法“{1}”可以标记为“Partial”。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyOneImplementingMethodAllowed3"> <source>Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method.</source> <target state="translated">方法“{0}”无法实现分部方法“{1}”,因为它已经由“{2}”实现。分部方法只能由一个方法实现。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodMustBeEmpty"> <source>Partial methods must have empty method bodies.</source> <target state="translated">分部方法必须具有空方法体。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodsMustBeSub1"> <source>'{0}' cannot be declared 'Partial' because partial methods must be Subs.</source> <target state="translated">“{0}”不能声明为“Partial”,因为分部方法必须为 Subs。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodGenericConstraints2"> <source>Method '{0}' does not have the same generic constraints as the partial method '{1}'.</source> <target state="translated">方法“{0}”没有与分部方法“{1}”相同的泛型约束。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialDeclarationImplements1"> <source>Partial method '{0}' cannot use the 'Implements' keyword.</source> <target state="translated">分部方法“{0}”不能使用“Implements”关键字。</target> <note /> </trans-unit> <trans-unit id="ERR_NoPartialMethodInAddressOf1"> <source>'AddressOf' cannot be applied to '{0}' because '{0}' is a partial method without an implementation.</source> <target state="translated">'“AddressOf”不能应用于“{0}”,因为“{0}”是不包含实现的分部方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementationMustBePrivate2"> <source>Method '{0}' must be declared 'Private' in order to implement partial method '{1}'.</source> <target state="translated">方法“{0}”必须声明为“Private”,以便实现分部方法“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodParamNamesMustMatch3"> <source>Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'.</source> <target state="translated">参数名“{0}”与在分部方法声明“{2}”上定义的相应参数的名称“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodTypeParamNameMismatch3"> <source>Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'.</source> <target state="translated">类型参数“{0}”的名称与在分部方法声明“{2}”上定义的相应类型参数“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeSharedProperty1"> <source>'Shared' attribute property '{0}' cannot be the target of an assignment.</source> <target state="translated">'“Shared”特性属性“{0}”不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeReadOnlyProperty1"> <source>'ReadOnly' attribute property '{0}' cannot be the target of an assignment.</source> <target state="translated">'“ReadOnly”特性属性“{0}”不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateResourceName1"> <source>Resource name '{0}' cannot be used more than once.</source> <target state="translated">资源名称“{0}”不能多次使用。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateResourceFileName1"> <source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly.</source> <target state="translated">每个链接的资源和模块都必须有唯一的文件名。此程序集中多次指定了文件名“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeMustBeClassNotStruct1"> <source>'{0}' cannot be used as an attribute because it is not a class.</source> <target state="translated">“{0}”不是类,因此不能用作属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeMustInheritSysAttr"> <source>'{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'.</source> <target state="translated">“{0}”不从“System.Attribute”继承,因此不能用作属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeCannotBeAbstract"> <source>'{0}' cannot be used as an attribute because it is declared 'MustInherit'.</source> <target state="translated">“{0}”已声明为“MustInherit”,因此不能用作属性。</target> <note /> </trans-unit> <trans-unit id="ERR_UnableToOpenResourceFile1"> <source>Unable to open resource file '{0}': {1}</source> <target state="translated">无法打开资源文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicProperty1"> <source>Attribute member '{0}' cannot be the target of an assignment because it is not declared 'Public'.</source> <target state="translated">特性成员“{0}”未声明为“Public”,因此不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_STAThreadAndMTAThread0"> <source>'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.</source> <target state="translated">'"System.STAThreadAttribute" 和 "System.MTAThreadAttribute" 不能同时应用于同一方法。</target> <note /> </trans-unit> <trans-unit id="ERR_IndirectUnreferencedAssembly4"> <source>Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project.</source> <target state="translated">项目“{0}”间接引用包含“{2}”的程序集“{1}”。请在您的项目中添加对“{3}”的文件引用。 </target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicType1"> <source>Type '{0}' cannot be used in an attribute because it is not declared 'Public'.</source> <target state="translated">类型“{0}”未声明为“Public”,因此不能用在特性中。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeNonPublicContType2"> <source>Type '{0}' cannot be used in an attribute because its container '{1}' is not declared 'Public'.</source> <target state="translated">类型“{0}”的容器“{1}”未声明为“Public”,因此不能用在特性中。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnNonEmptySubOrFunction"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于带有非空体的 Sub、Function 或 Operator。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportNotLegalOnDeclare"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Declare.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于 Declare。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportNotLegalOnGetOrSet"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Get or Set.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于 Get 或 Set。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnGenericSubOrFunction"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a method that is generic or contained in a generic type.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于属于泛型类型或者包含在泛型类型中的方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassOnGeneric"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”不能应用于属于泛型类型或者包含在泛型类型中的类。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnInstanceMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于实例方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnInterfaceMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to interface methods.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于接口方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportNotLegalOnEventMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to 'AddHandler', 'RemoveHandler' or 'RaiseEvent' method.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于 "AddHandler"、"RemoveHandler" 或 "RaiseEvent" 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyBadArguments"> <source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source> <target state="translated">友元程序集引用“{0}”无效。不能在 InternalsVisibleTo 声明中指定版本、区域性、公钥标记或处理器架构。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyStrongNameRequired"> <source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source> <target state="translated">友元程序集引用“{0}”无效。强名称签名的程序集必须在其 InternalsVisibleTo 声明中指定一个公钥。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyNameInvalid"> <source>Friend declaration '{0}' is invalid and cannot be resolved.</source> <target state="translated">友元声明“{0}”无效,且无法解析。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyBadAccessOverride2"> <source>Member '{0}' cannot override member '{1}' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.</source> <target state="translated">成员“{0}”无法重写另一个程序集/项目中定义的成员“{1}”,因为访问修饰符“Protected Friend”扩展了可访问性。请改用“Protected”。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfLocalBeforeDeclaration1"> <source>Local variable '{0}' cannot be referred to before it is declared.</source> <target state="translated">局部变量“{0}”在声明之前不能被引用。</target> <note /> </trans-unit> <trans-unit id="ERR_UseOfKeywordFromModule1"> <source>'{0}' is not valid within a Module.</source> <target state="translated">“{0}”在模块中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_BogusWithinLineIf"> <source>Statement cannot end a block outside of a line 'If' statement.</source> <target state="translated">语句不能在“If”语句行之外结束块。</target> <note /> </trans-unit> <trans-unit id="ERR_CharToIntegralTypeMismatch1"> <source>'Char' values cannot be converted to '{0}'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit.</source> <target state="translated">'“Char”值不能转换为“{0}”。请使用“Microsoft.VisualBasic.AscW”将字符解释为 Unicode 值,或者使用“Microsoft.VisualBasic.Val”将字符解释为数字。</target> <note /> </trans-unit> <trans-unit id="ERR_IntegralToCharTypeMismatch1"> <source>'{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit.</source> <target state="translated">“{0}”值不能转换为“Char”。使用“Microsoft.VisualBasic.ChrW”将数值解释为 Unicode 字符或先将其转换为“String”以产生数字。</target> <note /> </trans-unit> <trans-unit id="ERR_NoDirectDelegateConstruction1"> <source>Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.</source> <target state="translated">委托“{0}”需要使用一个“AddressOf”表达式或 lambda 表达式作为其构造函数的唯一参数。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodMustBeFirstStatementOnLine"> <source>Method declaration statements must be the first statement on a logical line.</source> <target state="translated">方法声明语句必须是逻辑行上的第一条语句。</target> <note /> </trans-unit> <trans-unit id="ERR_AttrAssignmentNotFieldOrProp1"> <source>'{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property.</source> <target state="translated">“{0}”不是字段或属性(Property),因此不能命名为属性(Attribute)说明符中的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowsObjectComparison1"> <source>Option Strict On disallows operands of type Object for operator '{0}'. Use the 'Is' operator to test for object identity.</source> <target state="translated">Option Strict On 不允许将类型 Object 的操作数用于运算符“{0}”。请使用“Is”运算符测试对象标识。</target> <note /> </trans-unit> <trans-unit id="ERR_NoConstituentArraySizes"> <source>Bounds can be specified only for the top-level array when initializing an array of arrays.</source> <target state="translated">初始化数组的数组时,只能指定顶级数组的界限。</target> <note /> </trans-unit> <trans-unit id="ERR_FileAttributeNotAssemblyOrModule"> <source>'Assembly' or 'Module' expected.</source> <target state="translated">'应为“Assembly”或“Module”。</target> <note /> </trans-unit> <trans-unit id="ERR_FunctionResultCannotBeIndexed1"> <source>'{0}' has no parameters and its return type cannot be indexed.</source> <target state="translated">“{0}”没有任何参数,并且无法对它的返回类型进行索引。</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentSyntax"> <source>Comma, ')', or a valid expression continuation expected.</source> <target state="translated">应为逗号、")" 或有效的表达式继续符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedResumeOrGoto"> <source>'Resume' or 'GoTo' expected.</source> <target state="translated">'应为 "Resume" 或 "GoTo"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAssignmentOperator"> <source>'=' expected.</source> <target state="translated">'应为 "="。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgAlsoOmitted2"> <source>Parameter '{0}' in '{1}' already has a matching omitted argument.</source> <target state="translated">“{1}”中的形参“{0}”已具有匹配的省略实参。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotCallEvent1"> <source>'{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.</source> <target state="translated">“{0}”是事件,不能直接调用。请使用“RaiseEvent”语句引发事件。</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachCollectionDesignPattern1"> <source>Expression is of type '{0}', which is not a collection type.</source> <target state="translated">表达式的类型为“{0}”,该类型不是集合类型。</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueForNonOptionalParam"> <source>Default values cannot be supplied for parameters that are not declared 'Optional'.</source> <target state="translated">无法向未声明为 "Optional" 的参数提供默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDotAfterMyBase"> <source>'MyBase' must be followed by '.' and an identifier.</source> <target state="translated">'“MyBase”的后面必须跟有“.”和标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDotAfterMyClass"> <source>'MyClass' must be followed by '.' and an identifier.</source> <target state="translated">'“MyClass”的后面必须跟有“.”和标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictArgumentCopyBackNarrowing3"> <source>Option Strict On disallows narrowing from type '{1}' to type '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source> <target state="translated">将“ByRef”形参“{0}”的值复制回匹配实参时,Option Strict On 不允许从类型“{1}”收缩为类型“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_LbElseifAfterElse"> <source>'#ElseIf' cannot follow '#Else' as part of a '#If' block.</source> <target state="translated">'"#ElseIf" 不能作为 "#If" 块的一部分跟在 "#Else" 之后。</target> <note /> </trans-unit> <trans-unit id="ERR_StandaloneAttribute"> <source>Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.</source> <target state="translated">特性说明符不是一个完整的语句。请使用行继续符将该特性应用于下列语句。</target> <note /> </trans-unit> <trans-unit id="ERR_NoUniqueConstructorOnBase2"> <source>Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">类“{0}”必须声明一个“Sub New”,因它的基类“{1}”有多个不使用参数就可以调用的可访问“Sub New”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtraNextVariable"> <source>'Next' statement names more variables than there are matching 'For' statements.</source> <target state="translated">'“Next”语句命名的变量比已有的匹配“For”语句多。</target> <note /> </trans-unit> <trans-unit id="ERR_RequiredNewCallTooMany2"> <source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source> <target state="translated">“{1}”的基类“{0}”没有不使用参数就可以调用的可访问“Sub New”,因此该“Sub New”的第一个语句必须是对“MyBase.New”或“MyClass.New”的调用。</target> <note /> </trans-unit> <trans-unit id="ERR_ForCtlVarArraySizesSpecified"> <source>Array declared as for loop control variable cannot be declared with an initial size.</source> <target state="translated">声明用于循环控制变量的数组时不能使用初始大小的值。</target> <note /> </trans-unit> <trans-unit id="ERR_BadFlagsOnNewOverloads"> <source>The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'.</source> <target state="translated">“{0}”关键字用于重载继承的成员;重载“Sub New”时不要使用“{0}”关键字。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharOnGenericParam"> <source>Type character cannot be used in a type parameter declaration.</source> <target state="translated">在类型参数声明中不能使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_TooFewGenericArguments1"> <source>Too few type arguments to '{0}'.</source> <target state="translated">“{0}”的类型参数太少。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyGenericArguments1"> <source>Too many type arguments to '{0}'.</source> <target state="translated">“{0}”的类型参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfied2"> <source>Type argument '{0}' does not inherit from or implement the constraint type '{1}'.</source> <target state="translated">类型参数“{0}”不能继承自或实现约束类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOrMemberNotGeneric1"> <source>'{0}' has no type parameters and so cannot have type arguments.</source> <target state="translated">“{0}”没有类型形参,因此不能有类型实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NewIfNullOnGenericParam"> <source>'New' cannot be used on a type parameter that does not have a 'New' constraint.</source> <target state="translated">'不能在没有 "New" 约束的类型参数上使用 "New"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleClassConstraints1"> <source>Type parameter '{0}' can only have one constraint that is a class.</source> <target state="translated">类型参数“{0}”只能有一个属于类的约束。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstNotClassInterfaceOrTypeParam1"> <source>Type constraint '{0}' must be either a class, interface or type parameter.</source> <target state="translated">类型约束“{0}”必须是类、接口或类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateTypeParamName1"> <source>Type parameter already declared with name '{0}'.</source> <target state="translated">类型参数已使用名称“{0}”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_UnboundTypeParam2"> <source>Type parameter '{0}' for '{1}' cannot be inferred.</source> <target state="translated">无法推断“{1}”的类型参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_IsOperatorGenericParam1"> <source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source> <target state="translated">'类型“{0}”是没有类约束的类型参数,因此类型“{0}”的“Is”操作数只能与“Nothing”比较。</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentCopyBackNarrowing3"> <source>Copying the value of 'ByRef' parameter '{0}' back to the matching argument narrows from type '{1}' to type '{2}'.</source> <target state="translated">将“ByRef”参数“{0}”的值复制回匹配的参数将导致从类型“{1}”到类型“{2}”的收缩。</target> <note /> </trans-unit> <trans-unit id="ERR_ShadowingGenericParamWithMember1"> <source>'{0}' has the same name as a type parameter.</source> <target state="translated">“{0}”与一个类型参数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericParamBase2"> <source>{0} '{1}' cannot inherit from a type parameter.</source> <target state="translated">{0}“{1}”不能从类型参数中继承。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsGenericParam"> <source>Type parameter not allowed in 'Implements' clause.</source> <target state="translated">“Implements”子句中不允许类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyNullLowerBound"> <source>Array lower bounds can be only '0'.</source> <target state="translated">数组的下限只能是“0”。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassConstraintNotInheritable1"> <source>Type constraint cannot be a 'NotInheritable' class.</source> <target state="translated">类型约束不能是“NotInheritable”类。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintIsRestrictedType1"> <source>'{0}' cannot be used as a type constraint.</source> <target state="translated">“{0}”不能用作类型约束。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericParamsOnInvalidMember"> <source>Type parameters cannot be specified on this declaration.</source> <target state="translated">在此声明上不能指定类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericArgsOnAttributeSpecifier"> <source>Type arguments are not valid because attributes cannot be generic.</source> <target state="translated">由于特性不能是泛型,因此类型参数无效。</target> <note /> </trans-unit> <trans-unit id="ERR_AttrCannotBeGenerics"> <source>Type parameters, generic types or types contained in generic types cannot be used as attributes.</source> <target state="translated">类型参数、泛型类型或泛型类型中包含的类型不能用作特性。</target> <note /> </trans-unit> <trans-unit id="ERR_BadStaticLocalInGenericMethod"> <source>Local variables within generic methods cannot be declared 'Static'.</source> <target state="translated">泛型方法中的局部变量不能声明为“Static”。</target> <note /> </trans-unit> <trans-unit id="ERR_SyntMemberShadowsGenericParam3"> <source>{0} '{1}' implicitly defines a member '{2}' which has the same name as a type parameter.</source> <target state="translated">{0}“{1}”隐式定义了与某个类型参数同名的成员“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintAlreadyExists1"> <source>Constraint type '{0}' already specified for this type parameter.</source> <target state="translated">已为此类型参数指定了约束类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacePossiblyImplTwice2"> <source>Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,该接口的实现可能与另一个已实现的接口“{1}”的实现冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ModulesCannotBeGeneric"> <source>Modules cannot be generic.</source> <target state="translated">模块不能是泛型的。</target> <note /> </trans-unit> <trans-unit id="ERR_GenericClassCannotInheritAttr"> <source>Classes that are generic or contained in a generic type cannot inherit from an attribute class.</source> <target state="translated">属于泛型或包含在泛型类型中的类不能从特性类继承。</target> <note /> </trans-unit> <trans-unit id="ERR_DeclaresCantBeInGeneric"> <source>'Declare' statements are not allowed in generic types or types contained in generic types.</source> <target state="translated">'泛型类型或包含在泛型类型中的类型中不允许“Declare”语句。</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithConstraintMismatch2"> <source>'{0}' cannot override '{1}' because they differ by type parameter constraints.</source> <target state="translated">“{0}”无法重写“{1}”,因为它们在类型参数约束上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_ImplementsWithConstraintMismatch3"> <source>'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints.</source> <target state="translated">“{0}”无法实现“{1}.{2}”,因为它们在类型参数约束上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_OpenTypeDisallowed"> <source>Type parameters or types constructed with type parameters are not allowed in attribute arguments.</source> <target state="translated">特性实参中不允许类型形参或用类型形参构造的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_HandlesInvalidOnGenericMethod"> <source>Generic methods cannot use 'Handles' clause.</source> <target state="translated">泛型方法不能使用“Handles”子句。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleNewConstraints"> <source>'New' constraint cannot be specified multiple times for the same type parameter.</source> <target state="translated">'"New" 约束不能为同一类型参数指定多次。</target> <note /> </trans-unit> <trans-unit id="ERR_MustInheritForNewConstraint2"> <source>Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”声明为“MustInherit”,并且不满足类型形参“{1}”的“New”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuitableNewForNewConstraint2"> <source>Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”必须具有一个公共的无参数实例构造函数,才能满足类型形参“{1}”的“New”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_BadGenericParamForNewConstraint2"> <source>Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'.</source> <target state="translated">类型参数“{0}”必须具有“New”约束或“Structure”约束,才能满足类型参数“{1}”的“New”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_NewArgsDisallowedForTypeParam"> <source>Arguments cannot be passed to a 'New' used on a type parameter.</source> <target state="translated">无法给类型形参上使用的 "New" 传递实参。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateRawGenericTypeImport1"> <source>Generic type '{0}' cannot be imported more than once.</source> <target state="translated">不能多次导入泛型类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypeArgumentCountOverloadCand1"> <source>Overload resolution failed because no accessible '{0}' accepts this number of type arguments.</source> <target state="translated">重载决策失败,因为没有可访问的“{0}”接受此数量的类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeArgsUnexpected"> <source>Type arguments unexpected.</source> <target state="translated">不应为类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_NameSameAsMethodTypeParam1"> <source>'{0}' is already declared as a type parameter of this method.</source> <target state="translated">“{0}”已声明为此方法的类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamNameFunctionNameCollision"> <source>Type parameter cannot have the same name as its defining function.</source> <target state="translated">类型参数不能与其定义函数同名。</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstraintSyntax"> <source>Type or 'New' expected.</source> <target state="translated">应为类型或“New”。</target> <note /> </trans-unit> <trans-unit id="ERR_OfExpected"> <source>'Of' required when specifying type arguments for a generic type or method.</source> <target state="translated">'在指定泛型类型或方法的类型参数时需要 "Of"。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayOfRawGenericInvalid"> <source>'(' unexpected. Arrays of uninstantiated generic types are not allowed.</source> <target state="translated">'不应为 "("。不允许非实例化泛型类型的数组。</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachAmbiguousIEnumerable1"> <source>'For Each' on type '{0}' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'.</source> <target state="translated">'类型“{0}”的“For Each”不明确,因为此类型实现了“System.Collections.Generic.IEnumerable(Of T)”的多个实例化。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNotOperatorGenericParam1"> <source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source> <target state="translated">'类型“{0}”是没有类约束的类型参数,因此类型“{0}”的“Isnot”操作数只能与“Nothing”比较。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamQualifierDisallowed"> <source>Type parameters cannot be used as qualifiers.</source> <target state="translated">类型参数不能用作限定符。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamMissingCommaOrRParen"> <source>Comma or ')' expected.</source> <target state="translated">应为逗号或 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamMissingAsCommaOrRParen"> <source>'As', comma or ')' expected.</source> <target state="translated">'应为 "As"、逗号或 ")"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleReferenceConstraints"> <source>'Class' constraint cannot be specified multiple times for the same type parameter.</source> <target state="translated">'"Class" 约束不能为同一类型参数指定多次。</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleValueConstraints"> <source>'Structure' constraint cannot be specified multiple times for the same type parameter.</source> <target state="translated">'"Structure" 约束不能为同一类型参数指定多次。</target> <note /> </trans-unit> <trans-unit id="ERR_NewAndValueConstraintsCombined"> <source>'New' constraint and 'Structure' constraint cannot be combined.</source> <target state="translated">'"New" 约束不能与 "Structure" 约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_RefAndValueConstraintsCombined"> <source>'Class' constraint and 'Structure' constraint cannot be combined.</source> <target state="translated">'"Class" 约束不能与 "Structure" 约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgForStructConstraint2"> <source>Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”不满足类型形参“{1}”的“Structure”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgForRefConstraint2"> <source>Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'.</source> <target state="translated">类型实参“{0}”不满足类型形参“{1}”的“Class”约束。</target> <note /> </trans-unit> <trans-unit id="ERR_RefAndClassTypeConstrCombined"> <source>'Class' constraint and a specific class type constraint cannot be combined.</source> <target state="translated">'"Class" 约束不能与特定的类类型约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_ValueAndClassTypeConstrCombined"> <source>'Structure' constraint and a specific class type constraint cannot be combined.</source> <target state="translated">'"Structure" 约束不能与特定的类类型约束组合。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintClashIndirectIndirect4"> <source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'.</source> <target state="translated">从类型参数约束“{1}”获得的间接约束“{0}”与从类型参数约束“{3}”获得的间接约束“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintClashDirectIndirect3"> <source>Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'.</source> <target state="translated">约束“{0}”与从类型参数约束“{2}”获得的间接约束“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintClashIndirectDirect3"> <source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'.</source> <target state="translated">从类型参数约束“{1}”获得的间接约束“{0}”与约束“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintCycleLink2"> <source> '{0}' is constrained to '{1}'.</source> <target state="translated"> “{0}”被约束为“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintCycle2"> <source>Type parameter '{0}' cannot be constrained to itself: {1}</source> <target state="translated">类型参数“{0}”不能约束为自身: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamWithStructConstAsConst"> <source>Type parameter with a 'Structure' constraint cannot be used as a constraint.</source> <target state="translated">具有 "Structure" 约束的类型参数不能用作约束。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableDisallowedForStructConstr1"> <source>'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed.</source> <target state="translated">'“System.Nullable”不满足类型参数“{0}”的“Structure”约束。仅允许不可为 null 的“Structure”类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingDirectConstraints3"> <source>Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'.</source> <target state="translated">约束“{0}”与已为类型参数“{2}”指定的约束“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceUnifiesWithInterface2"> <source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,该接口与接口“{1}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_BaseUnifiesWithInterfaces3"> <source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,它所继承的接口“{1}”可能与接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceBaseUnifiesWithBase4"> <source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the interface '{3}' inherits for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,继承的接口“{1}”可能与接口“{3}”继承的接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceUnifiesWithBase3"> <source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' from which the interface '{2}' inherits for some type arguments.</source> <target state="translated">无法继承接口“{0}”,因为对于某些类型参数,该接口与接口“{2}”继承的接口“{1}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassInheritsBaseUnifiesWithInterfaces3"> <source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to implemented interface '{2}' for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,它所继承的接口“{1}”可能与实现的接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassInheritsInterfaceBaseUnifiesWithBase4"> <source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the implemented interface '{3}' inherits for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,它所继承的接口“{1}”可能与实现的接口“{3}”所继承的接口“{2}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ClassInheritsInterfaceUnifiesWithBase3"> <source>Cannot implement interface '{0}' because it could be identical to interface '{1}' from which the implemented interface '{2}' inherits for some type arguments.</source> <target state="translated">无法实现接口“{0}”,因为对于某些类型参数,它可能与实现的接口“{2}”所继承的接口“{1}”相同。</target> <note /> </trans-unit> <trans-unit id="ERR_OptionalsCantBeStructGenericParams"> <source>Generic parameters used as optional parameter types must be class constrained.</source> <target state="translated">用作可选参数类型的泛型参数必须受类约束。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfNullableMethod"> <source>Methods of 'System.Nullable(Of T)' cannot be used as operands of the 'AddressOf' operator.</source> <target state="translated">“System.Nullable(Of T)”的方法不能用作“AddressOf”运算符的操作数。</target> <note /> </trans-unit> <trans-unit id="ERR_IsOperatorNullable1"> <source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source> <target state="translated">'类型“{0}”是可以为 null 的类型,因此“{0}”的“Is”操作数只能与“Nothing”进行比较。</target> <note /> </trans-unit> <trans-unit id="ERR_IsNotOperatorNullable1"> <source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source> <target state="translated">'类型“{0}”是可以为 null 的类型,因此“{0}”的“IsNot”操作数只能与“Nothing”进行比较。</target> <note /> </trans-unit> <trans-unit id="ERR_ShadowingTypeOutsideClass1"> <source>'{0}' cannot be declared 'Shadows' outside of a class, structure, or interface.</source> <target state="translated">“{0}”不能在类、结构或接口外声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertySetParamCollisionWithValue"> <source>Property parameters cannot have the name 'Value'.</source> <target state="translated">属性参数的名称不能为 "Value"。</target> <note /> </trans-unit> <trans-unit id="ERR_SxSIndirectRefHigherThanDirectRef3"> <source>The project currently contains references to more than one version of '{0}', a direct reference to version {2} and an indirect reference to version {1}. Change the direct reference to use version {1} (or higher) of {0}.</source> <target state="translated">项目当前包含对多个版本的“{0}”的引用、对版本 {2} 的直接引用和对版本 {1} 的间接引用。请将直接引用更改为使用 {0} 的版本 {1} (或更高版本)。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateReferenceStrong"> <source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source> <target state="translated">导入了具有等效标识的多个程序集:“{0}”和“{1}”。请删除重复引用之一。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateReference2"> <source>Project already has a reference to assembly '{0}'. A second reference to '{1}' cannot be added.</source> <target state="translated">项目已经具有对程序集“{0}”的引用。无法添加另一个对“{1}”的引用。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalCallOrIndex"> <source>Illegal call expression or index expression.</source> <target state="translated">非法的调用表达式或索引表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictDefaultPropertyAttribute"> <source>Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'.</source> <target state="translated">默认属性与“{0}”上定义的“DefaultMemberAttribute”之间有冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeUuid2"> <source>'{0}' cannot be applied because the format of the GUID '{1}' is not correct.</source> <target state="translated">'GUID“{1}”的格式不正确,因此无法应用“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassAndReservedAttribute1"> <source>'Microsoft.VisualBasic.ComClassAttribute' and '{0}' cannot both be applied to the same class.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”和“{0}”不能同时应用于同一个类。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassRequiresPublicClass2"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because its container '{1}' is not declared 'Public'.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”的容器“{1}”未声明为“Public”,因此不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassReservedDispIdZero1"> <source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”为默认属性保留的值为零,因此“System.Runtime.InteropServices.DispIdAttribute”不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassReservedDispId1"> <source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”保留的值小于零,因此“System.Runtime.InteropServices.DispIdAttribute”不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassDuplicateGuids1"> <source>'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on '{0}' cannot have the same value.</source> <target state="translated">“{0}”上“Microsoft.VisualBasic.ComClassAttribute”的“InterfaceId”和“EventsId”参数的值不能相同。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassCantBeAbstract0"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”不能应用于被声明为“MustInherit”的类。</target> <note /> </trans-unit> <trans-unit id="ERR_ComClassRequiresPublicClass1"> <source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because it is not declared 'Public'.</source> <target state="translated">'“Microsoft.VisualBasic.ComClassAttribute”未声明为“Public”,因此不能应用于“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UnknownOperator"> <source>Operator declaration must be one of: +, -, *, \, /, ^, &amp;, Like, Mod, And, Or, Xor, Not, &lt;&lt;, &gt;&gt;, =, &lt;&gt;, &lt;, &lt;=, &gt;, &gt;=, CType, IsTrue, IsFalse.</source> <target state="translated">运算符声明必须是以下符号之一: +、-、*、\、/、^、&amp;,、Like、Mod、And、Or、Xor、Not、&lt;&lt;、&gt;&gt;、=、&lt;&gt;、&lt;、&lt;=、&gt;、&gt;=、CType、IsTrue 和 IsFalse。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateConversionCategoryUsed"> <source>'Widening' and 'Narrowing' cannot be combined.</source> <target state="translated">'"Widening" 不能与 "Narrowing" 组合。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorNotOverloadable"> <source>Operator is not overloadable. Operator declaration must be one of: +, -, *, \, /, ^, &amp;, Like, Mod, And, Or, Xor, Not, &lt;&lt;, &gt;&gt;, =, &lt;&gt;, &lt;, &lt;=, &gt;, &gt;=, CType, IsTrue, IsFalse.</source> <target state="translated">运算符不可重载。运算符声明必须是以下符号之一: +、-、*、\、/、^、&amp;,、Like、Mod、And、Or、Xor、Not、&lt;&lt;、&gt;&gt;、=、&lt;&gt;、&lt;、&lt;=、&gt;、&gt;=、CType、IsTrue 和 IsFalse。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidHandles"> <source>'Handles' is not valid on operator declarations.</source> <target state="translated">'“Handles”在运算符声明上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidImplements"> <source>'Implements' is not valid on operator declarations.</source> <target state="translated">'“Implements”在运算符声明上无效。</target> <note /> </trans-unit> <trans-unit id="ERR_EndOperatorExpected"> <source>'End Operator' expected.</source> <target state="translated">'应为 "End Operator"。</target> <note /> </trans-unit> <trans-unit id="ERR_EndOperatorNotAtLineStart"> <source>'End Operator' must be the first statement on a line.</source> <target state="translated">'“End Operator”必须是一行中的第一条语句。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidEndOperator"> <source>'End Operator' must be preceded by a matching 'Operator'.</source> <target state="translated">'“End Operator”前面必须是匹配的“Operator”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExitOperatorNotValid"> <source>'Exit Operator' is not valid. Use 'Return' to exit an operator.</source> <target state="translated">'"Exit Operator" 无效。请使用 "Return" 从运算符中退出。</target> <note /> </trans-unit> <trans-unit id="ERR_ParamArrayIllegal1"> <source>'{0}' parameters cannot be declared 'ParamArray'.</source> <target state="translated">“{0}”参数不能声明为 "ParamArray"。</target> <note /> </trans-unit> <trans-unit id="ERR_OptionalIllegal1"> <source>'{0}' parameters cannot be declared 'Optional'.</source> <target state="translated">“{0}”参数不能声明为“Optional”。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorMustBePublic"> <source>Operators must be declared 'Public'.</source> <target state="translated">运算符必须声明为 "Public"。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorMustBeShared"> <source>Operators must be declared 'Shared'.</source> <target state="translated">运算符必须声明为 "Shared"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadOperatorFlags1"> <source>Operators cannot be declared '{0}'.</source> <target state="translated">运算符不能声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OneParameterRequired1"> <source>Operator '{0}' must have one parameter.</source> <target state="translated">运算符“{0}”必须有一个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TwoParametersRequired1"> <source>Operator '{0}' must have two parameters.</source> <target state="translated">运算符“{0}”必须有两个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OneOrTwoParametersRequired1"> <source>Operator '{0}' must have either one or two parameters.</source> <target state="translated">运算符“{0}”必须有一个两个参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvMustBeWideningOrNarrowing"> <source>Conversion operators must be declared either 'Widening' or 'Narrowing'.</source> <target state="translated">转换运算符必须声明为“Widening”或者“Narrowing”。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorDeclaredInModule"> <source>Operators cannot be declared in modules.</source> <target state="translated">运算符不能在模块中声明。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSpecifierOnNonConversion1"> <source>Only conversion operators can be declared '{0}'.</source> <target state="translated">只有转换运算符可以声明为“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_UnaryParamMustBeContainingType1"> <source>Parameter of this unary operator must be of the containing type '{0}'.</source> <target state="translated">此一元运算符的参数必须属于包含类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryParamMustBeContainingType1"> <source>At least one parameter of this binary operator must be of the containing type '{0}'.</source> <target state="translated">此二元运算符的至少一个参数必须属于包含类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConvParamMustBeContainingType1"> <source>Either the parameter type or the return type of this conversion operator must be of the containing type '{0}'.</source> <target state="translated">此转换运算符的参数类型或返回类型必须属于包含类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorRequiresBoolReturnType1"> <source>Operator '{0}' must have a return type of Boolean.</source> <target state="translated">运算符“{0}”必须具有 Boolean 返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToSameType"> <source>Conversion operators cannot convert from a type to the same type.</source> <target state="translated">转换运算符不能从某一类型转换为相同的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToInterfaceType"> <source>Conversion operators cannot convert to an interface type.</source> <target state="translated">转换运算符不能转换为接口类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToBaseType"> <source>Conversion operators cannot convert from a type to its base type.</source> <target state="translated">转换运算符不能从某一类型转换为它的基类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToDerivedType"> <source>Conversion operators cannot convert from a type to its derived type.</source> <target state="translated">转换运算符不能从某一类型转换为它的派生类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionToObject"> <source>Conversion operators cannot convert to Object.</source> <target state="translated">转换运算符不能转换为 Object。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromInterfaceType"> <source>Conversion operators cannot convert from an interface type.</source> <target state="translated">转换运算符不能从接口类型转换。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromBaseType"> <source>Conversion operators cannot convert from a base type.</source> <target state="translated">转换运算符不能从基类型转换。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromDerivedType"> <source>Conversion operators cannot convert from a derived type.</source> <target state="translated">转换运算符不能从派生类型转换。</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionFromObject"> <source>Conversion operators cannot convert from Object.</source> <target state="translated">转换运算符不能从 Object 转换。</target> <note /> </trans-unit> <trans-unit id="ERR_MatchingOperatorExpected2"> <source>Matching '{0}' operator is required for '{1}'.</source> <target state="translated">“{1}”需要匹配“{0}”运算符。</target> <note /> </trans-unit> <trans-unit id="ERR_UnacceptableLogicalOperator3"> <source>Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression.</source> <target state="translated">“{0}”的返回类型和参数类型必须是“{1}”,才能在“{2}”表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionOperatorRequired3"> <source>Type '{0}' must define operator '{1}' to be used in a '{2}' expression.</source> <target state="translated">类型“{0}”必须定义运算符“{1}”,才能在“{2}”表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CopyBackTypeMismatch3"> <source>Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'.</source> <target state="translated">由于类型“{1}”不能转换为类型“{2}”,因此无法将“ByRef”参数“{0}”的值复制回匹配的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_ForLoopOperatorRequired2"> <source>Type '{0}' must define operator '{1}' to be used in a 'For' statement.</source> <target state="translated">类型“{0}”必须定义运算符“{1}”,才能在“For”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_UnacceptableForLoopOperator2"> <source>Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source> <target state="translated">“{0}”的返回类型和参数类型必须是“{1}”,才能在“For”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_UnacceptableForLoopRelOperator2"> <source>Parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source> <target state="translated">“{0}”的参数类型必须是“{1}”,才能在“For”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorRequiresIntegerParameter1"> <source>Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'.</source> <target state="translated">运算符“{0}”必须有另一个“Integer”或“Integer?”类型的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyNullableOnBoth"> <source>Nullable modifier cannot be specified on both a variable and its type.</source> <target state="translated">不能在变量及其类型上同时指定可以为 null 的修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgForStructConstraintNull"> <source>Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.</source> <target state="translated">类型“{0}”必须是一个被约束为“Structure”的值类型或类型参数,才能与“Nullable”或可以为 null 的修饰符“?”一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyArrayAndNullableOnBoth"> <source>Nullable modifier '?' and array modifiers '(' and ')' cannot be specified on both a variable and its type.</source> <target state="translated">不能在变量及其类型上同时指定可为 null 的修饰符“?”和数组修饰符“(”/“)”。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyTypeCharacterOnIIF"> <source>Expressions used with an 'If' expression cannot contain type characters.</source> <target state="translated">与“If”表达式一起使用的表达式不能包含类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFName"> <source>'If' operands cannot be named arguments.</source> <target state="translated">'“If”操作数不能是命名参数。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFConversion"> <source>Cannot infer a common type for the second and third operands of the 'If' operator. One must have a widening conversion to the other.</source> <target state="translated">无法推断“If”运算符的第二个和第三个操作数的通用类型。其中一个必须是另一个的扩大转换。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalCondTypeInIIF"> <source>First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type.</source> <target state="translated">二进制“If”表达式中的第一个操作数必须是可以为 null 的类型或引用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CantCallIIF"> <source>'If' operator cannot be used in a 'Call' statement.</source> <target state="translated">'“If”运算符不能在“Call”语句中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyAsNewAndNullable"> <source>Nullable modifier cannot be specified in variable declarations with 'As New'.</source> <target state="translated">在变量声明中不能用“As New”指定可以为 null 的修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFConversion2"> <source>Cannot infer a common type for the first and second operands of the binary 'If' operator. One must have a widening conversion to the other.</source> <target state="translated">无法推断二元“If”运算符的第一个和第二个操作数的通用类型。其中一个必须是另一个的扩大转换。</target> <note /> </trans-unit> <trans-unit id="ERR_BadNullTypeInCCExpression"> <source>Nullable types are not allowed in conditional compilation expressions.</source> <target state="translated">在条件编译表达式中不允许有可以为 null 的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableImplicit"> <source>Nullable modifier cannot be used with a variable whose implicit type is 'Object'.</source> <target state="translated">可以为 null 的修饰符不能与隐式类型为 "Object" 的变量一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingRuntimeHelper"> <source>Requested operation is not available because the runtime library function '{0}' is not defined.</source> <target state="translated">所请求的操作不可用,因为没有定义运行库函数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedDotAfterGlobalNameSpace"> <source>'Global' must be followed by '.' and an identifier.</source> <target state="translated">'“Global”的后面必须跟有“.”和标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_NoGlobalExpectedIdentifier"> <source>'Global' not allowed in this context; identifier expected.</source> <target state="translated">'此上下文中不允许 "Global";应为标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_NoGlobalInHandles"> <source>'Global' not allowed in handles; local name expected.</source> <target state="translated">'句柄中不允许 "Global";应为本地名称。</target> <note /> </trans-unit> <trans-unit id="ERR_ElseIfNoMatchingIf"> <source>'ElseIf' must be preceded by a matching 'If' or 'ElseIf'.</source> <target state="translated">'"ElseIf" 前面必须是匹配的 "If" 或 "ElseIf"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeConstructor2"> <source>Attribute constructor has a 'ByRef' parameter of type '{0}'; cannot use constructors with byref parameters to apply the attribute.</source> <target state="translated">特性构造函数有一个“{0}”类型的“ByRef”参数;不能用带有 byref 参数的构造函数来应用特性。</target> <note /> </trans-unit> <trans-unit id="ERR_EndUsingWithoutUsing"> <source>'End Using' must be preceded by a matching 'Using'.</source> <target state="translated">'“End Using”前面必须是匹配的“Using”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndUsing"> <source>'Using' must end with a matching 'End Using'.</source> <target state="translated">'“Using”必须以匹配的“End Using”结束。</target> <note /> </trans-unit> <trans-unit id="ERR_GotoIntoUsing"> <source>'GoTo {0}' is not valid because '{0}' is inside a 'Using' statement that does not contain this statement.</source> <target state="translated">'“GoTo {0}”无效,因为“{0}”位于不包含此语句的“Using”语句中。</target> <note /> </trans-unit> <trans-unit id="ERR_UsingRequiresDisposePattern"> <source>'Using' operand of type '{0}' must implement 'System.IDisposable'.</source> <target state="translated">“{0}”类型的“Using”操作数必须实现“System.IDisposable”。</target> <note /> </trans-unit> <trans-unit id="ERR_UsingResourceVarNeedsInitializer"> <source>'Using' resource variable must have an explicit initialization.</source> <target state="translated">'"Using" 资源变量必须有一个显式初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_UsingResourceVarCantBeArray"> <source>'Using' resource variable type can not be array type.</source> <target state="translated">'"Using" 资源变量类型不能是数组类型。</target> <note /> </trans-unit> <trans-unit id="ERR_OnErrorInUsing"> <source>'On Error' statements are not valid within 'Using' statements.</source> <target state="translated">'"On Error" 语句在 "Using" 语句内无效。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyNameConflictInMyCollection"> <source>'{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace.</source> <target state="translated">“{0}”与“My”组中公开的类型“{1}”所使用的成员同名。请重命名该类型或其封闭命名空间。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidImplicitVar"> <source>Implicit variable '{0}' is invalid because of '{1}'.</source> <target state="translated">由于“{1}”,隐式变量“{0}”无效。</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectInitializerRequiresFieldName"> <source>Object initializers require a field name to initialize.</source> <target state="translated">对象初始值设定项需要一个字段名称以便进行初始化。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedFrom"> <source>'From' expected.</source> <target state="translated">'应为“From”。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaBindingMismatch1"> <source>Nested function does not have the same signature as delegate '{0}'.</source> <target state="translated">嵌套函数与委托“{0}”的签名不相同。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaBindingMismatch2"> <source>Nested sub does not have a signature that is compatible with delegate '{0}'.</source> <target state="translated">嵌套 Sub 的签名与委托“{0}”不兼容。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftByRefParamQuery1"> <source>'ByRef' parameter '{0}' cannot be used in a query expression.</source> <target state="translated">'不能在查询表达式中使用“ByRef”参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeNotSupported"> <source>Expression cannot be converted into an expression tree.</source> <target state="translated">无法将表达式转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftStructureMeQuery"> <source>Instance members and 'Me' cannot be used within query expressions in structures.</source> <target state="translated">无法在结构中的查询表达式中使用实例成员和“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_InferringNonArrayType1"> <source>Variable cannot be initialized with non-array type '{0}'.</source> <target state="translated">无法用非数组类型“{0}”初始化变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefParamInExpressionTree"> <source>References to 'ByRef' parameters cannot be converted to an expression tree.</source> <target state="translated">对“ByRef”参数的引用无法转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAnonTypeMemberName1"> <source>Anonymous type member or property '{0}' is already declared.</source> <target state="translated">已声明匿名类型成员或属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAnonymousTypeForExprTree"> <source>Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.</source> <target state="translated">无法将匿名类型转换为表达式树,因为此类型的属性用于初始化其他属性。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftAnonymousType1"> <source>Anonymous type property '{0}' cannot be used in the definition of a lambda expression within the same initialization list.</source> <target state="translated">不能在同一个初始化列表中的 lambda 表达式定义中使用匿名类型属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionOnlyAllowedOnModuleSubOrFunction"> <source>'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations.</source> <target state="translated">'“Extension”特性只能应用于“Module”、“Sub”或“Function”声明。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodNotInModule"> <source>Extension methods can be defined only in modules.</source> <target state="translated">只能在模块中定义扩展方法。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodNoParams"> <source>Extension methods must declare at least one parameter. The first parameter specifies which type to extend.</source> <target state="translated">扩展方法必须至少声明一个参数。第一个参数指定要扩展的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodOptionalFirstArg"> <source>'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source> <target state="translated">'“Optional”无法应用于扩展方法的第一个参数。第一个参数指定要扩展哪个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodParamArrayFirstArg"> <source>'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source> <target state="translated">"ParamArray" 无法应用于扩展方法的第一个参数。第一个参数指定要扩展哪个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeFieldNameInference"> <source>Anonymous type member name can be inferred only from a simple or qualified name with no arguments.</source> <target state="translated">只能从不带参数的简单名或限定名中推断匿名类型成员名称。</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotMemberOfAnonymousType2"> <source>'{0}' is not a member of '{1}'; it does not exist in the current context.</source> <target state="translated">“{0}”不是“{1}”的成员;它不存在于当前上下文。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionAttributeInvalid"> <source>The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods.</source> <target state="translated">编译器找到的“System.Runtime.CompilerServices.ExtensionAttribute”的自定义设计版本无效。必须将其特性用法标志设置为允许程序集、类和方法使用。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypePropertyOutOfOrder1"> <source>Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established.</source> <target state="translated">无法使用匿名类型成员属性“{0}”来推断另一个成员属性的类型,因为尚未建立“{0}”的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeDisallowsTypeChar"> <source>Type characters cannot be used in anonymous type declarations.</source> <target state="translated">不能在匿名类型声明中使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleLiteralDisallowsTypeChar"> <source>Type characters cannot be used in tuple literals.</source> <target state="translated">类型字符无法用在元组文本中。</target> <note /> </trans-unit> <trans-unit id="ERR_NewWithTupleTypeSyntax"> <source>'New' cannot be used with tuple type. Use a tuple literal expression instead.</source> <target state="translated">"New" 不能与元组类型共同使用。请改用元组字面量表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct"> <source>Predefined type '{0}' must be a structure.</source> <target state="translated">预定义的类型“{0}”必须是一种结构。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodUncallable1"> <source>Extension method '{0}' has type constraints that can never be satisfied.</source> <target state="translated">扩展方法“{0}”具有无法满足的类型约束。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodOverloadCandidate3"> <source> Extension method '{0}' defined in '{1}': {2}</source> <target state="translated"> “{1}”中定义的扩展方法“{0}”: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingMismatch"> <source>Method does not have a signature compatible with the delegate.</source> <target state="translated">方法没有与委托兼容的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingTypeInferenceFails"> <source>Type arguments could not be inferred from the delegate.</source> <target state="translated">未能从委托中推断类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyArgs"> <source>Too many arguments.</source> <target state="translated">参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgAlsoOmitted1"> <source>Parameter '{0}' already has a matching omitted argument.</source> <target state="translated">形参“{0}”已具有匹配的省略实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgUsedTwice1"> <source>Parameter '{0}' already has a matching argument.</source> <target state="translated">形参“{0}”已具有匹配的实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamNotFound1"> <source>'{0}' is not a method parameter.</source> <target state="translated">“{0}”不是方法参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedArgument1"> <source>Argument not specified for parameter '{0}'.</source> <target state="translated">没有为参数“{0}”指定参数。</target> <note /> </trans-unit> <trans-unit id="ERR_UnboundTypeParam1"> <source>Type parameter '{0}' cannot be inferred.</source> <target state="translated">无法推断类型参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodOverloadCandidate2"> <source> Extension method '{0}' defined in '{1}'.</source> <target state="translated"> “{1}”中定义的扩展方法“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeNeedField"> <source>Anonymous type must contain at least one member.</source> <target state="translated">匿名类型必须至少包含一个成员。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeNameWithoutPeriod"> <source>Anonymous type member name must be preceded by a period.</source> <target state="translated">匿名类型成员名前面必须有一个句点。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeExpectedIdentifier"> <source>Identifier expected, preceded with a period.</source> <target state="translated">应为开头带有句点的标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyArgs2"> <source>Too many arguments to extension method '{0}' defined in '{1}'.</source> <target state="translated">对“{1}”中定义的扩展方法“{0}”而言,参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgAlsoOmitted3"> <source>Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument.</source> <target state="translated">“{2}”中定义的扩展方法中的“{1}”形参“{0}”已具有匹配的省略实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgUsedTwice3"> <source>Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument.</source> <target state="translated">“{2}”中定义的扩展方法“{1}”的形参“{0}”已具有匹配的实参。</target> <note /> </trans-unit> <trans-unit id="ERR_NamedParamNotFound3"> <source>'{0}' is not a parameter of extension method '{1}' defined in '{2}'.</source> <target state="translated">“{0}”不是“{2}”中定义的扩展方法“{1}”的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedArgument3"> <source>Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'.</source> <target state="translated">没有为“{2}”中定义的扩展方法“{1}”的形参“{0}”指定实参。</target> <note /> </trans-unit> <trans-unit id="ERR_UnboundTypeParam3"> <source>Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred.</source> <target state="translated">无法推断“{2}”中定义的扩展方法“{1}”的类型参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TooFewGenericArguments2"> <source>Too few type arguments to extension method '{0}' defined in '{1}'.</source> <target state="translated">对“{1}”中定义的扩展方法“{0}”而言,类型参数太少。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyGenericArguments2"> <source>Too many type arguments to extension method '{0}' defined in '{1}'.</source> <target state="translated">对“{1}”中定义的扩展方法“{0}”而言,类型参数太多。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedInOrEq"> <source>'In' or '=' expected.</source> <target state="translated">'应为“In”或“=”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedQueryableSource"> <source>Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.</source> <target state="translated">类型“{0}”的表达式不可查询。请确保不缺少程序集引用和/或 LINQ 提供程序的命名空间导入。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryOperatorNotFound"> <source>Definition of method '{0}' is not accessible in this context.</source> <target state="translated">方法“{0}”的定义在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseOnErrorGotoWithClosure"> <source>Method cannot contain both a '{0}' statement and a definition of a variable that is used in a lambda or query expression.</source> <target state="translated">方法不能同时包含“{0}”语句以及在 lambda 或查询表达式中使用的变量的定义。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotGotoNonScopeBlocksWithClosure"> <source>'{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression.</source> <target state="translated">“{0}{1}”无效,因为“{2}”所在的范围定义一个用在 lambda 表达式或查询表达式中的变量。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftRestrictedTypeQuery"> <source>Instance of restricted type '{0}' cannot be used in a query expression.</source> <target state="translated">不能在查询表达式中使用受限类型“{0}”的实例。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryAnonymousTypeFieldNameInference"> <source>Range variable name can be inferred only from a simple or qualified name with no arguments.</source> <target state="translated">只能从不带参数的简单名或限定名中推断范围变量名。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryDuplicateAnonTypeMemberName1"> <source>Range variable '{0}' is already declared.</source> <target state="translated">已声明范围变量“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryAnonymousTypeDisallowsTypeChar"> <source>Type characters cannot be used in range variable declarations.</source> <target state="translated">在范围变量声明中不能使用类型字符。</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyInClosure"> <source>'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.</source> <target state="translated">'在构造函数内的 lambda 表达式中,"ReadOnly" 变量不能作为赋值的目标。</target> <note /> </trans-unit> <trans-unit id="ERR_ExprTreeNoMultiDimArrayCreation"> <source>Multi-dimensional array cannot be converted to an expression tree.</source> <target state="translated">多维数组无法转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_ExprTreeNoLateBind"> <source>Late binding operations cannot be converted to an expression tree.</source> <target state="translated">后期绑定操作无法转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedBy"> <source>'By' expected.</source> <target state="translated">'应为 "By"。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryInvalidControlVariableName1"> <source>Range variable name cannot match the name of a member of the 'Object' class.</source> <target state="translated">范围变量名无法与 "Object" 类的成员名匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIn"> <source>'In' expected.</source> <target state="translated">'应为“In”。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNameNotDeclared"> <source>Name '{0}' is either not declared or not in the current scope.</source> <target state="translated">名称“{0}”未声明或不在当前作用域中。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedFunctionArgumentNarrowing3"> <source>Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'.</source> <target state="translated">与参数“{0}”匹配的嵌套函数的返回类型从“{1}”收缩到“{2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AnonTypeFieldXMLNameInference"> <source>Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source> <target state="translated">无法根据不是有效 Visual Basic 标识符的 XML 标识符推断出匿名类型成员名称。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryAnonTypeFieldXMLNameInference"> <source>Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source> <target state="translated">无法根据不是有效 Visual Basic 标识符的 XML 标识符推断出范围变量名。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedInto"> <source>'Into' expected.</source> <target state="translated">'应为“Into”。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeCharOnAggregation"> <source>Aggregate function name cannot be used with a type character.</source> <target state="translated">聚合函数名不能与类型字符一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedOn"> <source>'On' expected.</source> <target state="translated">'应为 "On"。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEquals"> <source>'Equals' expected.</source> <target state="translated">'应为“Equals”。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedAnd"> <source>'And' expected.</source> <target state="translated">'应为 "And"。</target> <note /> </trans-unit> <trans-unit id="ERR_EqualsTypeMismatch"> <source>'Equals' cannot compare a value of type '{0}' with a value of type '{1}'.</source> <target state="translated">'“Equals”不能对类型为“{0}”的值与类型“{1}”的值进行比较。</target> <note /> </trans-unit> <trans-unit id="ERR_EqualsOperandIsBad"> <source>You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) {0} must appear on one side of the 'Equals' operator, and range variable(s) {1} must appear on the other.</source> <target state="translated">“Equals”运算符的每一侧都必须至少引用一个范围变量。范围变量 {0} 必须出现在“Equals”运算符的一侧,范围变量 {1} 必须出现在另一侧。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNotDelegate1"> <source>Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source> <target state="translated">Lambda 表达式无法转换为“{0}”,因为“{0}”不是委托类型。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNotCreatableDelegate1"> <source>Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source> <target state="translated">Lambda 表达式无法转换为“{0}”,因为类型“{0}”被声明为“MustInherit”,无法创建。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotInferNullableForVariable1"> <source>A nullable type cannot be inferred for variable '{0}'.</source> <target state="translated">对于变量“{0}”不能推断可以为 null 的类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableTypeInferenceNotSupported"> <source>Nullable type inference is not supported in this context.</source> <target state="translated">在该上下文中不支持可以为 null 的类型推理。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedJoin"> <source>'Join' expected.</source> <target state="translated">'应为“Join”。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableParameterMustSpecifyType"> <source>Nullable parameters must specify a type.</source> <target state="translated">可以为 null 的参数必须指定一个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_IterationVariableShadowLocal2"> <source>Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source> <target state="translated">范围变量“{0}”隐藏封闭块中的某个变量、以前定义的某个范围变量或者在查询表达式中隐式声明的某个变量。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdasCannotHaveAttributes"> <source>Attributes cannot be applied to parameters of lambda expressions.</source> <target state="translated">特性不能应用于 lambda 表达式的参数。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaInSelectCaseExpr"> <source>Lambda expressions are not valid in the first expression of a 'Select Case' statement.</source> <target state="translated">Lambda 表达式在 "Select Case" 语句的第一个表达式中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfInSelectCaseExpr"> <source>'AddressOf' expressions are not valid in the first expression of a 'Select Case' statement.</source> <target state="translated">'“AddressOf”表达式在“Select Case”语句的第一个表达式中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_NullableCharNotSupported"> <source>The '?' character cannot be used here.</source> <target state="translated">此处不能使用 "?" 字符。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftStructureMeLambda"> <source>Instance members and 'Me' cannot be used within a lambda expression in structures.</source> <target state="translated">无法在结构中的 lambda 表达式内使用实例成员和“Me”。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftByRefParamLambda1"> <source>'ByRef' parameter '{0}' cannot be used in a lambda expression.</source> <target state="translated">'不能在 lambda 表达式中使用“ByRef”参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftRestrictedTypeLambda"> <source>Instance of restricted type '{0}' cannot be used in a lambda expression.</source> <target state="translated">不能在 lambda 表达式中使用受限类型“{0}”的实例。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaParamShadowLocal1"> <source>Lambda parameter '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source> <target state="translated">Lambda 参数“{0}”隐藏封闭块中的某个变量、以前定义的某个范围变量或者在查询表达式中隐式声明的某个变量。</target> <note /> </trans-unit> <trans-unit id="ERR_StrictDisallowImplicitObjectLambda"> <source>Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.</source> <target state="translated">Option Strict On 要求使用 "As" 子句来声明其类型无法推断的每个 lambda 表达式参数。</target> <note /> </trans-unit> <trans-unit id="ERR_CantSpecifyParamsOnLambdaParamNoType"> <source>Array modifiers cannot be specified on lambda expression parameter name. They must be specified on its type.</source> <target state="translated">不能在 lambda 表达式的参数名中指定数组修饰符。数组修饰符必须在其类型中指定。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailure1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断类型形参的数据类型。显式指定该数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailure2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailure3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicit1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments.</source> <target state="translated">无法从这些实参推断类型形参的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicit2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicit3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureAmbiguous1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为可能会存在多个类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureAmbiguous2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为可能会存在多个类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureAmbiguous3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断“{0}”中定义的扩展方法“{1}”中类型形参的数据类型,因为可能会存在多个类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为可能会存在多个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为可能会存在多个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible.</source> <target state="translated">无法从这些实参推断“{0}”中定义的扩展方法“{1}”中类型形参的数据类型,因为可能会存在多个类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoBest1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为这些数据类型不会转换为同一类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoBest2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoBest3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。显式指定数据类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest1"> <source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type.</source> <target state="translated">无法从这些实参推断类型形参的数据类型,因为这些数据类型不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest2"> <source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type.</source> <target state="translated">无法从这些实参推断方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest3"> <source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type.</source> <target state="translated">无法从这些实参推断“{1}”中定义的扩展方法“{0}”中类型形参的数据类型,因为这些数据类型不会转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingMismatchStrictOff2"> <source>Option Strict On does not allow narrowing in implicit type conversions between method '{0}' and delegate '{1}'.</source> <target state="translated">Option Strict On 不允许对方法“{0}”和委托“{1}”之间的隐式类型转换进行收缩。</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleReturnTypeOfMember2"> <source>'{0}' is not accessible in this context because the return type is not accessible.</source> <target state="translated">“{0}”是不可访问的返回类型,因此它在此上下文中不可访问。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedIdentifierOrGroup"> <source>'Group' or an identifier expected.</source> <target state="translated">'应为“Group”或标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedGroup"> <source>'Group' not allowed in this context; identifier expected.</source> <target state="translated">'此上下文中不允许 "Group";应为标识符。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingMismatchStrictOff3"> <source>Option Strict On does not allow narrowing in implicit type conversions between extension method '{0}' defined in '{2}' and delegate '{1}'.</source> <target state="translated">Option Strict On 不允许对“{2}”中定义的扩展方法“{0}”和委托“{1}”之间的隐式类型转换进行收缩。</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateBindingIncompatible3"> <source>Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'.</source> <target state="translated">“{2}”中定义的扩展方法“{0}”没有与委托“{1}”兼容的签名。</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentNarrowing2"> <source>Argument matching parameter '{0}' narrows to '{1}'.</source> <target state="translated">与形参“{0}”匹配的实参收缩到“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadCandidate1"> <source> {0}</source> <target state="translated"> {0}</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyInitializedInStructure"> <source>Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.</source> <target state="translated">如果没有将结构中包含的自动实现的属性标记为 "Shared",这些属性就不能有初始值设定项。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeDisallowsElements"> <source>XML elements cannot be selected from type '{0}'.</source> <target state="translated">XML 元素不能从类型“{0}”中选择。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeDisallowsAttributes"> <source>XML attributes cannot be selected from type '{0}'.</source> <target state="translated">XML 特性不能从类型“{0}”中选择。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeDisallowsDescendants"> <source>XML descendant elements cannot be selected from type '{0}'.</source> <target state="translated">XML 子代元素不能从类型“{0}”中选择。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeOrMemberNotGeneric2"> <source>Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments.</source> <target state="translated">“{1}”中定义的扩展方法“{0}”不是泛型方法(或没有可用的类型形参),因此无法拥有类型实参。</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodCannotBeLateBound"> <source>Late-bound extension methods are not supported.</source> <target state="translated">不支持后期绑定的扩展方法。</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceArrayRankMismatch1"> <source>Cannot infer a data type for '{0}' because the array dimensions do not match.</source> <target state="translated">无法推断“{0}”的数据类型,因为数组维数不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_QueryStrictDisallowImplicitObject"> <source>Type of the range variable cannot be inferred, and late binding is not allowed with Option Strict on. Use an 'As' clause to specify the type.</source> <target state="translated">无法推断范围变量的类型,且 Option Strict on 不允许后期绑定。请使用“As”子句来指定类型。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotEmbedInterfaceWithGeneric"> <source>Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.</source> <target state="translated">无法嵌入类型“{0}”,因为它有泛型参数。请考虑禁用互操作类型嵌入。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseGenericTypeAcrossAssemblyBoundaries"> <source>Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source> <target state="translated">无法跨程序集边界使用类型“{0}”,因为它有身为嵌入的互操作类型的泛型类型参数。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbol2"> <source>'{0}' is obsolete: '{1}'.</source> <target state="translated">“{0}”已过时:“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbol2_Title"> <source>Type or member is obsolete</source> <target state="translated">类型或成员已过时</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverloadBase4"> <source>{0} '{1}' shadows an overloadable member declared in the base {2} '{3}'. If you want to overload the base method, this method must be declared 'Overloads'.</source> <target state="translated">{0}“{1}”隐藏在基 {2}“{3}”中声明的可重载的成员。如果要重载基方法,则此方法必须声明为“Overloads”。</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverloadBase4_Title"> <source>Member shadows an overloadable member declared in the base type</source> <target state="translated">成员隐藏在基类型中声明的可重载的成员</target> <note /> </trans-unit> <trans-unit id="WRN_OverrideType5"> <source>{0} '{1}' conflicts with {2} '{1}' in the base {3} '{4}' and should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”与基 {3}“{4}”中的 {2}“{1}”冲突,应该声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_OverrideType5_Title"> <source>Member conflicts with member in the base type and should be declared 'Shadows'</source> <target state="translated">成员与基类型中的成员发生冲突,因此应声明为 "Shadows"</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverride2"> <source>{0} '{1}' shadows an overridable method in the base {2} '{3}'. To override the base method, this method must be declared 'Overrides'.</source> <target state="translated">{0}“{1}”隐藏基 {2}“{3}”中的可重写方法。若要重写基方法,必须将此方法声明为“Overrides”。</target> <note /> </trans-unit> <trans-unit id="WRN_MustOverride2_Title"> <source>Member shadows an overridable method in the base type</source> <target state="translated">成员隐藏基类型中的可重写的方法</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultnessShadowed4"> <source>Default property '{0}' conflicts with the default property '{1}' in the base {2} '{3}'. '{0}' will be the default property. '{0}' should be declared 'Shadows'.</source> <target state="translated">默认属性“{0}”与基 {2}“{3}”中的默认属性“{1}”冲突。“{0}”将成为默认属性。“{0}”应声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultnessShadowed4_Title"> <source>Default property conflicts with the default property in the base type</source> <target state="translated">默认属性与基类型中的默认属性发生冲突</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1"> <source>'{0}' is obsolete.</source> <target state="translated">“{0}”已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1_Title"> <source>Type or member is obsolete</source> <target state="translated">类型或成员已过时</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration0"> <source>Possible problem detected while building assembly: {0}</source> <target state="translated">生成程序集时检测到可能存在的问题: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration0_Title"> <source>Possible problem detected while building assembly</source> <target state="translated">生成程序集时检测到可能的问题</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration1"> <source>Possible problem detected while building assembly '{0}': {1}</source> <target state="translated">生成程序集“{0}”时检测到可能存在的问题: {1}</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyGeneration1_Title"> <source>Possible problem detected while building assembly</source> <target state="translated">生成程序集时检测到可能的问题</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassNoMembers1"> <source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class '{0}' but '{0}' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.</source> <target state="translated">'为类“{0}”指定了“Microsoft.VisualBasic.ComClassAttribute”,但“{0}”没有可以向 COM 公开的公共成员;因此不生成 COM 接口。</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassNoMembers1_Title"> <source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class but class has no public members that can be exposed to COM</source> <target state="translated">'为类指定了 "Microsoft.VisualBasic.ComClassAttribute",但类没有可向 COM 公开的公共成员</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsMember5"> <source>{0} '{1}' implicitly declares '{2}', which conflicts with a member in the base {3} '{4}', and so the {0} should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”隐式声明的“{2}”与基 {3}“{4}”中的成员冲突,因此应将 {0} 声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsMember5_Title"> <source>Property or event implicitly declares type or member that conflicts with a member in the base type</source> <target state="translated">属性或事件隐式声明与基类型中的成员发生冲突的类型或成员</target> <note /> </trans-unit> <trans-unit id="WRN_MemberShadowsSynthMember6"> <source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in the base {4} '{5}' and should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”与为基 {4}“{5}”中 {2}“{3}”隐式声明的成员冲突,应将它声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_MemberShadowsSynthMember6_Title"> <source>Member conflicts with a member implicitly declared for property or event in the base type</source> <target state="translated">成员与为基类型中的属性或事件隐式声明的成员冲突</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsSynthMember7"> <source>{0} '{1}' implicitly declares '{2}', which conflicts with a member implicitly declared for {3} '{4}' in the base {5} '{6}'. {0} should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”隐式声明的“{2}”与为基 {5}“{6}”中的 {3}“{4}”隐式声明的成员冲突。{0} 应声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_SynthMemberShadowsSynthMember7_Title"> <source>Property or event implicitly declares member, which conflicts with a member implicitly declared for property or event in the base type</source> <target state="translated">属性或事件隐式声明与为基类型中的属性或事件隐式声明的成员发生冲突的成员</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor3"> <source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source> <target state="translated">“{1}”的“{0}”访问器已过时:“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor3_Title"> <source>Property accessor is obsolete</source> <target state="translated">属性访问器已过时</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor2"> <source>'{0}' accessor of '{1}' is obsolete.</source> <target state="translated">“{1}”的“{0}”访问器已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_UseOfObsoletePropertyAccessor2_Title"> <source>Property accessor is obsolete</source> <target state="translated">属性访问器已过时</target> <note /> </trans-unit> <trans-unit id="WRN_FieldNotCLSCompliant1"> <source>Type of member '{0}' is not CLS-compliant.</source> <target state="translated">成员“{0}”的类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_FieldNotCLSCompliant1_Title"> <source>Type of member is not CLS-compliant</source> <target state="translated">成员的类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_BaseClassNotCLSCompliant2"> <source>'{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant.</source> <target state="translated">“{0}”不符合 CLS,因为它是从不符合 CLS 的“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_BaseClassNotCLSCompliant2_Title"> <source>Type is not CLS-compliant because it derives from base type that is not CLS-compliant</source> <target state="translated">类型不符合 CLS,原因是它从不符合 CLS 的基类型派生</target> <note /> </trans-unit> <trans-unit id="WRN_ProcTypeNotCLSCompliant1"> <source>Return type of function '{0}' is not CLS-compliant.</source> <target state="translated">函数“{0}”的返回类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_ProcTypeNotCLSCompliant1_Title"> <source>Return type of function is not CLS-compliant</source> <target state="translated">函数的返回类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_ParamNotCLSCompliant1"> <source>Type of parameter '{0}' is not CLS-compliant.</source> <target state="translated">参数“{0}”的类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_ParamNotCLSCompliant1_Title"> <source>Type of parameter is not CLS-compliant</source> <target state="translated">参数的类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2"> <source>'{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant.</source> <target state="translated">“{0}”不符合 CLS,因为它所继承的接口“{1}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2_Title"> <source>Type is not CLS-compliant because the interface it inherits from is not CLS-compliant</source> <target state="translated">类型不符合 CLS,原因是它继承自的接口不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_CLSMemberInNonCLSType3"> <source>{0} '{1}' cannot be marked CLS-compliant because its containing type '{2}' is not CLS-compliant.</source> <target state="translated">{0}“{1}”不能被标记为符合 CLS,因为它的包含类型“{2}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_CLSMemberInNonCLSType3_Title"> <source>Member cannot be marked CLS-compliant because its containing type is not CLS-compliant</source> <target state="translated">无法将成员标记为符合 CLS,原因是它的包含类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_NameNotCLSCompliant1"> <source>Name '{0}' is not CLS-compliant.</source> <target state="translated">名称“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_NameNotCLSCompliant1_Title"> <source>Name is not CLS-compliant</source> <target state="translated">名称不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_EnumUnderlyingTypeNotCLS1"> <source>Underlying type '{0}' of Enum is not CLS-compliant.</source> <target state="translated">枚举的基础类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_EnumUnderlyingTypeNotCLS1_Title"> <source>Underlying type of Enum is not CLS-compliant</source> <target state="translated">枚举的基础类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMemberInCLSInterface1"> <source>Non CLS-compliant '{0}' is not allowed in a CLS-compliant interface.</source> <target state="translated">在符合 CLS 的接口中不允许出现不符合 CLS 的“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMemberInCLSInterface1_Title"> <source>Non CLS-compliant member is not allowed in a CLS-compliant interface</source> <target state="translated">在符合 CLS 的接口中不允许出现不符合 CLS 的成员</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMustOverrideInCLSType1"> <source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type '{0}'.</source> <target state="translated">在符合 CLS 的类型“{0}”中不允许出现不符合 CLS 的 "MustOverride" 成员。</target> <note /> </trans-unit> <trans-unit id="WRN_NonCLSMustOverrideInCLSType1_Title"> <source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type</source> <target state="translated">在符合 CLS 的类型中不允许出现不符合 CLS 的 "Mustoverride" 成员</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayOverloadsNonCLS2"> <source>'{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types.</source> <target state="translated">“{0}”不符合 CLS,因为它重载仅在数组参数类型的数组或数组参数类型的秩方面与它不同的“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayOverloadsNonCLS2_Title"> <source>Method is not CLS-compliant because it overloads method which differs from it only by array of array parameter types or by the rank of the array parameter types</source> <target state="translated">方法不符合 CLS,因为它重载仅在数组参数类型的数组或数组参数类型的秩方面与它不同的方法</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant1"> <source>Root namespace '{0}' is not CLS-compliant.</source> <target state="translated">根命名空间“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant1_Title"> <source>Root namespace is not CLS-compliant</source> <target state="translated">根命名空间不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant2"> <source>Name '{0}' in the root namespace '{1}' is not CLS-compliant.</source> <target state="translated">根命名空间“{1}”中的名称“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_RootNamespaceNotCLSCompliant2_Title"> <source>Part of the root namespace is not CLS-compliant</source> <target state="translated">根命名空间的一部分不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_GenericConstraintNotCLSCompliant1"> <source>Generic parameter constraint type '{0}' is not CLS-compliant.</source> <target state="translated">泛型形参约束类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_GenericConstraintNotCLSCompliant1_Title"> <source>Generic parameter constraint type is not CLS-compliant</source> <target state="translated">泛型参数约束类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_TypeNotCLSCompliant1"> <source>Type '{0}' is not CLS-compliant.</source> <target state="translated">类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_TypeNotCLSCompliant1_Title"> <source>Type is not CLS-compliant</source> <target state="translated">类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_OptionalValueNotCLSCompliant1"> <source>Type of optional value for optional parameter '{0}' is not CLS-compliant.</source> <target state="translated">可选参数“{0}”的可选值的类型不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_OptionalValueNotCLSCompliant1_Title"> <source>Type of optional value for optional parameter is not CLS-compliant</source> <target state="translated">可选参数的可选值类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_CLSAttrInvalidOnGetSet"> <source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.</source> <target state="translated">System.CLSCompliantAttribute 不能应用于属性 "Get" 或 "Set"。</target> <note /> </trans-unit> <trans-unit id="WRN_CLSAttrInvalidOnGetSet_Title"> <source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'</source> <target state="translated">System.CLSCompliantAttribute 不能应用于属性 "Get" 或 "Set"</target> <note /> </trans-unit> <trans-unit id="WRN_TypeConflictButMerged6"> <source>{0} '{1}' and partial {2} '{3}' conflict in {4} '{5}', but are being merged because one of them is declared partial.</source> <target state="translated">{0}“{1}”和分部 {2}“{3}”在 {4}“{5}”中冲突,但由于其中的一个被声明为 Partial,因此正在合并。</target> <note /> </trans-unit> <trans-unit id="WRN_TypeConflictButMerged6_Title"> <source>Type and partial type conflict, but are being merged because one of them is declared partial</source> <target state="translated">类型和分部类型冲突,但由于其中一个被声明为 Partial,因此正在合并</target> <note /> </trans-unit> <trans-unit id="WRN_ShadowingGenericParamWithParam1"> <source>Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.</source> <target state="translated">类型参数“{0}”与封闭类型的类型参数同名。封闭类型的类型参数将被隐藏。</target> <note /> </trans-unit> <trans-unit id="WRN_ShadowingGenericParamWithParam1_Title"> <source>Type parameter has the same name as a type parameter of an enclosing type</source> <target state="translated">类型参数与封闭类型的类型参数具有相同的名称</target> <note /> </trans-unit> <trans-unit id="WRN_CannotFindStandardLibrary1"> <source>Could not find standard library '{0}'.</source> <target state="translated">未能找到标准库“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_CannotFindStandardLibrary1_Title"> <source>Could not find standard library</source> <target state="translated">找不到标准库</target> <note /> </trans-unit> <trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2"> <source>Delegate type '{0}' of event '{1}' is not CLS-compliant.</source> <target state="translated">事件“{1}”的委托类型“{0}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2_Title"> <source>Delegate type of event is not CLS-compliant</source> <target state="translated">事件的委托类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties"> <source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate.</source> <target state="translated">System.Diagnostics.DebuggerHiddenAttribute 在应用于属性定义时不影响“Get”或“Set”。请根据相应的情况,将此特性直接应用于“Get”和“Set”过程。</target> <note /> </trans-unit> <trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties_Title"> <source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition</source> <target state="translated">在应用到属性定义时,System.Diagnostics.DebuggerHiddenAttribute 不影响 "Get" 或 "Set"</target> <note /> </trans-unit> <trans-unit id="WRN_SelectCaseInvalidRange"> <source>Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound.</source> <target state="translated">为 "Case" 语句指定的范围无效。请确保下限小于或等于上限。</target> <note /> </trans-unit> <trans-unit id="WRN_SelectCaseInvalidRange_Title"> <source>Range specified for 'Case' statement is not valid</source> <target state="translated">为 "Case" 语句指定的范围无效</target> <note /> </trans-unit> <trans-unit id="WRN_CLSEventMethodInNonCLSType3"> <source>'{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant.</source> <target state="translated">'事件“{1}”的“{0}”方法不能被标记为符合 CLS,因为它的包含类型“{2}”不符合 CLS。</target> <note /> </trans-unit> <trans-unit id="WRN_CLSEventMethodInNonCLSType3_Title"> <source>AddHandler or RemoveHandler method for event cannot be marked CLS compliant because its containing type is not CLS compliant</source> <target state="translated">事件的 AddHandler 方法或 RemoveHandler 方法无法标记为符合 CLS,原因是它的包含类型不符合 CLS</target> <note /> </trans-unit> <trans-unit id="WRN_ExpectedInitComponentCall2"> <source>'{0}' in designer-generated type '{1}' should call InitializeComponent method.</source> <target state="translated">'设计器生成的类型“{1}”中的“{0}”应调用 InitializeComponent 方法。</target> <note /> </trans-unit> <trans-unit id="WRN_ExpectedInitComponentCall2_Title"> <source>Constructor in designer-generated type should call InitializeComponent method</source> <target state="translated">设计器生成的类型中的构造函数应调用 InitializeComponent 方法</target> <note /> </trans-unit> <trans-unit id="WRN_NamespaceCaseMismatch3"> <source>Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'.</source> <target state="translated">命名空间名“{0}”的大小写与“{2}”中命名空间名“{1}”的大小写不匹配。</target> <note /> </trans-unit> <trans-unit id="WRN_NamespaceCaseMismatch3_Title"> <source>Casing of namespace name does not match</source> <target state="translated">命名空间名称的大小写不匹配</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1"> <source>Namespace or type specified in the Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source> <target state="translated">Imports“{0}”中指定的命名空间或类型不包含任何公共成员,或者找不到该命名空间或类型。确保定义了该命名空间或类型且其中至少包含一个公共成员。确保导入的元素名不使用任何别名。</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1_Title"> <source>Namespace or type specified in Imports statement doesn't contain any public member or cannot be found</source> <target state="translated">在 Imports 语句中指定的命名空间或类型不包含任何公共成员或找不到公共成员</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1"> <source>Namespace or type specified in the project-level Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source> <target state="translated">项目级 Imports“{0}”中指定的命名空间或类型不包含任何公共成员,或者找不到公共成员。要确保定义了该命名空间或类型且其中至少包含一个公共成员;还要确保导入的元素名不使用任何别名。</target> <note /> </trans-unit> <trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1_Title"> <source>Namespace or type imported at project level doesn't contain any public member or cannot be found</source> <target state="translated">在项目级别导入的命名空间或类型不包含任何公共成员或找不到公共成员</target> <note /> </trans-unit> <trans-unit id="WRN_IndirectRefToLinkedAssembly2"> <source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly from assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source> <target state="translated">已创建对嵌入的互操作程序集“{0}”的引用,因为程序集“{1}”间接引用了该程序集。请考虑更改其中一个程序集的“嵌入互操作类型”属性。</target> <note /> </trans-unit> <trans-unit id="WRN_IndirectRefToLinkedAssembly2_Title"> <source>A reference was created to embedded interop assembly because of an indirect reference to that assembly</source> <target state="translated">已创建对嵌入的互操作程序集的引用,因为间接引用了该程序集</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase3"> <source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source> <target state="translated">类“{0}”应该声明一个“Sub New”,因为其基类“{2}”中的“{1}”被标记为已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase3_Title"> <source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source> <target state="translated">类应声明 "Sub New",原因是它的基类中的构造函数被标记为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase4"> <source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source> <target state="translated">类“{0}”应该声明一个“Sub New”,因为其基类“{2}”中的“{1}”被标记为已过时:“{3}”。</target> <note /> </trans-unit> <trans-unit id="WRN_NoNonObsoleteConstructorOnBase4_Title"> <source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source> <target state="translated">类应声明 "Sub New",原因是它的基类中的构造函数被标记为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall3"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source> <target state="translated">此“Sub New”中的第一条语句应为对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标记为已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall3_Title"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source> <target state="translated">此 "Sub New" 的第一条语句必须是对 "MyBase.New" 或 "MyClass.New" 的显式调用,原因是基类中的构造函数被标为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall4"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'</source> <target state="translated">此“Sub New”中的第一条语句应为对“MyBase.New”或“MyClass.New”的显式调用,因为“{2}”的基类“{1}”中的“{0}”被标记为已过时:“{3}”</target> <note /> </trans-unit> <trans-unit id="WRN_RequiredNonObsoleteNewCall4_Title"> <source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source> <target state="translated">此 "Sub New" 的第一条语句必须是对 "MyBase.New" 或 "MyClass.New" 的显式调用,原因是基类中的构造函数被标为已过时</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinOperator"> <source>Operator without an 'As' clause; type of Object assumed.</source> <target state="translated">运算符没有 "As" 子句;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinOperator_Title"> <source>Operator without an 'As' clause</source> <target state="translated">运算符没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_ConstraintsFailedForInferredArgs2"> <source>Type arguments inferred for method '{0}' result in the following warnings :{1}</source> <target state="translated">为方法“{0}”推断的类型参数导致以下警告:{1}</target> <note /> </trans-unit> <trans-unit id="WRN_ConstraintsFailedForInferredArgs2_Title"> <source>Type arguments inferred for method result in warnings</source> <target state="translated">为方法推断的类型参数导致警告</target> <note /> </trans-unit> <trans-unit id="WRN_ConditionalNotValidOnFunction"> <source>Attribute 'Conditional' is only valid on 'Sub' declarations.</source> <target state="translated">特性 "Conditional" 只在 "Sub" 声明中有效。</target> <note /> </trans-unit> <trans-unit id="WRN_ConditionalNotValidOnFunction_Title"> <source>Attribute 'Conditional' is only valid on 'Sub' declarations</source> <target state="translated">特性 "Conditional" 只在 "Sub" 声明中有效</target> <note /> </trans-unit> <trans-unit id="WRN_UseSwitchInsteadOfAttribute"> <source>Use command-line option '{0}' or appropriate project settings instead of '{1}'.</source> <target state="translated">请使用命令行选项“{0}”或适当的项目设置,而不是“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UseSwitchInsteadOfAttribute_Title"> <source>Use command-line option /keyfile, /keycontainer, or /delaysign instead of AssemblyKeyFileAttribute, AssemblyKeyNameAttribute, or AssemblyDelaySignAttribute</source> <target state="translated">使用命令行选项 /keyfile、/keycontainer 或 /delaysign,而不要使用 AssemblyKeyFileAttribute、AssemblyKeyNameAttribute 或 AssemblyDelaySignAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveAddHandlerCall"> <source>Statement recursively calls the containing '{0}' for event '{1}'.</source> <target state="translated">语句以递归方式调用事件“{1}”的包含“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveAddHandlerCall_Title"> <source>Statement recursively calls the event's containing AddHandler</source> <target state="translated">语句递归调用事件包含的 AddHandler</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionCopyBack"> <source>Implicit conversion from '{1}' to '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source> <target state="translated">将“ByRef”形参“{0}”的值复制回匹配实参时,发生从“{1}”到“{2}”的隐式转换。</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionCopyBack_Title"> <source>Implicit conversion in copying the value of 'ByRef' parameter back to the matching argument</source> <target state="translated">在把 "ByRef" 参数的值复制回匹配参数的过程中进行隐式转换</target> <note /> </trans-unit> <trans-unit id="WRN_MustShadowOnMultipleInheritance2"> <source>{0} '{1}' conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'.</source> <target state="translated">{0}“{1}”与继承层次结构中的其他同名成员冲突,因此应声明为“Shadows”。</target> <note /> </trans-unit> <trans-unit id="WRN_MustShadowOnMultipleInheritance2_Title"> <source>Method conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'</source> <target state="translated">方法与继承层次结构中的其他同名成员冲突,因此应声明为 "Shadows"</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveOperatorCall"> <source>Expression recursively calls the containing Operator '{0}'.</source> <target state="translated">表达式以递归方式调用包含运算符“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RecursiveOperatorCall_Title"> <source>Expression recursively calls the containing Operator</source> <target state="translated">表达式递归调用包含运算符</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversion2"> <source>Implicit conversion from '{0}' to '{1}'.</source> <target state="translated">从“{0}”到“{1}”的隐式转换。</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversion2_Title"> <source>Implicit conversion</source> <target state="translated">隐式转换</target> <note /> </trans-unit> <trans-unit id="WRN_MutableStructureInUsing"> <source>Local variable '{0}' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source> <target state="translated">局部变量“{0}”是只读的并且其类型是结构。调用此变量的成员或通过 ByRef 传递它不会更改其内容,并可能导致意外的错误。考虑在“Using”块之外声明此变量。</target> <note /> </trans-unit> <trans-unit id="WRN_MutableStructureInUsing_Title"> <source>Local variable declared by Using statement is read-only and its type is a structure</source> <target state="translated">Using 语句声明的局部变量是只读的,它的类型是一种结构</target> <note /> </trans-unit> <trans-unit id="WRN_MutableGenericStructureInUsing"> <source>Local variable '{0}' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source> <target state="translated">局部变量“{0}”是只读的。其类型为结构时,调用其成员或使用 ByRef 传递该类型不会更改其内容,并可能会导致意外的结果。考虑在“Using”块之外声明此变量。</target> <note /> </trans-unit> <trans-unit id="WRN_MutableGenericStructureInUsing_Title"> <source>Local variable declared by Using statement is read-only and its type may be a structure</source> <target state="translated">Using 语句声明的局部变量是只读的,它的类型可能是一种结构</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionSubst1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitConversionSubst1_Title"> <source>Implicit conversion</source> <target state="translated">隐式转换</target> <note /> </trans-unit> <trans-unit id="WRN_LateBindingResolution"> <source>Late bound resolution; runtime errors could occur.</source> <target state="translated">后期绑定解决方案;可能会发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_LateBindingResolution_Title"> <source>Late bound resolution</source> <target state="translated">后期绑定解决方案</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1"> <source>Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity.</source> <target state="translated">对运算符“{0}”使用了 Object 类型的操作数;应使用“Is”运算符来测试对象标识。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1_Title"> <source>Operands of type Object used for operator</source> <target state="translated">为运算符使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath2"> <source>Operands of type Object used for operator '{0}'; runtime errors could occur.</source> <target state="translated">对运算符“{0}”使用了 Object 类型的操作数;可能会发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath2_Title"> <source>Operands of type Object used for operator</source> <target state="translated">为运算符使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedVar1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedVar1_Title"> <source>Variable declaration without an 'As' clause</source> <target state="translated">变量声明没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumed1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumed1_Title"> <source>Function without an 'As' clause</source> <target state="translated">函数没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedProperty1"> <source>{0}</source> <target state="translated">{0}</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectAssumedProperty1_Title"> <source>Property without an 'As' clause</source> <target state="translated">属性没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinVarDecl"> <source>Variable declaration without an 'As' clause; type of Object assumed.</source> <target state="translated">变量声明没有 "As" 子句;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinVarDecl_Title"> <source>Variable declaration without an 'As' clause</source> <target state="translated">变量声明没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinFunction"> <source>Function without an 'As' clause; return type of Object assumed.</source> <target state="translated">函数没有 "As" 子句;假定返回类型为 Object。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinFunction_Title"> <source>Function without an 'As' clause</source> <target state="translated">函数没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinProperty"> <source>Property without an 'As' clause; type of Object assumed.</source> <target state="translated">属性没有 "As" 子句;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_MissingAsClauseinProperty_Title"> <source>Property without an 'As' clause</source> <target state="translated">属性没有 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocal"> <source>Unused local variable: '{0}'.</source> <target state="translated">未使用的局部变量:“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocal_Title"> <source>Unused local variable</source> <target state="translated">未使用的本地变量</target> <note /> </trans-unit> <trans-unit id="WRN_SharedMemberThroughInstance"> <source>Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.</source> <target state="translated">通过实例访问共享成员、常量成员、枚举成员或嵌套类型;将不计算限定表达式。</target> <note /> </trans-unit> <trans-unit id="WRN_SharedMemberThroughInstance_Title"> <source>Access of shared member, constant member, enum member or nested type through an instance</source> <target state="translated">通过实例访问共享成员、常量成员、枚举成员或嵌套类型</target> <note /> </trans-unit> <trans-unit id="WRN_RecursivePropertyCall"> <source>Expression recursively calls the containing property '{0}'.</source> <target state="translated">表达式递归调用包含属性“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RecursivePropertyCall_Title"> <source>Expression recursively calls the containing property</source> <target state="translated">表达式递归调用包含属性</target> <note /> </trans-unit> <trans-unit id="WRN_OverlappingCatch"> <source>'Catch' block never reached, because '{0}' inherits from '{1}'.</source> <target state="translated">'永远不会到达“Catch”块,因为“{0}”从“{1}”继承。</target> <note /> </trans-unit> <trans-unit id="WRN_OverlappingCatch_Title"> <source>'Catch' block never reached; exception type's base type handled above in the same Try statement</source> <target state="translated">'永远不会到达 "Catch" 块;异常类型的基类型已在上面同一个 Try 语句中处理</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRef"> <source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime.</source> <target state="translated">变量“{0}”在赋值前通过引用传递。可能会在运行时导致 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRef_Title"> <source>Variable is passed by reference before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已通过引用传递</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateCatch"> <source>'Catch' block never reached; '{0}' handled above in the same Try statement.</source> <target state="translated">'永远不会到达“Catch”块;“{0}”已在上面同一个 Try 语句中处理。</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateCatch_Title"> <source>'Catch' block never reached; exception type handled above in the same Try statement</source> <target state="translated">'永远不会到达 "Catch" 块;异常类型已在上面同一个 Try 语句中处理</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1Not"> <source>Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity.</source> <target state="translated">对运算符“{0}”使用了 Object 类型的操作数;应使用“IsNot”运算符来测试对象标识。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMath1Not_Title"> <source>Operands of type Object used for operator &lt;&gt;</source> <target state="translated">为运算符 &lt;&gt; 使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_BadChecksumValExtChecksum"> <source>Bad checksum value, non hex digits or odd number of hex digits.</source> <target state="translated">错误的校验和值、非十六进制数字或奇数个十六进制数字。</target> <note /> </trans-unit> <trans-unit id="WRN_BadChecksumValExtChecksum_Title"> <source>Bad checksum value, non hex digits or odd number of hex digits</source> <target state="translated">错误的校验和值、非十六进制数字或奇数个十六进制数字</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleDeclFileExtChecksum"> <source>File name already declared with a different GUID and checksum value.</source> <target state="translated">已使用另一个 GUID 和校验和值声明了文件名。</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleDeclFileExtChecksum_Title"> <source>File name already declared with a different GUID and checksum value</source> <target state="translated">已使用另一个 GUID 和校验和值声明了文件名</target> <note /> </trans-unit> <trans-unit id="WRN_BadGUIDFormatExtChecksum"> <source>Bad GUID format.</source> <target state="translated">错误的 GUID 格式。</target> <note /> </trans-unit> <trans-unit id="WRN_BadGUIDFormatExtChecksum_Title"> <source>Bad GUID format</source> <target state="translated">错误的 GUID 格式</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMathSelectCase"> <source>Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur.</source> <target state="translated">在 "Select"、"Case" 语句的表达式中使用了 Object 类型的操作数;可能会发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_ObjectMathSelectCase_Title"> <source>Operands of type Object used in expressions for 'Select', 'Case' statements</source> <target state="translated">"Select"、"Case" 语句的表达式中使用的 Object 类型的操作数</target> <note /> </trans-unit> <trans-unit id="WRN_EqualToLiteralNothing"> <source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.</source> <target state="translated">此表达式的计算结果始终为 Nothing (由于来自等于运算符的 null 传播)。若要检查值是否为 null,请考虑使用 "Is Nothing"。</target> <note /> </trans-unit> <trans-unit id="WRN_EqualToLiteralNothing_Title"> <source>This expression will always evaluate to Nothing</source> <target state="translated">此表达式的计算结果始终为 Nothing</target> <note /> </trans-unit> <trans-unit id="WRN_NotEqualToLiteralNothing"> <source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'.</source> <target state="translated">此表达式的计算结果始终为 Nothing (由于来自等于运算符的 null 传播)。若要检查值是否不为 null,请考虑使用 "IsNot Nothing"。</target> <note /> </trans-unit> <trans-unit id="WRN_NotEqualToLiteralNothing_Title"> <source>This expression will always evaluate to Nothing</source> <target state="translated">此表达式的计算结果始终为 Nothing</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocalConst"> <source>Unused local constant: '{0}'.</source> <target state="translated">未使用的局部常量:“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_UnusedLocalConst_Title"> <source>Unused local constant</source> <target state="translated">未使用的局部常量</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassInterfaceShadows5"> <source>'Microsoft.VisualBasic.ComClassAttribute' on class '{0}' implicitly declares {1} '{2}', which conflicts with a member of the same name in {3} '{4}'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base {4}.</source> <target state="translated">'类“{0}”上的“Microsoft.VisualBasic.ComClassAttribute”隐式声明的 {1}“{2}”与 {3}“{4}”中的同名成员冲突。如果要隐藏基 {4} 上的名称,请使用“Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)”。</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassInterfaceShadows5_Title"> <source>'Microsoft.VisualBasic.ComClassAttribute' on class implicitly declares member, which conflicts with a member of the same name</source> <target state="translated">'类上的 "Microsoft.VisualBasic.ComClassAttribute" 隐式声明与同名成员发生冲突的成员</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassPropertySetObject1"> <source>'{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.</source> <target state="translated">“{0}”无法作为属性“Let”向 COM 公开。将无法使用“Let”语句从 Visual Basic 6.0 向该属性分配非对象值(如数字或字符串)。</target> <note /> </trans-unit> <trans-unit id="WRN_ComClassPropertySetObject1_Title"> <source>Property cannot be exposed to COM as a property 'Let'</source> <target state="translated">无法将属性作为 "Let" 属性向 COM 公开</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRef"> <source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime.</source> <target state="translated">变量“{0}”在赋值前被使用。可能会在运行时导致 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRef_Title"> <source>Variable is used before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已被使用</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncRef1"> <source>Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source> <target state="translated">函数“{0}”不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncRef1_Title"> <source>Function doesn't return a value on all code paths</source> <target state="translated">函数没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpRef1"> <source>Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source> <target state="translated">运算符“{0}”不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpRef1_Title"> <source>Operator doesn't return a value on all code paths</source> <target state="translated">运算符没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropRef1"> <source>Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source> <target state="translated">属性“{0}”不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropRef1_Title"> <source>Property doesn't return a value on all code paths</source> <target state="translated">属性没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRefStr"> <source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source> <target state="translated">变量“{0}”在赋值前通过引用传递。可能会在运行时导致 null 引用异常。请确保结构或所有引用成员在使用前已经初始化</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefByRefStr_Title"> <source>Variable is passed by reference before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已通过引用传递</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefStr"> <source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source> <target state="translated">变量“{0}”在赋值前被使用。可能会在运行时导致 null 引用异常。请确保结构或所有引用成员在使用前已经初始化</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgUseNullRefStr_Title"> <source>Variable is used before it has been assigned a value</source> <target state="translated">在为变量赋值之前,变量已被使用</target> <note /> </trans-unit> <trans-unit id="WRN_StaticLocalNoInference"> <source>Static variable declared without an 'As' clause; type of Object assumed.</source> <target state="translated">未使用 "As" 子句声明的静态变量;假定为 Object 类型。</target> <note /> </trans-unit> <trans-unit id="WRN_StaticLocalNoInference_Title"> <source>Static variable declared without an 'As' clause</source> <target state="translated">声明静态变量时未使用 "As" 子句</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName"> <source>Assembly reference '{0}' is invalid and cannot be resolved.</source> <target state="translated">程序集引用“{0}”无效,无法解析。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName_Title"> <source>Assembly reference is invalid and cannot be resolved</source> <target state="translated">程序集引用无效,无法解析</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadXMLLine"> <source>XML comment block must immediately precede the language element to which it applies. XML comment will be ignored.</source> <target state="translated">XML 注释块必须紧挨着它应用于的语言元素的前面。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadXMLLine_Title"> <source>XML comment block must immediately precede the language element to which it applies</source> <target state="translated">XML 注释块必须紧跟它所应用于的语言元素</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocMoreThanOneCommentBlock"> <source>Only one XML comment block is allowed per language element.</source> <target state="translated">每个语言元素只能有一个 XML 注释块。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocMoreThanOneCommentBlock_Title"> <source>Only one XML comment block is allowed per language element</source> <target state="translated">每个语言元素只能有一个 XML 注释块</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocNotFirstOnLine"> <source>XML comment must be the first statement on a line. XML comment will be ignored.</source> <target state="translated">XML 注释必须是一行中的第一条语句。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocNotFirstOnLine_Title"> <source>XML comment must be the first statement on a line</source> <target state="translated">XML 注释必须是一行上的第一条语句</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInsideMethod"> <source>XML comment cannot appear within a method or a property. XML comment will be ignored.</source> <target state="translated">XML 注释不能在方法或属性内出现。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInsideMethod_Title"> <source>XML comment cannot appear within a method or a property</source> <target state="translated">XML 注释不能在方法或属性内出现</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParseError1"> <source>XML documentation parse error: {0} XML comment will be ignored.</source> <target state="translated">XML 文档分析错误: {0} XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParseError1_Title"> <source>XML documentation parse error</source> <target state="translated">XML 文档分析错误</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocDuplicateXMLNode1"> <source>XML comment tag '{0}' appears with identical attributes more than once in the same XML comment block.</source> <target state="translated">具有相同特性的 XML 注释标记“{0}”在同一 XML 注释块中出现多次。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocDuplicateXMLNode1_Title"> <source>XML comment tag appears with identical attributes more than once in the same XML comment block</source> <target state="translated">具有相同属性的 XML 注释标记在同一个 XML 注释块中出现多次</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocIllegalTagOnElement2"> <source>XML comment tag '{0}' is not permitted on a '{1}' language element.</source> <target state="translated">“{1}”语言元素中不允许 XML 注释标记“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocIllegalTagOnElement2_Title"> <source>XML comment tag is not permitted on language element</source> <target state="translated">语言元素中不允许出现 XML 注释标记</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadParamTag2"> <source>XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement.</source> <target state="translated">XML 注释参数“{0}”和相应的“{1}”语句的参数不匹配。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadParamTag2_Title"> <source>XML comment parameter does not match a parameter on the corresponding declaration statement</source> <target state="translated">XML 注释参数与相应的声明语句上的参数不匹配</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParamTagWithoutName"> <source>XML comment parameter must have a 'name' attribute.</source> <target state="translated">XML 注释参数必须具有 "name" 属性。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocParamTagWithoutName_Title"> <source>XML comment parameter must have a 'name' attribute</source> <target state="translated">XML 注释参数必须具有 "name" 属性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefAttributeNotFound1"> <source>XML comment has a tag with a 'cref' attribute '{0}' that could not be resolved.</source> <target state="translated">XML 注释中的一个标记具有未能解析的“cref”特性“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefAttributeNotFound1_Title"> <source>XML comment has a tag with a 'cref' attribute that could not be resolved</source> <target state="translated">XML 注释包含具有无法解析的 "cref" 属性的标记</target> <note /> </trans-unit> <trans-unit id="WRN_XMLMissingFileOrPathAttribute1"> <source>XML comment tag 'include' must have a '{0}' attribute. XML comment will be ignored.</source> <target state="translated">XML 注释标记“include”必须具有“{0}”特性。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLMissingFileOrPathAttribute1_Title"> <source>XML comment tag 'include' must have 'file' and 'path' attributes</source> <target state="translated">XML 注释标记 "include" 必须具有 "file" 和 "path" 特性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLCannotWriteToXMLDocFile2"> <source>Unable to create XML documentation file '{0}': {1}</source> <target state="translated">无法创建 XML 文档文件“{0}”: {1}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLCannotWriteToXMLDocFile2_Title"> <source>Unable to create XML documentation file</source> <target state="translated">无法创建 XML 文档文件</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocWithoutLanguageElement"> <source>XML documentation comments must precede member or type declarations.</source> <target state="translated">XML 文档注释必须位于成员声明或类型声明之前。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocWithoutLanguageElement_Title"> <source>XML documentation comments must precede member or type declarations</source> <target state="translated">XML 文档注释必须位于成员声明或类型声明之前</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty"> <source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.</source> <target state="translated">WriteOnly 属性中不允许有 XML 注释标记 "returns"。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty_Title"> <source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property</source> <target state="translated">"WriteOnly" 属性中不允许出现 XML 注释标记 "returns"</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocOnAPartialType"> <source>XML comment cannot be applied more than once on a partial {0}. XML comments for this {0} will be ignored.</source> <target state="translated">XML 注释在分部 {0} 中不能应用多次。此 {0} 的 XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocOnAPartialType_Title"> <source>XML comment cannot be applied more than once on a partial type</source> <target state="translated">XML 注释无法在一个分部类型上应用多次</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnADeclareSub"> <source>XML comment tag 'returns' is not permitted on a 'declare sub' language element.</source> <target state="translated">declare sub 语言元素中不允许有 XML 注释标记 "returns"。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocReturnsOnADeclareSub_Title"> <source>XML comment tag 'returns' is not permitted on a 'declare sub' language element</source> <target state="translated">"declare sub" 语言元素中不允许出现 XML 注释标记 "returns"</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocStartTagWithNoEndTag"> <source>XML documentation parse error: Start tag '{0}' doesn't have a matching end tag. XML comment will be ignored.</source> <target state="translated">XML 文档分析错误: 开始标记“{0}”没有匹配的结束标记。XML 注释将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocStartTagWithNoEndTag_Title"> <source>XML documentation parse error: Start tag doesn't have a matching end tag</source> <target state="translated">XML 文档分析错误: 开始标记没有匹配的结束标记</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadGenericParamTag2"> <source>XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement.</source> <target state="translated">XML 注释类型参数“{0}”和相应的“{1}”语句的类型参数不匹配。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadGenericParamTag2_Title"> <source>XML comment type parameter does not match a type parameter on the corresponding declaration statement</source> <target state="translated">XML 注释类型参数与相应的声明语句上的类型参数不匹配</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocGenericParamTagWithoutName"> <source>XML comment type parameter must have a 'name' attribute.</source> <target state="translated">XML 注释类型参数必须具有 "name" 属性。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocGenericParamTagWithoutName_Title"> <source>XML comment type parameter must have a 'name' attribute</source> <target state="translated">XML 注释类型参数必须具有 "name" 属性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocExceptionTagWithoutCRef"> <source>XML comment exception must have a 'cref' attribute.</source> <target state="translated">XML 注释异常必须具有 "cref" 属性。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocExceptionTagWithoutCRef_Title"> <source>XML comment exception must have a 'cref' attribute</source> <target state="translated">XML 注释异常必须具有 "cref" 属性</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInvalidXMLFragment"> <source>Unable to include XML fragment '{0}' of file '{1}'.</source> <target state="translated">无法包括文件“{1}”的 XML 段落“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocInvalidXMLFragment_Title"> <source>Unable to include XML fragment</source> <target state="translated">无法包括 XML 段落</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadFormedXML"> <source>Unable to include XML fragment '{1}' of file '{0}'. {2}</source> <target state="translated">无法包括文件“{0}”的 XML 段落“{1}”。{2}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocBadFormedXML_Title"> <source>Unable to include XML fragment</source> <target state="translated">无法包括 XML 段落</target> <note /> </trans-unit> <trans-unit id="WRN_InterfaceConversion2"> <source>Runtime errors might occur when converting '{0}' to '{1}'.</source> <target state="translated">将“{0}”转换为“{1}”时可能发生运行时错误。</target> <note /> </trans-unit> <trans-unit id="WRN_InterfaceConversion2_Title"> <source>Runtime errors might occur when converting to or from interface type</source> <target state="translated">运行时错误可能在转换到或从接口类型转换时发生</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableLambda"> <source>Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source> <target state="translated">在 lambda 表达式中使用迭代变量可能会产生意外的结果。应改为在循环中创建一个局部变量并将迭代变量的值赋给它。</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableLambda_Title"> <source>Using the iteration variable in a lambda expression may have unexpected results</source> <target state="translated">在 lambda 表达式中使用迭代变量可能会产生意外的结果</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaPassedToRemoveHandler"> <source>Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.</source> <target state="translated">Lambda 表达式将不会从此事件处理程序中移除。将 lambda 表达式赋给变量,并使用该变量添加和移除事件。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaPassedToRemoveHandler_Title"> <source>Lambda expression will not be removed from this event handler</source> <target state="translated">Lambda 表达式将不会从此事件处理程序中删除</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableQuery"> <source>Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source> <target state="translated">在查询表达式中使用迭代变量可能会产生意外的结果。应改为在循环中创建一个局部变量并将迭代变量的值赋给它。</target> <note /> </trans-unit> <trans-unit id="WRN_LiftControlVariableQuery_Title"> <source>Using the iteration variable in a query expression may have unexpected results</source> <target state="translated">在查询表达式中使用迭代变量可能会产生意外的结果</target> <note /> </trans-unit> <trans-unit id="WRN_RelDelegatePassedToRemoveHandler"> <source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler.</source> <target state="translated">"AddressOf" 表达式在此上下文中不起作用,因为 "AddressOf" 的方法参数需要到该事件的委托类型的宽松转换。将 "AddressOf' 表达式赋给变量,并使用变量将该方法作为处理程序进行添加或移除。</target> <note /> </trans-unit> <trans-unit id="WRN_RelDelegatePassedToRemoveHandler_Title"> <source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event</source> <target state="translated">"AddressOf" 表达式在此上下文中不起作用,原因是 "AddressOf" 的方法参数需要到该事件的委托类型的宽松转换</target> <note /> </trans-unit> <trans-unit id="WRN_QueryMissingAsClauseinVarDecl"> <source>Range variable is assumed to be of type Object because its type cannot be inferred. Use an 'As' clause to specify a different type.</source> <target state="translated">假定范围变量属于对象类型,因为无法推断其类型。请使用“As”子句指定不同类型。</target> <note /> </trans-unit> <trans-unit id="WRN_QueryMissingAsClauseinVarDecl_Title"> <source>Range variable is assumed to be of type Object because its type cannot be inferred</source> <target state="translated">范围变量被假设为 Object 类型,原因是无法推断它的类型</target> <note /> </trans-unit> <trans-unit id="ERR_MultilineLambdaMissingFunction"> <source>Multiline lambda expression is missing 'End Function'.</source> <target state="translated">多行 lambda 表达式缺少 "End Function"。</target> <note /> </trans-unit> <trans-unit id="ERR_MultilineLambdaMissingSub"> <source>Multiline lambda expression is missing 'End Sub'.</source> <target state="translated">多行 lambda 表达式缺少 "End Sub"。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeOnLambdaReturnType"> <source>Attributes cannot be applied to return types of lambda expressions.</source> <target state="translated">特性不能应用于 lambda 表达式的返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_SubDisallowsStatement"> <source>Statement is not valid inside a single-line statement lambda.</source> <target state="translated">该语句在单行语句 lambda 中无效。</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresParenthesesBang"> <source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() &lt;statement&gt;)!key</source> <target state="translated">此单行语句 lambda 必须括在括号中。例如: (Sub() &lt;语句&gt;)!key</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresParenthesesDot"> <source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() &lt;statement&gt;).Invoke()</source> <target state="translated">此单行语句 lambda 必须括在括号中。例如: (Sub() &lt;语句&gt;).Invoke()</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresParenthesesLParen"> <source>This single-line statement lambda must be enclosed in parentheses. For example: Call (Sub() &lt;statement&gt;) ()</source> <target state="translated">此单行语句 lambda 必须括在括号中。例如: Call (Sub() &lt;语句&gt;) ()</target> <note /> </trans-unit> <trans-unit id="ERR_SubRequiresSingleStatement"> <source>Single-line statement lambdas must include exactly one statement.</source> <target state="translated">单行语句 lambda 必须仅包含一个语句。</target> <note /> </trans-unit> <trans-unit id="ERR_StaticInLambda"> <source>Static local variables cannot be declared inside lambda expressions.</source> <target state="translated">无法在 lambda 表达式内声明静态局部变量。</target> <note /> </trans-unit> <trans-unit id="ERR_InitializedExpandedProperty"> <source>Expanded Properties cannot be initialized.</source> <target state="translated">无法初始化扩展属性。</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyCantHaveParams"> <source>Auto-implemented properties cannot have parameters.</source> <target state="translated">自动实现的属性不能带有参数。</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyCantBeWriteOnly"> <source>Auto-implemented properties cannot be WriteOnly.</source> <target state="translated">自动实现的属性不能为 WriteOnly。</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalOperandInIIFCount"> <source>'If' operator requires either two or three operands.</source> <target state="translated">'“If”运算符需要两个或三个操作数。</target> <note /> </trans-unit> <trans-unit id="ERR_NotACollection1"> <source>Cannot initialize the type '{0}' with a collection initializer because it is not a collection type.</source> <target state="translated">无法用集合初始值设定项初始化类型“{0}”,因为该类型不是集合类型。</target> <note /> </trans-unit> <trans-unit id="ERR_NoAddMethod1"> <source>Cannot initialize the type '{0}' with a collection initializer because it does not have an accessible 'Add' method.</source> <target state="translated">无法用集合初始值设定项初始化类型“{0}”,因为该类型没有可访问的“Add”方法。</target> <note /> </trans-unit> <trans-unit id="ERR_CantCombineInitializers"> <source>An Object Initializer and a Collection Initializer cannot be combined in the same initialization.</source> <target state="translated">不能将对象初始值设定项与集合初始值设定项组合到同一个初始化过程中。</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyAggregateInitializer"> <source>An aggregate collection initializer entry must contain at least one element.</source> <target state="translated">聚合集合初始值设定项必须至少包含一个元素。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlEndElementNoMatchingStart"> <source>XML end element must be preceded by a matching start element.</source> <target state="translated">XML 结束元素前面必须是匹配的开始元素。</target> <note /> </trans-unit> <trans-unit id="ERR_MultilineLambdasCannotContainOnError"> <source>'On Error' and 'Resume' cannot appear inside a lambda expression.</source> <target state="translated">'“On Error”和“Resume”不能出现在 lambda 表达式内。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceDisallowedHere"> <source>Keywords 'Out' and 'In' can only be used in interface and delegate declarations.</source> <target state="translated">关键字 "Out" 和 "In" 只能在接口声明和委托声明中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_XmlEndCDataNotAllowedInContent"> <source>The literal string ']]&gt;' is not allowed in element content.</source> <target state="translated">元素内容中不允许使用字符串“]]&gt;”。</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadsModifierInModule"> <source>Inappropriate use of '{0}' keyword in a module.</source> <target state="translated">模块中不恰当地使用了“{0}”关键字。</target> <note /> </trans-unit> <trans-unit id="ERR_UndefinedTypeOrNamespace1"> <source>Type or namespace '{0}' is not defined.</source> <target state="translated">未定义类型或命名空间“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_IdentityDirectCastForFloat"> <source>Using DirectCast operator to cast a floating-point value to the same type is not supported.</source> <target state="translated">不支持使用 DirectCast 运算符将浮点值强制转换为同一类型。</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType"> <source>Using DirectCast operator to cast a value-type to the same type is obsolete.</source> <target state="translated">使用 DirectCast 运算符将值类型强制转换为同一类型的做法已过时。</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType_Title"> <source>Using DirectCast operator to cast a value-type to the same type is obsolete</source> <target state="translated">使用 DirectCast 运算符将值类型强制转换为同一类型的做法已过时</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode"> <source>Unreachable code detected.</source> <target state="translated">检测到无法访问的代码。</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode_Title"> <source>Unreachable code detected</source> <target state="translated">检测到无法访问的代码</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncVal1"> <source>Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">函数“{0}”不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValFuncVal1_Title"> <source>Function doesn't return a value on all code paths</source> <target state="translated">函数没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpVal1"> <source>Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">运算符“{0}”不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValOpVal1_Title"> <source>Operator doesn't return a value on all code paths</source> <target state="translated">运算符没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropVal1"> <source>Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">属性“{0}”不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValPropVal1_Title"> <source>Property doesn't return a value on all code paths</source> <target state="translated">属性没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="ERR_NestedGlobalNamespace"> <source>Global namespace may not be nested in another namespace.</source> <target state="translated">全局命名空间不能嵌套在另一个命名空间中。</target> <note /> </trans-unit> <trans-unit id="ERR_AccessMismatch6"> <source>'{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'.</source> <target state="translated">“{0}”不能通过 {4}“{5}”在 {2}“{3}”中公开类型“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadMetaDataReference1"> <source>'{0}' cannot be referenced because it is not a valid assembly.</source> <target state="translated">“{0}”不是有效程序集,因此无法引用它。</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyDoesntImplementAllAccessors"> <source>'{0}' cannot be implemented by a {1} property.</source> <target state="translated">“{0}”无法由 {1} 属性实现。</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedMustOverride"> <source> {0}: {1}</source> <target state="translated"> {0}: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_IfTooManyTypesObjectDisallowed"> <source>Cannot infer a common type because more than one type is possible.</source> <target state="translated">无法推断通用类型,因为可能存在多个类型。</target> <note /> </trans-unit> <trans-unit id="WRN_IfTooManyTypesObjectAssumed"> <source>Cannot infer a common type because more than one type is possible; 'Object' assumed.</source> <target state="translated">无法推断通用类型,因为可能存在多个类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_IfTooManyTypesObjectAssumed_Title"> <source>Cannot infer a common type because more than one type is possible</source> <target state="translated">无法推断通用类型,原因是可能存在多个类型</target> <note /> </trans-unit> <trans-unit id="ERR_IfNoTypeObjectDisallowed"> <source>Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.</source> <target state="translated">无法推断通用类型,且 Option Strict On 不允许假定“Object”。</target> <note /> </trans-unit> <trans-unit id="WRN_IfNoTypeObjectAssumed"> <source>Cannot infer a common type; 'Object' assumed.</source> <target state="translated">无法推断通用类型;假定为“Object”。</target> <note /> </trans-unit> <trans-unit id="WRN_IfNoTypeObjectAssumed_Title"> <source>Cannot infer a common type</source> <target state="translated">无法推断通用类型</target> <note /> </trans-unit> <trans-unit id="ERR_IfNoType"> <source>Cannot infer a common type.</source> <target state="translated">无法推断通用类型。</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyFileFailure"> <source>Error extracting public key from file '{0}': {1}</source> <target state="translated">从文件“{0}”中提取公钥时出错: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyContainerFailure"> <source>Error extracting public key from container '{0}': {1}</source> <target state="translated">从容器“{0}”中提取公钥时出错: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefNotEqualToThis"> <source>Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</source> <target state="translated">友元访问权限由“{0}”授予,但是输出程序集的公钥与授予程序集中特性指定的公钥不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefSigningMismatch"> <source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source> <target state="translated">友元访问权限由“{0}”授予,但是输出程序集的强名称签名状态与授予程序集的强名称签名状态不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignNoKey"> <source>Public sign was specified and requires a public key, but no public key was specified</source> <target state="translated">已指定公共符号并且它需要一个公钥,但未指定任何公钥</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignNetModule"> <source>Public signing is not supported for netmodules.</source> <target state="translated">netmodule 不支持公共签名。</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning"> <source>Attribute '{0}' is ignored when public signing is specified.</source> <target state="translated">指定公共签名时,将忽略特性“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title"> <source>Attribute is ignored when public signing is specified.</source> <target state="translated">指定公共签名时,将忽略特性。</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey"> <source>Delay signing was specified and requires a public key, but no public key was specified.</source> <target state="translated">指定了延迟签名,这需要公钥,但是未指定任何公钥。</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey_Title"> <source>Delay signing was specified and requires a public key, but no public key was specified</source> <target state="translated">指定了延迟签名,这需要公钥,但是未指定任何公钥</target> <note /> </trans-unit> <trans-unit id="ERR_SignButNoPrivateKey"> <source>Key file '{0}' is missing the private key needed for signing.</source> <target state="translated">密钥文件“{0}”缺少进行签名所需的私钥。</target> <note /> </trans-unit> <trans-unit id="ERR_FailureSigningAssembly"> <source>Error signing assembly '{0}': {1}</source> <target state="translated">对程序集“{0}”签名时出错: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat"> <source>The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]]</source> <target state="translated">指定的版本字符串不符合所需格式 - major[.minor[.build|*[.revision|*]]]</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">指定版本字符串不符合建议格式 - major.minor.build.revision</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat_Title"> <source>The specified version string does not conform to the recommended format</source> <target state="translated">指定的版本字符串不符合建议的格式</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat2"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">指定版本字符串不符合建议格式 - major.minor.build.revision</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCultureForExe"> <source>Executables cannot be satellite assemblies; culture should always be empty</source> <target state="translated">可执行文件不能是附属程序集;区域性应始终为空</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored"> <source>The entry point of the program is global script code; ignoring '{0}' entry point.</source> <target state="translated">程序的入口点是全局脚本代码;正在忽略“{0}”入口点。</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored_Title"> <source>The entry point of the program is global script code; ignoring entry point</source> <target state="translated">程序的入口点是全局脚本代码;正在忽略入口点</target> <note /> </trans-unit> <trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName"> <source>The xmlns attribute has special meaning and should not be written with a prefix.</source> <target state="translated">xmlns 特性具有特殊含义,不应使用前缀进行编写。</target> <note /> </trans-unit> <trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName_Title"> <source>The xmlns attribute has special meaning and should not be written with a prefix</source> <target state="translated">xmlns 特性具有特殊含义,不应使用前缀进行编写</target> <note /> </trans-unit> <trans-unit id="WRN_PrefixAndXmlnsLocalName"> <source>It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:{0}' to define a prefix named '{0}'?</source> <target state="translated">建议不要将特性命名为 xmlns。是否有意编写“xmlns:{0}”以定义名为“{0}”的前缀?</target> <note /> </trans-unit> <trans-unit id="WRN_PrefixAndXmlnsLocalName_Title"> <source>It is not recommended to have attributes named xmlns</source> <target state="translated">不建议拥有名为 xmlns 的属性</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSingleScript"> <source>Expected a single script (.vbx file)</source> <target state="translated">需要一个脚本 (.vbx 文件)</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedAssemblyName"> <source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source> <target state="translated">程序集名“{0}”保留名称,不能在交互会话中用作引用</target> <note /> </trans-unit> <trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts"> <source>#R is only allowed in scripts</source> <target state="translated">仅在脚本中允许 #R</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotAllowedInScript"> <source>You cannot declare Namespace in script code</source> <target state="translated">不能在脚本代码中声明命名空间</target> <note /> </trans-unit> <trans-unit id="ERR_KeywordNotAllowedInScript"> <source>You cannot use '{0}' in top-level script code</source> <target state="translated">您不能使用顶级脚本代码中的“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNoType"> <source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source> <target state="translated">无法推断返回类型。请考虑添加一个“As”子句来指定返回类型。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaNoTypeObjectAssumed"> <source>Cannot infer a return type; 'Object' assumed.</source> <target state="translated">无法推断返回类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaNoTypeObjectAssumed_Title"> <source>Cannot infer a return type</source> <target state="translated">无法推断返回类型</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaTooManyTypesObjectAssumed"> <source>Cannot infer a return type because more than one type is possible; 'Object' assumed.</source> <target state="translated">无法推断返回类型,因为可能存在多个类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_LambdaTooManyTypesObjectAssumed_Title"> <source>Cannot infer a return type because more than one type is possible</source> <target state="translated">无法推断返回类型,原因是可能存在多个类型</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaNoTypeObjectDisallowed"> <source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source> <target state="translated">无法推断返回类型。请考虑添加一个 "As" 子句来指定返回类型。</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaTooManyTypesObjectDisallowed"> <source>Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.</source> <target state="translated">无法推断返回类型,因为可能存在多个类型。请考虑添加一个 "As" 子句来指定返回类型。</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch"> <source>The command line switch '{0}' is not yet implemented and was ignored.</source> <target state="translated">命令行开关“{0}”尚未实现,已忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch_Title"> <source>Command line switch is not yet implemented</source> <target state="translated">命令行开关尚未实现</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitNoTypeObjectDisallowed"> <source>Cannot infer an element type, and Option Strict On does not allow 'Object' to be assumed. Specifying the type of the array might correct this error.</source> <target state="translated">无法推断元素类型,且 Option Strict On 不允许假定 "Object"。指定数组的类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitNoType"> <source>Cannot infer an element type. Specifying the type of the array might correct this error.</source> <target state="translated">无法推断元素类型。指定数组的类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitTooManyTypesObjectDisallowed"> <source>Cannot infer an element type because more than one type is possible. Specifying the type of the array might correct this error.</source> <target state="translated">无法推断元素类型,因为可能存在多个类型。指定数组的类型可更正此错误。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitNoTypeObjectAssumed"> <source>Cannot infer an element type; 'Object' assumed.</source> <target state="translated">无法推断元素类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitNoTypeObjectAssumed_Title"> <source>Cannot infer an element type</source> <target state="translated">无法推断元素类型</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed"> <source>Cannot infer an element type because more than one type is possible; 'Object' assumed.</source> <target state="translated">无法推断元素类型,因为可能存在多个类型;假定为 "Object"。</target> <note /> </trans-unit> <trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed_Title"> <source>Cannot infer an element type because more than one type is possible</source> <target state="translated">无法推断元素类型,原因是可能存在多个类型</target> <note /> </trans-unit> <trans-unit id="WRN_TypeInferenceAssumed3"> <source>Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed.</source> <target state="translated">未能推断“{1}”中“{0}”的数据类型。假定为“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_TypeInferenceAssumed3_Title"> <source>Data type could not be inferred</source> <target state="translated">无法推断数据类型</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousCastConversion2"> <source>Option Strict On does not allow implicit conversions from '{0}' to '{1}' because the conversion is ambiguous.</source> <target state="translated">Option Strict 不允许进行“{0}”到“{1}”的隐式转换,因为转换不明确。</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousCastConversion2"> <source>Conversion from '{0}' to '{1}' may be ambiguous.</source> <target state="translated">从“{0}”到“{1}”的转换可能不明确。</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousCastConversion2_Title"> <source>Conversion may be ambiguous</source> <target state="translated">转换可能不明确</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceIEnumerableSuggestion3"> <source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑改用“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceIEnumerableSuggestion3"> <source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑改用“{2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceIEnumerableSuggestion3_Title"> <source>Type cannot be converted to target collection type</source> <target state="translated">无法将类型转换为目标集合类型</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedIn6"> <source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source> <target state="translated">“{4}”不能转换为“{5}”,因为根据“{3}”中“In”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedOut6"> <source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source> <target state="translated">“{4}”不能转换为“{5}”,因为根据“{3}”中“Out”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedIn6"> <source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source> <target state="translated">从“{4}”到“{5}”的隐式转换;此转换可能失败,因为根据“{3}”中“In”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedIn6_Title"> <source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'In' generic parameter</source> <target state="translated">隐式转换;此转换可能失败,原因是目标类型不是从源类型派生的,而这是 "In" 泛型参数所必需的</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedOut6"> <source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source> <target state="translated">从“{4}”到“{5}”的隐式转换;此转换可能失败,因为根据“{3}”中“Out”泛型形参“{2}”的需要,“{0}”不是从“{1}”派生的。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedOut6_Title"> <source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'Out' generic parameter</source> <target state="translated">隐式转换;此转换可能失败,原因是目标类型不是从源类型派生的,而这是 "Out" 泛型参数所必需的</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedTryIn4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceConversionFailedTryOut4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryIn4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 In 类型参数“In {2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryIn4_Title"> <source>Type cannot be converted to target type</source> <target state="translated">无法将类型转换为目标类型</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryOut4"> <source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source> <target state="translated">“{0}”不能转换为“{1}”。考虑在“{3}”的定义中将“{2}”改为 Out 类型参数“Out {2}”。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceConversionFailedTryOut4_Title"> <source>Type cannot be converted to target type</source> <target state="translated">无法将类型转换为目标类型</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceDeclarationAmbiguous3"> <source>Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'.</source> <target state="translated">“{2}”中的“In”和“Out”参数导致接口“{0}”与另一个已实现的接口“{1}”一起使用时目的不明确。</target> <note /> </trans-unit> <trans-unit id="WRN_VarianceDeclarationAmbiguous3_Title"> <source>Interface is ambiguous with another implemented interface due to 'In' and 'Out' parameters</source> <target state="translated">接口对于另一个实现的接口不明确,原因在于 "In" 和 "Out" 参数</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInterfaceNesting"> <source>Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.</source> <target state="translated">无法在含有 "In" 或 "Out" 类型参数的接口中声明枚举、类和结构。</target> <note /> </trans-unit> <trans-unit id="ERR_VariancePreventsSynthesizedEvents2"> <source>Event definitions with parameters are not allowed in an interface such as '{0}' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within '{0}'. For example, 'Event {1} As Action(Of ...)'.</source> <target state="translated">在“{0}”这样的含有“In”或“Out”类型参数的接口中,不允许带参数的事件定义。考虑使用不在“{0}”中定义的委托类型来声明事件。例如,“Event {1} As Action(Of ...)”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInByRefDisallowed1"> <source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“In”和“Out”类型参数不能用于 ByRef 参数类型,且“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInNullableDisallowed2"> <source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用于“{1}”,因为“In”和“Out”类型参数不能设置为可以为 null,并且“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowed1"> <source>Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowedForGeneric3"> <source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{2}”中的“{1}”,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowedHere2"> <source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInParamDisallowedHereForGeneric4"> <source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”中“{3}”的“{2}”,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInPropertyDisallowed1"> <source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly.</source> <target state="translated">在此上下文中,类型“{0}”不能用作属性类型,因为“{0}”是“In”类型参数,且该属性未标记为 WriteOnly。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInReadOnlyPropertyDisallowed1"> <source>Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用作 ReadOnly 属性类型,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInReturnDisallowed1"> <source>Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter.</source> <target state="translated">类型“{0}”不能用作返回类型,因为“{0}”是“In”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutByRefDisallowed1"> <source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“In”和“Out”类型参数不能用于 ByRef 参数类型,且“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutByValDisallowed1"> <source>Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用作 ByVal 参数类型,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutConstraintDisallowed1"> <source>Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用作泛型类型约束,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutNullableDisallowed2"> <source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用于“{1}”,因为“In”和“Out”类型参数不能设置为可以为 null,并且“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowed1"> <source>Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用于此上下文,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowedForGeneric3"> <source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{2}”中的“{1}”,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowedHere2"> <source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutParamDisallowedHereForGeneric4"> <source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter.</source> <target state="translated">在此上下文中,类型“{0}”不能用于“{1}”中“{3}”的“{2}”,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutPropertyDisallowed1"> <source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly.</source> <target state="translated">在此上下文中,类型“{0}”不能用作属性类型,因为“{0}”是“Out”类型参数,且该属性未标记为 ReadOnly。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceOutWriteOnlyPropertyDisallowed1"> <source>Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter.</source> <target state="translated">类型“{0}”不能用作 WriteOnly 属性类型,因为“{0}”是“Out”类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowed2"> <source>Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能用于此上下文,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowedForGeneric4"> <source>Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能在此上下文中用于“{3}”中的“{2}”,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowedHere3"> <source>Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能在此上下文用于“{2}”,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceTypeDisallowedHereForGeneric5"> <source>Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source> <target state="translated">类型“{0}”不能在此上下文中用于“{2}”中“{4}”的“{3}”,因为此上下文和“{0}”的定义均嵌套在接口“{1}”内,而“{1}”含有“In”或“Out”类型参数。考虑将“{0}”的定义移出“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterNotValidForType"> <source>Parameter not valid for the specified unmanaged type.</source> <target state="translated">参数对于指定非托管类型无效。</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields"> <source>Unmanaged type '{0}' not valid for fields.</source> <target state="translated">非托管类型“{0}”对于字段无效。</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields"> <source>Unmanaged type '{0}' is only valid for fields.</source> <target state="translated">非托管类型“{0}”仅对字段有效。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired1"> <source>Attribute parameter '{0}' must be specified.</source> <target state="translated">必须指定特性参数“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired2"> <source>Attribute parameter '{0}' or '{1}' must be specified.</source> <target state="translated">必须指定特性参数“{0}”或“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_MemberConflictWithSynth4"> <source>Conflicts with '{0}', which is implicitly declared for '{1}' in {2} '{3}'.</source> <target state="translated">与为 {2}“{3}”中的“{1}”隐式声明的“{0}”冲突。</target> <note /> </trans-unit> <trans-unit id="IDS_ProjectSettingsLocationName"> <source>&lt;project settings&gt;</source> <target state="translated">&lt;项目设置&gt;</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty"> <source>Attributes applied on a return type of a WriteOnly Property have no effect.</source> <target state="translated">应用于 WriteOnly 属性的返回类型的特性不起作用。</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty_Title"> <source>Attributes applied on a return type of a WriteOnly Property have no effect</source> <target state="translated">应用于 WriteOnly 属性的返回类型的特性不起作用</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidTarget"> <source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source> <target state="translated">安全特性“{0}”对此声明类型无效。安全特性仅对程序集、类型和方法声明有效。</target> <note /> </trans-unit> <trans-unit id="ERR_AbsentReferenceToPIA1"> <source>Cannot find the interop type that matches the embedded type '{0}'. Are you missing an assembly reference?</source> <target state="translated">找不到与嵌入的类型“{0}”匹配的互操作类型。是否缺少程序集引用?</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLinkClassWithNoPIA1"> <source>Reference to class '{0}' is not allowed when its assembly is configured to embed interop types.</source> <target state="translated">当类“{0}”的程序集配置为嵌入互操作类型时,不允许使用对该类的引用。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidStructMemberNoPIA1"> <source>Embedded interop structure '{0}' can contain only public instance fields.</source> <target state="translated">嵌入的互操作结构“{0}”只能包含公共实例字段。</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIAAttributeMissing2"> <source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source> <target state="translated">无法嵌入互操作类型“{0}”,因为它缺少必需的“{1}”特性。</target> <note /> </trans-unit> <trans-unit id="ERR_PIAHasNoAssemblyGuid1"> <source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source> <target state="translated">无法嵌入来自程序集“{0}”的互操作类型,因为它缺少“{1}”特性。</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLocalTypes3"> <source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider disabling the embedding of interop types.</source> <target state="translated">无法嵌入程序集“{1}”和“{2}”中找到的互操作类型“{0}”。请考虑禁用互操作类型的嵌入。</target> <note /> </trans-unit> <trans-unit id="ERR_PIAHasNoTypeLibAttribute1"> <source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source> <target state="translated">无法嵌入来自程序集“{0}”的互操作类型,因为它缺少“{1}”特性或“{2}”特性。</target> <note /> </trans-unit> <trans-unit id="ERR_SourceInterfaceMustBeInterface"> <source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source> <target state="translated">接口“{0}”的源接口无效,该源接口是嵌入事件“{1}”所必需的。</target> <note /> </trans-unit> <trans-unit id="ERR_EventNoPIANoBackingMember"> <source>Source interface '{0}' is missing method '{1}', which is required to embed event '{2}'.</source> <target state="translated">源接口“{0}”缺少方法“{2}”,此方法对嵌入事件“{1}”是必需的。</target> <note /> </trans-unit> <trans-unit id="ERR_NestedInteropType"> <source>Nested type '{0}' cannot be embedded.</source> <target state="translated">无法嵌入嵌套类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_LocalTypeNameClash2"> <source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types.</source> <target state="translated">嵌入来自程序集“{1}”中的互操作类型“{0}”会导致当前程序集中发生名称冲突。请考虑禁用互操作类型的嵌入。</target> <note /> </trans-unit> <trans-unit id="ERR_InteropMethodWithBody1"> <source>Embedded interop method '{0}' contains a body.</source> <target state="translated">嵌入互操作方法“{0}”包含主体。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncInQuery"> <source>'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.</source> <target state="translated">'"Await" 只能在初始 "From" 子句的第一个集合表达式或 "Join" 子句的集合表达式的查询表达式中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_BadGetAwaiterMethod1"> <source>'Await' requires that the type '{0}' have a suitable GetAwaiter method.</source> <target state="translated">'“Await”要求类型“{0}”包含适当的 GetAwaiter 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_BadIsCompletedOnCompletedGetResult2"> <source>'Await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.</source> <target state="translated">'“Await”要求“{1}.GetAwaiter()”的返回类型“{0}”包含适当的 IsCompleted、OnCompleted 和 GetResult 成员,并实现 INotifyCompletion 或 ICriticalNotifyCompletion</target> <note /> </trans-unit> <trans-unit id="ERR_DoesntImplementAwaitInterface2"> <source>'{0}' does not implement '{1}'.</source> <target state="translated">“{0}”未实现“{1}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitNothing"> <source>Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.</source> <target state="translated">不能等待 Nothing。请考虑改为等待“Task.Yield()”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncByRefParam"> <source>Async methods cannot have ByRef parameters.</source> <target state="translated">异步方法不能包含 ByRef 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAsyncIteratorModifiers"> <source>'Async' and 'Iterator' modifiers cannot be used together.</source> <target state="translated">'“Async”和“Iterator”修饰符不能一起使用。</target> <note /> </trans-unit> <trans-unit id="ERR_BadResumableAccessReturnVariable"> <source>The implicit return variable of an Iterator or Async method cannot be accessed.</source> <target state="translated">无法访问迭代器方法或异步方法的隐式返回变量。</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnFromNonGenericTaskAsync"> <source>'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.</source> <target state="translated">'此异步方法中的 "Return" 语句无法返回值,因为函数的返回类型为 "Task" 。请考虑将函数的返回类型更改为 "Task(Of T)"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturnOperand1"> <source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task(Of {0})'.</source> <target state="translated">这是一个异步方法,因此返回表达式的类型必须为“{0}”而不是“Task(Of {0})”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturn"> <source>The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).</source> <target state="translated">只能在 Sub 上或者在返回 Task 或 Task(Of T) 的函数上使用 "Async" 修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_CantAwaitAsyncSub1"> <source>'{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function.</source> <target state="translated">“{0}”不返回 Task 且无法等待。请考虑将它更改为 Async Function。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidLambdaModifier"> <source>'Only the 'Async' or 'Iterator' modifier is valid on a lambda.</source> <target state="translated">'仅“Async”或“Iterator”修饰符在 lambda 上有效。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInNonAsyncMethod"> <source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of {0})'.</source> <target state="translated">'“Await”只能在异步方法中使用。请考虑使用“Async”修饰符标记此方法,并将其返回类型更改为“Task(Of {0})”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInNonAsyncVoidMethod"> <source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.</source> <target state="translated">'“Await”只能用于异步方法中。请考虑用“Async”修饰符标记此方法,并将其返回类型更改为“Task”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInNonAsyncLambda"> <source>'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.</source> <target state="translated">'“Await”只能用于异步 lambda 表达式中。请考虑用“Async”修饰符标记此 lambda 表达式。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitNotInAsyncMethodOrLambda"> <source>'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.</source> <target state="translated">'仅当其包含方法或 lambda 表达式用“Async”修饰符标记时,才能使用“Await”。</target> <note /> </trans-unit> <trans-unit id="ERR_StatementLambdaInExpressionTree"> <source>Statement lambdas cannot be converted to expression trees.</source> <target state="translated">语句 lambda 不能转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression"> <source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.</source> <target state="translated">由于此调用不会等待,因此在调用完成前将继续执行当前方法。请考虑对调用结果应用 Await 运算符。</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression_Title"> <source>Because this call is not awaited, execution of the current method continues before the call is completed</source> <target state="translated">由于此调用不会等待,因此在调用完成前将继续执行当前方法</target> <note /> </trans-unit> <trans-unit id="ERR_LoopControlMustNotAwait"> <source>Loop control variable cannot include an 'Await'.</source> <target state="translated">循环控制变量不可包含 "Await"。</target> <note /> </trans-unit> <trans-unit id="ERR_BadStaticInitializerInResumable"> <source>Static variables cannot appear inside Async or Iterator methods.</source> <target state="translated">静态变量不能出现在异步方法或迭代器方法内。</target> <note /> </trans-unit> <trans-unit id="ERR_RestrictedResumableType1"> <source>'{0}' cannot be used as a parameter type for an Iterator or Async method.</source> <target state="translated">“{0}”不能用作 Iterator 或 Async 方法的参数类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorAsync"> <source>Constructor must not have the 'Async' modifier.</source> <target state="translated">构造函数不得包含“Async”修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodsMustNotBeAsync1"> <source>'{0}' cannot be declared 'Partial' because it has the 'Async' modifier.</source> <target state="translated">“{0}”不能声明为“Partial”,因为它具有“Async”修饰符。</target> <note /> </trans-unit> <trans-unit id="ERR_ResumablesCannotContainOnError"> <source>'On Error' and 'Resume' cannot appear inside async or iterator methods.</source> <target state="translated">'"On Error" 和 "Resume" 不能出现在异步方法或迭代器方法内。</target> <note /> </trans-unit> <trans-unit id="ERR_ResumableLambdaInExpressionTree"> <source>Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.</source> <target state="translated">无法将带 "Async" 或 "Iterator" 修饰符的 lambda 转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotLiftRestrictedTypeResumable1"> <source>Variable of restricted type '{0}' cannot be declared in an Async or Iterator method.</source> <target state="translated">不能在异步方法或迭代器方法中声明受限类型“{0}”的变量。</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInTryHandler"> <source>'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.</source> <target state="translated">'不能在“Catch”语句、“Finally”语句或“SyncLock”语句内使用“Await”。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits"> <source>This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.</source> <target state="translated">此异步方法缺少 "Await" 运算符,因此它将同步运行。请考虑使用 "Await" 运算符等待非阻止 API 调用,或使用 "Await Task.Run(...)" 利用后台线程执行占用大量 CPU 的工作。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits_Title"> <source>This async method lacks 'Await' operators and so will run synchronously</source> <target state="translated">此异步方法缺少 "Await" 运算符,因此将以同步方式运行</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableDelegate"> <source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.</source> <target state="translated">从此 Async Function 返回的任务将被删除,并且忽略其中的任何异常。考虑将其更改为 Async Sub,以便传播其异常。</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableDelegate_Title"> <source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored</source> <target state="translated">自此 Async Function 返回的任务将被丢弃,它包含的任何异常也将被忽略</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalAsyncInClassOrStruct"> <source>Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source> <target state="translated">在具有“SecurityCritical”或“SecuritySafeCritical”属性的 [Class|Structure|Interface|Module] 中不允许使用 Async 或 Iterator 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalAsync"> <source>Security attribute '{0}' cannot be applied to an Async or Iterator method.</source> <target state="translated">安全属性“{0}”不能应用于 Async 或 Iterator 方法。</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnResumableMethod"> <source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.</source> <target state="translated">'"System.Runtime.InteropServices.DllImportAttribute" 不能应用于异步方法或迭代器方法。</target> <note /> </trans-unit> <trans-unit id="ERR_SynchronizedAsyncMethod"> <source>'MethodImplOptions.Synchronized' cannot be applied to an Async method.</source> <target state="translated">'"MethodImplOptions.Synchronized" 不能应用于异步方法。</target> <note /> </trans-unit> <trans-unit id="ERR_AsyncSubMain"> <source>The 'Main' method cannot be marked 'Async'.</source> <target state="translated">"Main" 方法不能标记为 "Async"。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncSubCouldBeFunction"> <source>Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.</source> <target state="translated">此处某些重载使用的是 Async Function 而不是 Async Sub。请考虑使用 Async Function 或将此 Async Sub 显式强制转换为所需类型。</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncSubCouldBeFunction_Title"> <source>Some overloads here take an Async Function rather than an Async Sub</source> <target state="translated">此处的一些重载采用的是 Async Function,而不是 Async Sub</target> <note /> </trans-unit> <trans-unit id="ERR_MyGroupCollectionAttributeCycle"> <source>MyGroupCollectionAttribute cannot be applied to itself.</source> <target state="translated">MyGroupCollectionAttribute 不能应用于自身。</target> <note /> </trans-unit> <trans-unit id="ERR_LiteralExpected"> <source>Literal expected.</source> <target state="translated">应为文本。</target> <note /> </trans-unit> <trans-unit id="ERR_WinRTEventWithoutDelegate"> <source>Event declarations that target WinMD must specify a delegate type. Add an As clause to the event declaration.</source> <target state="translated">面向 WinMD 的事件声明必须指定委托类型。请在事件声明中添加一个 As 子句。</target> <note /> </trans-unit> <trans-unit id="ERR_MixingWinRTAndNETEvents"> <source>Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}'</source> <target state="translated">事件“{0}”无法实现 Windows 运行时事件“{1}”和常规 .NET 事件“{2}”</target> <note /> </trans-unit> <trans-unit id="ERR_EventImplRemoveHandlerParamWrong"> <source>Event '{0}' cannot implement event '{1}' on interface '{2}' because the parameters of their 'RemoveHandler' methods do not match.</source> <target state="translated">事件“{0}”无法实现接口“{2}”上的事件“{1}”,因为其“RemoveHandler”方法的参数不匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_AddParamWrongForWinRT"> <source>The type of the 'AddHandler' method's parameter must be the same as the type of the event.</source> <target state="translated">“AddHandler”方法的参数的类型必须与事件的类型相同。</target> <note /> </trans-unit> <trans-unit id="ERR_RemoveParamWrongForWinRT"> <source>In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken'</source> <target state="translated">在 Windows Runtime 事件中,“RemoveHandler”方法参数的类型必须为“EventRegistrationToken”</target> <note /> </trans-unit> <trans-unit id="ERR_ReImplementingWinRTInterface5"> <source>'{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed</source> <target state="translated">'“实现 {2}”中的“{0}.{1}”已由基类“{3}”实现。不允许重新实现 Windows Runtime 接口“{4}”</target> <note /> </trans-unit> <trans-unit id="ERR_ReImplementingWinRTInterface4"> <source>'{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed</source> <target state="translated">“{0}.{1}”已由基类“{2}”实现。不允许重新实现 Windows Runtime 接口“{3}”</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorByRefParam"> <source>Iterator methods cannot have ByRef parameters.</source> <target state="translated">迭代器方法不能包含 ByRef 参数。</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorExpressionLambda"> <source>Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.</source> <target state="translated">单行 lambda 不能包含“Iterator”修饰符。请改用多行 lambda。</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorReturn"> <source>Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.</source> <target state="translated">迭代器函数必须返回 IEnumerable(Of T) 或 IEnumerator(Of T),或返回非泛型格式的 IEnumerable 或 IEnumerator。</target> <note /> </trans-unit> <trans-unit id="ERR_BadReturnValueInIterator"> <source>To return a value from an Iterator function, use 'Yield' rather than 'Return'.</source> <target state="translated">若要从迭代器函数返回值,请使用“Yield”而不是“Return”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInNonIteratorMethod"> <source>'Yield' can only be used in a method marked with the 'Iterator' modifier.</source> <target state="translated">'只能在用“Iterator”修饰符标记的方法中使用“Yield”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInTryHandler"> <source>'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.</source> <target state="translated">'不能在“Catch”语句或“Finally”语句内使用“Yield”。</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1"> <source>The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source> <target state="translated">Windows 运行时事件“{0}”的 AddHandler 不会在所有代码路径上都返回值。是否缺少“Return”语句?</target> <note /> </trans-unit> <trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1_Title"> <source>The AddHandler for Windows Runtime event doesn't return a value on all code paths</source> <target state="translated">Windows 运行时事件的 AddHandler 没有在所有代码路径上返回值</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodDefaultParameterValueMismatch2"> <source>Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'.</source> <target state="translated">方法“{0}”的可选参数没有与分部方法“{1}”的相应参数相同的默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodParamArrayMismatch2"> <source>Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'.</source> <target state="translated">方法“{0}”的参数在分部方法“{1}”的相应参数的 ParamArray 修饰符上存在差异。</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMismatch"> <source>Module name '{0}' stored in '{1}' must match its filename.</source> <target state="translated">存储在“{1}”中的模块名“{0}”必须与其文件名匹配。</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleName"> <source>Invalid module name: {0}</source> <target state="translated">无效的模块名称: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden"> <source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source.</source> <target state="translated">来自模块“{1}”的特性“{0}”将忽略,以便支持源中出现的实例。</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title"> <source>Attribute from module will be ignored in favor of the instance appearing in source</source> <target state="translated">为支持源中出现的实例,将忽略模块的特性</target> <note /> </trans-unit> <trans-unit id="ERR_CmdOptionConflictsSource"> <source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source> <target state="translated">源文件中提供的特定“{0}”与选项“{1}”冲突。</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName"> <source>Referenced assembly '{0}' does not have a strong name.</source> <target state="translated">引用程序集“{0}”没有强名称。</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title"> <source>Referenced assembly does not have a strong name</source> <target state="translated">引用程序集没有强名称</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSignaturePublicKey"> <source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source> <target state="translated">在 AssemblySignatureKeyAttribute 中指定的签名公钥无效。</target> <note /> </trans-unit> <trans-unit id="ERR_CollisionWithPublicTypeInModule"> <source>Type '{0}' conflicts with public type defined in added module '{1}'.</source> <target state="translated">类型“{0}”与添加的模块“{1}”中定义的公共类型冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypeConflictsWithDeclaration"> <source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">从模块“{1}”导出的类型“{0}”与此程序集主模块中声明的类型冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypesConflict"> <source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">从模块“{1}”导出的类型“{0}”与从模块“{3}”导出的类型“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch"> <source>Referenced assembly '{0}' has different culture setting of '{1}'.</source> <target state="translated">引用程序集“{0}”具有不同区域性设置“{1}”。</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch_Title"> <source>Referenced assembly has different culture setting</source> <target state="translated">引用程序集具有不同区域性设置</target> <note /> </trans-unit> <trans-unit id="ERR_AgnosticToMachineModule"> <source>Agnostic assembly cannot have a processor specific module '{0}'.</source> <target state="translated">不可知的程序集不能具有特定于处理器的模块“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingMachineModule"> <source>Assembly and module '{0}' cannot target different processors.</source> <target state="translated">程序集和模块“{0}”不能以不同处理器为目标。</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly"> <source>Referenced assembly '{0}' targets a different processor.</source> <target state="translated">引用程序集“{0}”面向的是另一个处理器。</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly_Title"> <source>Referenced assembly targets a different processor</source> <target state="translated">引用程序集面向的是另一个处理器</target> <note /> </trans-unit> <trans-unit id="ERR_CryptoHashFailed"> <source>Cryptographic failure while creating hashes.</source> <target state="translated">创建哈希时加密失败。</target> <note /> </trans-unit> <trans-unit id="ERR_CantHaveWin32ResAndManifest"> <source>Conflicting options specified: Win32 resource file; Win32 manifest.</source> <target state="translated">指定的选项冲突: Win32 资源文件;Win32 清单。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration"> <source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">转发的类型“{0}”与此程序集主模块中声明的类型冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypesConflict"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source> <target state="translated">转发到程序集“{1}”的类型“{0}”与转发到程序集“{3}”的类型“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="ERR_TooLongMetadataName"> <source>Name '{0}' exceeds the maximum length allowed in metadata.</source> <target state="translated">名称“{0}”超出元数据中允许的最大长度。</target> <note /> </trans-unit> <trans-unit id="ERR_MissingNetModuleReference"> <source>Reference to '{0}' netmodule missing.</source> <target state="translated">缺少对“{0}”netmodule 的引用。</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMustBeUnique"> <source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source> <target state="translated">模块“{0}”已在此程序集中定义。每个模块必须具有唯一的文件名。</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithExportedType"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">转发到程序集“{1}”的类型“{0}”与从模块“{3}”导出的类型“{2}”冲突。</target> <note /> </trans-unit> <trans-unit id="IDS_MSG_ADDREFERENCE"> <source>Adding assembly reference '{0}'</source> <target state="translated">正在添加程序集引用“{0}”</target> <note /> </trans-unit> <trans-unit id="IDS_MSG_ADDLINKREFERENCE"> <source>Adding embedded assembly reference '{0}'</source> <target state="translated">正在添加嵌入程序集引用“{0}”</target> <note /> </trans-unit> <trans-unit id="IDS_MSG_ADDMODULE"> <source>Adding module reference '{0}'</source> <target state="translated">正在添加模块引用“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_NestingViolatesCLS1"> <source>Type '{0}' does not inherit the generic type parameters of its container.</source> <target state="translated">类型“{0}”不继承其容器的泛型类型参数。</target> <note /> </trans-unit> <trans-unit id="ERR_PDBWritingFailed"> <source>Failure writing debug information: {0}</source> <target state="translated">写入调试信息失败: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute"> <source>The parameter has multiple distinct default values.</source> <target state="translated">参数具有多个不同的默认值。</target> <note /> </trans-unit> <trans-unit id="ERR_FieldHasMultipleDistinctConstantValues"> <source>The field has multiple distinct constant values.</source> <target state="translated">字段具有多个不同的常量值。</target> <note /> </trans-unit> <trans-unit id="ERR_EncNoPIAReference"> <source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source> <target state="translated">无法继续,因为编辑包括对嵌入类型的引用:“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_EncReferenceToAddedMember"> <source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source> <target state="translated">在当前调试会话期间添加的成员“{0}”只能从其声明的程序集“{1}”中访问。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedModule1"> <source>'{0}' is an unsupported .NET module.</source> <target state="translated">“{0}”是不受支持的 .NET 模块。</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedEvent1"> <source>'{0}' is an unsupported event.</source> <target state="translated">“{0}”是不受支持的事件。</target> <note /> </trans-unit> <trans-unit id="PropertiesCanNotHaveTypeArguments"> <source>Properties can not have type arguments</source> <target state="translated">属性不能具有类型参数</target> <note /> </trans-unit> <trans-unit id="IdentifierSyntaxNotWithinSyntaxTree"> <source>IdentifierSyntax not within syntax tree</source> <target state="translated">IdentifierSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="AnonymousObjectCreationExpressionSyntaxNotWithinTree"> <source>AnonymousObjectCreationExpressionSyntax not within syntax tree</source> <target state="translated">AnonymousObjectCreationExpressionSyntax 未在语法树内</target> <note /> </trans-unit> <trans-unit id="FieldInitializerSyntaxNotWithinSyntaxTree"> <source>FieldInitializerSyntax not within syntax tree</source> <target state="translated">FieldInitializerSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="IDS_TheSystemCannotFindThePathSpecified"> <source>The system cannot find the path specified</source> <target state="translated">系统无法找到指定路径</target> <note /> </trans-unit> <trans-unit id="ThereAreNoPointerTypesInVB"> <source>There are no pointer types in VB.</source> <target state="translated">VB 中没有任何指针属性。</target> <note /> </trans-unit> <trans-unit id="ThereIsNoDynamicTypeInVB"> <source>There is no dynamic type in VB.</source> <target state="translated">VB 中没有任何动态类型。</target> <note /> </trans-unit> <trans-unit id="VariableSyntaxNotWithinSyntaxTree"> <source>variableSyntax not within syntax tree</source> <target state="translated">variableSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="AggregateSyntaxNotWithinSyntaxTree"> <source>AggregateSyntax not within syntax tree</source> <target state="translated">AggregateSyntax 未在语法树内</target> <note /> </trans-unit> <trans-unit id="FunctionSyntaxNotWithinSyntaxTree"> <source>FunctionSyntax not within syntax tree</source> <target state="translated">FunctionSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="PositionIsNotWithinSyntax"> <source>Position is not within syntax tree</source> <target state="translated">位置不在语法树中</target> <note /> </trans-unit> <trans-unit id="RangeVariableSyntaxNotWithinSyntaxTree"> <source>RangeVariableSyntax not within syntax tree</source> <target state="translated">RangeVariableSyntax 不在语法树中</target> <note /> </trans-unit> <trans-unit id="DeclarationSyntaxNotWithinSyntaxTree"> <source>DeclarationSyntax not within syntax tree</source> <target state="translated">DeclarationSyntax 未在语法树内</target> <note /> </trans-unit> <trans-unit id="StatementOrExpressionIsNotAValidType"> <source>StatementOrExpression is not an ExecutableStatementSyntax or an ExpressionSyntax</source> <target state="translated">StatementOrExpression 不是 ExecutableStatementSyntax 或 ExpressionSyntax</target> <note /> </trans-unit> <trans-unit id="DeclarationSyntaxNotWithinTree"> <source>DeclarationSyntax not within tree</source> <target state="translated">DeclarationSyntax 未在树内</target> <note /> </trans-unit> <trans-unit id="TypeParameterNotWithinTree"> <source>TypeParameter not within tree</source> <target state="translated">TypeParameter 不在树中</target> <note /> </trans-unit> <trans-unit id="NotWithinTree"> <source> not within tree</source> <target state="translated"> 不在树中</target> <note /> </trans-unit> <trans-unit id="LocationMustBeProvided"> <source>Location must be provided in order to provide minimal type qualification.</source> <target state="translated">必须提供位置才能提供最低程度的类型限定。</target> <note /> </trans-unit> <trans-unit id="SemanticModelMustBeProvided"> <source>SemanticModel must be provided in order to provide minimal type qualification.</source> <target state="translated">必须提供 SemanticModel 才能提供最低程度的类型限定。</target> <note /> </trans-unit> <trans-unit id="NumberOfTypeParametersAndArgumentsMustMatch"> <source>the number of type parameters and arguments should be the same</source> <target state="translated">类型形参和实参的数量应相同</target> <note /> </trans-unit> <trans-unit id="ERR_ResourceInModule"> <source>Cannot link resource files when building a module</source> <target state="translated">生成模块时,无法链接资源文件</target> <note /> </trans-unit> <trans-unit id="NotAVbSymbol"> <source>Not a VB symbol.</source> <target state="translated">不是 VB 符号。</target> <note /> </trans-unit> <trans-unit id="ElementsCannotBeNull"> <source>Elements cannot be null.</source> <target state="translated">元素不能为 Null。</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportClause"> <source>Unused import clause.</source> <target state="translated">未使用导入子句。</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportStatement"> <source>Unused import statement.</source> <target state="translated">未使用导入语句。</target> <note /> </trans-unit> <trans-unit id="WrongSemanticModelType"> <source>Expected a {0} SemanticModel.</source> <target state="translated">应为 {0} SemanticModel。</target> <note /> </trans-unit> <trans-unit id="PositionNotWithinTree"> <source>Position must be within span of the syntax tree.</source> <target state="translated">位置必须处于语法树范围内。</target> <note /> </trans-unit> <trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation"> <source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source> <target state="translated">要推断的语法节点不能属于来自当前编译的语法树。</target> <note /> </trans-unit> <trans-unit id="ChainingSpeculativeModelIsNotSupported"> <source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source> <target state="translated">不支持链接推理语义模型。应从非推理 ParentModel 创建推理模型。</target> <note /> </trans-unit> <trans-unit id="IDS_ToolName"> <source>Microsoft (R) Visual Basic Compiler</source> <target state="translated">Microsoft (R) Visual Basic 编译器</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine1"> <source>{0} version {1}</source> <target state="translated">{0} 版本 {1}</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">版权所有(C) Microsoft Corporation。保留所有权利。</target> <note /> </trans-unit> <trans-unit id="IDS_LangVersions"> <source>Supported language versions:</source> <target state="translated">支持的语言版本:</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong"> <source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source> <target state="translated">本地名称“{0}”对于 PDB 太长。请考虑缩短或在不使用 /debug 的情况下编译。</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong_Title"> <source>Local name is too long for PDB</source> <target state="translated">本地名称对于 PDB 太长</target> <note /> </trans-unit> <trans-unit id="WRN_PdbUsingNameTooLong"> <source>Import string '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source> <target state="translated">导入字符串“{0}”对于 PDB 太长。请考虑缩短或在不使用 /debug 的情况下编译。</target> <note /> </trans-unit> <trans-unit id="WRN_PdbUsingNameTooLong_Title"> <source>Import string is too long for PDB</source> <target state="translated">导入字符串对 PDB 而言太长</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefToTypeParameter"> <source>XML comment has a tag with a 'cref' attribute '{0}' that bound to a type parameter. Use the &lt;typeparamref&gt; tag instead.</source> <target state="translated">XML 注释中的一个标记具有绑定到类型参数的“cref”特性“{0}”。请改用 &lt;typeparamref&gt; 标记。</target> <note /> </trans-unit> <trans-unit id="WRN_XMLDocCrefToTypeParameter_Title"> <source>XML comment has a tag with a 'cref' attribute that bound to a type parameter</source> <target state="translated">XML 注释包含的一个标记具有绑定到类型参数的 "cref" 属性</target> <note /> </trans-unit> <trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage"> <source>Linked netmodule metadata must provide a full PE image: '{0}'.</source> <target state="translated">链接 netmodule 元数据必须提供完整 PE 映像:“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated"> <source>An instance of analyzer {0} cannot be created from {1} : {2}.</source> <target state="translated">无法从 {1} 创建分析器 {0} 的实例: {2}。</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated_Title"> <source>Instance of analyzer cannot be created</source> <target state="translated">无法创建分析器实例</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly"> <source>The assembly {0} does not contain any analyzers.</source> <target state="translated">程序集 {0} 不包含任何分析器。</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly_Title"> <source>Assembly does not contain any analyzers</source> <target state="translated">程序集不包含任何分析器</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer"> <source>Unable to load analyzer assembly {0} : {1}.</source> <target state="translated">无法加载分析器程序集 {0}: {1}。</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer_Title"> <source>Unable to load analyzer assembly</source> <target state="translated">无法加载分析器程序集</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer"> <source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source> <target state="translated">正在跳过分析器程序集 {0} 中的某些类型,因为出现 ReflectionTypeLoadException: {1}。</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title"> <source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source> <target state="translated">跳过加载分析器程序集中因 ReflectionTypeLoadException 而失败的类型</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadRulesetFile"> <source>Error reading ruleset file {0} - {1}</source> <target state="translated">读取规则集文件 {0} 时出错 - {1}</target> <note /> </trans-unit> <trans-unit id="ERR_PlatformDoesntSupport"> <source>{0} is not supported in current project type.</source> <target state="translated">当前项目类型不支持 {0}。</target> <note /> </trans-unit> <trans-unit id="ERR_CantUseRequiredAttribute"> <source>The RequiredAttribute attribute is not permitted on Visual Basic types.</source> <target state="translated">Visual Basic 类型上不允许有 RequiredAttribute 特性。</target> <note /> </trans-unit> <trans-unit id="ERR_EncodinglessSyntaxTree"> <source>Cannot emit debug information for a source text without encoding.</source> <target state="translated">无法在不进行编码的情况下发出源文本的调试信息。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFormatSpecifier"> <source>'{0}' is not a valid format specifier</source> <target state="translated">“{0}”不是有效的格式说明符</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPreprocessorConstantType"> <source>Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed.</source> <target state="translated">不支持“{1}”类型的预处理器常数“{0}”,仅允许使用基元类型。</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedWarningKeyword"> <source>'Warning' expected.</source> <target state="translated">'应为“Warning”。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotBeMadeNullable1"> <source>'{0}' cannot be made nullable.</source> <target state="translated">“{0}”不可以为 Null。</target> <note /> </trans-unit> <trans-unit id="ERR_BadConditionalWithRef"> <source>Leading '?' can only appear inside a 'With' statement, but not inside an object member initializer.</source> <target state="translated">以 "?" 开头的情况只能出现在“With”语句中,不能出现在对象成员初始值设定项中。</target> <note /> </trans-unit> <trans-unit id="ERR_NullPropagatingOpInExpressionTree"> <source>A null propagating operator cannot be converted into an expression tree.</source> <target state="translated">无法将 null 传播运算符转换为表达式树。</target> <note /> </trans-unit> <trans-unit id="ERR_TooLongOrComplexExpression"> <source>An expression is too long or complex to compile</source> <target state="translated">表达式太长或者过于复杂,无法编译</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionDoesntHaveName"> <source>This expression does not have a name.</source> <target state="translated">该表达式不具有名称。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNameOfSubExpression"> <source>This sub-expression cannot be used inside NameOf argument.</source> <target state="translated">此子表达式不能在 NameOf 参数中使用。</target> <note /> </trans-unit> <trans-unit id="ERR_MethodTypeArgsUnexpected"> <source>Method type arguments unexpected.</source> <target state="translated">意外的方法类型参数。</target> <note /> </trans-unit> <trans-unit id="NoNoneSearchCriteria"> <source>SearchCriteria is expected.</source> <target state="translated">需要 SearchCriteria。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCulture"> <source>Assembly culture strings may not contain embedded NUL characters.</source> <target state="translated">程序集区域性字符串可能不包含嵌入式 NUL 字符。</target> <note /> </trans-unit> <trans-unit id="ERR_InReferencedAssembly"> <source>There is an error in a referenced assembly '{0}'.</source> <target state="translated">引用的程序集“{0}”中有错误。</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolationFormatWhitespace"> <source>Format specifier may not contain trailing whitespace.</source> <target state="translated">格式说明符可能不包含尾随空格。</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolationAlignmentOutOfRange"> <source>Alignment value is outside of the supported range.</source> <target state="translated">对齐值不在支持的范围内。</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringFactoryError"> <source>There were one or more errors emitting a call to {0}.{1}. Method or its return type may be missing or malformed.</source> <target state="translated">向 {0}.{1} 发出调用时出现一个或多个错误。方法或其返回类型可能缺失或格式不正确。</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportClause_Title"> <source>Unused import clause</source> <target state="translated">未使用 import 子句</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedImportStatement_Title"> <source>Unused import statement</source> <target state="translated">未使用 import 语句</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantStringTooLong"> <source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source> <target state="translated">由串联所得的字符串常量长度超过了 System.Int32.MaxValue。请尝试将字符串拆分为多个常量。</target> <note /> </trans-unit> <trans-unit id="ERR_LanguageVersion"> <source>Visual Basic {0} does not support {1}.</source> <target state="translated">Visual Basic {0} 不支持 {1}。</target> <note /> </trans-unit> <trans-unit id="ERR_BadPdbData"> <source>Error reading debug information for '{0}'</source> <target state="translated">读取“{0}”的调试信息时出错</target> <note /> </trans-unit> <trans-unit id="FEATURE_ArrayLiterals"> <source>array literal expressions</source> <target state="translated">数组文本表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_AsyncExpressions"> <source>async methods or lambdas</source> <target state="translated">异步方法或 lambda</target> <note /> </trans-unit> <trans-unit id="FEATURE_AutoProperties"> <source>auto-implemented properties</source> <target state="translated">自动实现的属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_ReadonlyAutoProperties"> <source>readonly auto-implemented properties</source> <target state="translated">自动实现的只读属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_CoContraVariance"> <source>variance</source> <target state="translated">变型</target> <note /> </trans-unit> <trans-unit id="FEATURE_CollectionInitializers"> <source>collection initializers</source> <target state="translated">集合初始值设定项</target> <note /> </trans-unit> <trans-unit id="FEATURE_GlobalNamespace"> <source>declaring a Global namespace</source> <target state="translated">声明全局命名空间</target> <note /> </trans-unit> <trans-unit id="FEATURE_Iterators"> <source>iterators</source> <target state="translated">迭代器</target> <note /> </trans-unit> <trans-unit id="FEATURE_LineContinuation"> <source>implicit line continuation</source> <target state="translated">隐式行继续符</target> <note /> </trans-unit> <trans-unit id="FEATURE_StatementLambdas"> <source>multi-line lambda expressions</source> <target state="translated">多行 lambda 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_SubLambdas"> <source>'Sub' lambda expressions</source> <target state="translated">'“Sub”lambda 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_NullPropagatingOperator"> <source>null conditional operations</source> <target state="translated">空条件操作</target> <note /> </trans-unit> <trans-unit id="FEATURE_NameOfExpressions"> <source>'nameof' expressions</source> <target state="translated">'"nameof" 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_RegionsEverywhere"> <source>region directives within method bodies or regions crossing boundaries of declaration blocks</source> <target state="translated">方法主体内的 region 指令或跨声明块边界的 region</target> <note /> </trans-unit> <trans-unit id="FEATURE_MultilineStringLiterals"> <source>multiline string literals</source> <target state="translated">多行字符串文本</target> <note /> </trans-unit> <trans-unit id="FEATURE_CObjInAttributeArguments"> <source>CObj in attribute arguments</source> <target state="translated">属性参数中的 CObj</target> <note /> </trans-unit> <trans-unit id="FEATURE_LineContinuationComments"> <source>line continuation comments</source> <target state="translated">行延续注释</target> <note /> </trans-unit> <trans-unit id="FEATURE_TypeOfIsNot"> <source>TypeOf IsNot expression</source> <target state="translated">TypeOf IsNot 表达式</target> <note /> </trans-unit> <trans-unit id="FEATURE_YearFirstDateLiterals"> <source>year-first date literals</source> <target state="translated">年份在最前面的日期文本</target> <note /> </trans-unit> <trans-unit id="FEATURE_WarningDirectives"> <source>warning directives</source> <target state="translated">warning 指令</target> <note /> </trans-unit> <trans-unit id="FEATURE_PartialModules"> <source>partial modules</source> <target state="translated">部分模块</target> <note /> </trans-unit> <trans-unit id="FEATURE_PartialInterfaces"> <source>partial interfaces</source> <target state="translated">部分接口</target> <note /> </trans-unit> <trans-unit id="FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite"> <source>implementing read-only or write-only property with read-write property</source> <target state="translated">使用读写属性实现只读或只写属性</target> <note /> </trans-unit> <trans-unit id="FEATURE_DigitSeparators"> <source>digit separators</source> <target state="translated">数字分隔符</target> <note /> </trans-unit> <trans-unit id="FEATURE_BinaryLiterals"> <source>binary literals</source> <target state="translated">二进制文字</target> <note /> </trans-unit> <trans-unit id="FEATURE_Tuples"> <source>tuples</source> <target state="translated">元组</target> <note /> </trans-unit> <trans-unit id="FEATURE_PrivateProtected"> <source>Private Protected</source> <target state="translated">Private Protected</target> <note /> </trans-unit> <trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition"> <source>Debug entry point must be a definition of a method declared in the current compilation.</source> <target state="translated">调试入口点必须是当前编译中声明的方法的定义。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPathMap"> <source>The pathmap option was incorrectly formatted.</source> <target state="translated">路径映射选项的格式不正确。</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeIsNotASubmission"> <source>Syntax tree should be created from a submission.</source> <target state="translated">应从提交创建语法树。</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyUserStrings"> <source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string or XML literals.</source> <target state="translated">该程序所使用的用户字符串的合并后长度超出所允许的限制。请尝试减少字符串文本或 XML 文本的使用。</target> <note /> </trans-unit> <trans-unit id="ERR_PeWritingFailure"> <source>An error occurred while writing the output file: {0}</source> <target state="translated">写入输出文件时出错: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_OptionMustBeAbsolutePath"> <source>Option '{0}' must be an absolute path.</source> <target state="translated">选项“{0}”必须是绝对路径。</target> <note /> </trans-unit> <trans-unit id="ERR_SourceLinkRequiresPdb"> <source>/sourcelink switch is only supported when emitting PDB.</source> <target state="translated">只在发出 PDB 时才支持 /sourcelink 开关。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleDuplicateElementName"> <source>Tuple element names must be unique.</source> <target state="translated">元组元素名称必须是唯一的。</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch"> <source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source> <target state="translated">由于目标类型“{1}”指定了其他名称或未指定名称,因此元组元素名称“{0}”被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch_Title"> <source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source> <target state="translated">由于分配目标指定了其他名称或未指定名称,因此元组元素名称被忽略。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementName"> <source>Tuple element name '{0}' is only allowed at position {1}.</source> <target state="translated">只允许位置 {1} 使用元组元素名称“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementNameAnyPosition"> <source>Tuple element name '{0}' is disallowed at any position.</source> <target state="translated">任何位置都不允许使用元组元素名称“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleTooFewElements"> <source>Tuple must contain at least two elements.</source> <target state="translated">元组必须包含至少两个元素。</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNamesAttributeMissing"> <source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source> <target state="translated">由于找不到编译器必需的类型“{0}”,因此无法使用元组来定义类或成员。是否缺少引用?</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitTupleElementNamesAttribute"> <source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source> <target state="translated">无法显式引用 "System.Runtime.CompilerServices.TupleElementNamesAttribute"。请使用元组语法指定元组名称。</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturningCallInExpressionTree"> <source>An expression tree may not contain a call to a method or property that returns by reference.</source> <target state="translated">表达式树不能包含对引用所返回的方法或属性的调用。</target> <note /> </trans-unit> <trans-unit id="ERR_CannotEmbedWithoutPdb"> <source>/embed switch is only supported when emitting a PDB.</source> <target state="translated">仅在发出 PDB 时才支持 /embed 开关。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInstrumentationKind"> <source>Invalid instrumentation kind: {0}</source> <target state="translated">无效的检测类型: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DocFileGen"> <source>Error writing to XML documentation file: {0}</source> <target state="translated">写入 XML 文档文件时出错: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAssemblyName"> <source>Invalid assembly name: {0}</source> <target state="translated">无效的程序集名称: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_TypeForwardedToMultipleAssemblies"> <source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source> <target state="translated">程序集“{1}”中的模块“{0}”将类型“{2}”转发到多个程序集: “{3}”和“{4}”。</target> <note /> </trans-unit> <trans-unit id="ERR_Merge_conflict_marker_encountered"> <source>Merge conflict marker encountered</source> <target state="translated">遇到合并冲突标记</target> <note /> </trans-unit> <trans-unit id="ERR_NoRefOutWhenRefOnly"> <source>Do not use refout when using refonly.</source> <target state="translated">不要在使用 refonly 时使用 refout。</target> <note /> </trans-unit> <trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly"> <source>Cannot compile net modules when using /refout or /refonly.</source> <target state="translated">无法在使用 /refout 或 /refonly 时编译 Net 模块。</target> <note /> </trans-unit> <trans-unit id="ERR_BadNonTrailingNamedArgument"> <source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source> <target state="translated">命名参数“{0}”的使用位置不当,但后跟一个未命名参数</target> <note /> </trans-unit> <trans-unit id="ERR_BadDocumentationMode"> <source>Provided documentation mode is unsupported or invalid: '{0}'.</source> <target state="translated">提供的文档模式不受支持或无效:“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadLanguageVersion"> <source>Provided language version is unsupported or invalid: '{0}'.</source> <target state="translated">提供的语言版本不受支持或无效:“{0}”。</target> <note /> </trans-unit> <trans-unit id="ERR_BadSourceCodeKind"> <source>Provided source code kind is unsupported or invalid: '{0}'</source> <target state="translated">提供的源代码类型不受支持或无效:“{0}”</target> <note /> </trans-unit> <trans-unit id="ERR_TupleInferredNamesNotAvailable"> <source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source> <target state="translated">推断出元组元素名称“{0}”。请使用语言版本 {1} 或更高版本按推断名称访问元素。</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental"> <source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">“{0}”仅用于评估,在将来的更新中可能会被更改或删除。</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental_Title"> <source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">类型仅用于评估,在将来的更新中可能会被更改或删除。</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInfo"> <source>Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}'</source> <target state="translated">无法从程序集“{2}”读取方法“{0}”(令牌 0x{1})的调试信息</target> <note /> </trans-unit> <trans-unit id="IConversionExpressionIsNotVisualBasicConversion"> <source>{0} is not a valid Visual Basic conversion expression</source> <target state="translated">{0} 不是有效的 Visual Basic 转换表达式</target> <note /> </trans-unit> <trans-unit id="IArgumentIsNotVisualBasicArgument"> <source>{0} is not a valid Visual Basic argument</source> <target state="translated">{0} 不是有效的 Visual Basic 参数</target> <note /> </trans-unit> <trans-unit id="FEATURE_LeadingDigitSeparator"> <source>leading digit separator</source> <target state="translated">前导数字分隔符</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTupleResolutionAmbiguous3"> <source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source> <target state="translated">已在多个引用的程序集(“{1}”和“{2}”)中声明了预定义类型“{0}”</target> <note /> </trans-unit> <trans-unit id="ICompoundAssignmentOperationIsNotVisualBasicCompoundAssignment"> <source>{0} is not a valid Visual Basic compound assignment operation</source> <target state="translated">{0} 不是有效的 Visual Basic 复合赋值运算</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidHashAlgorithmName"> <source>Invalid hash algorithm name: '{0}'</source> <target state="translated">无效的哈希算法名称:“{0}”</target> <note /> </trans-unit> <trans-unit id="FEATURE_InterpolatedStrings"> <source>interpolated strings</source> <target state="translated">内插字符串</target> <note /> </trans-unit> <trans-unit id="FTL_InvalidInputFileName"> <source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source> <target state="translated">文件名“{0}”为空、包含无效字符、未使用绝对路径指定驱动器或太长</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeNotSupportedInVB"> <source>'{0}' is not supported in VB.</source> <target state="translated">VB 中不支持“{0}”。</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeNotSupportedInVB_Title"> <source>Attribute is not supported in VB</source> <target state="translated">VB 中不支持属性</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_RaiseEvent.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode Dim syntax = node.Syntax Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) ' in the absence of errors invocation must be a call '(could also be BadExpression, but that would have errors) Dim raiseCallExpression = DirectCast(node.EventInvocation, BoundCall) Dim result As BoundStatement Dim receiver = raiseCallExpression.ReceiverOpt If receiver Is Nothing OrElse receiver.IsMeReference Then result = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Else Debug.Assert(receiver.Kind = BoundKind.FieldAccess) #If DEBUG Then ' NOTE: The receiver is always as lowered as it's going to get (generally, a MeReference), so there's no need to Visit it. Dim fieldAccess As BoundFieldAccess = DirectCast(receiver, BoundFieldAccess) Dim fieldAccessReceiver = fieldAccess.ReceiverOpt Debug.Assert(fieldAccessReceiver Is Nothing OrElse fieldAccessReceiver.Kind = BoundKind.MeReference) #End If If node.EventSymbol.IsWindowsRuntimeEvent Then receiver = GetWindowsRuntimeEventReceiver(syntax, receiver) End If ' Need to null-check the receiver before invoking raise - ' ' eventField.raiseCallExpression === becomes ===> ' ' Block ' Dim temp = eventField ' if temp is Nothing GoTo skipEventRaise ' Call temp.raiseCallExpression ' skipEventRaise: ' End Block ' Dim temp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, receiver.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As BoundLocal = New BoundLocal(syntax, temp, temp.Type).MakeCompilerGenerated Dim tempInit = New BoundExpressionStatement(syntax, New BoundAssignmentOperator(syntax, tempAccess, receiver, True, receiver.Type)).MakeCompilerGenerated ' replace receiver with temp. raiseCallExpression = raiseCallExpression.Update(raiseCallExpression.Method, raiseCallExpression.MethodGroupOpt, tempAccess, raiseCallExpression.Arguments, raiseCallExpression.DefaultArguments, raiseCallExpression.ConstantValueOpt, isLValue:=raiseCallExpression.IsLValue, suppressObjectClone:=raiseCallExpression.SuppressObjectClone, type:=raiseCallExpression.Type) Dim invokeStatement = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Dim condition = New BoundBinaryOperator(syntax, BinaryOperatorKind.Is, tempAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, Me.Compilation.GetSpecialType(SpecialType.System_Object)), False, Me.Compilation.GetSpecialType(SpecialType.System_Boolean)).MakeCompilerGenerated Dim skipEventRaise As New GeneratedLabelSymbol("skipEventRaise") Dim ifNullSkip = New BoundConditionalGoto(syntax, condition, True, skipEventRaise).MakeCompilerGenerated result = New BoundBlock(syntax, Nothing, ImmutableArray.Create(temp), ImmutableArray.Create(Of BoundStatement)( tempInit, ifNullSkip, invokeStatement, New BoundLabelStatement(syntax, skipEventRaise))) End If RestoreUnstructuredExceptionHandlingContext(node, saveState) If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then result = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, result, canThrow:=True) End If If Instrument(node, result) Then result = _instrumenterOpt.InstrumentRaiseEventStatement(node, result) End If Return result End Function ' If the event is a WinRT event, then the backing field is actually an EventRegistrationTokenTable, ' rather than a delegate. If this is the case, then we replace the receiver with ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(eventField).InvocationList. Private Function GetWindowsRuntimeEventReceiver(syntax As SyntaxNode, rewrittenReceiver As BoundExpression) As BoundExpression Dim fieldType As NamedTypeSymbol = DirectCast(rewrittenReceiver.Type, NamedTypeSymbol) Debug.Assert(fieldType.Name = "EventRegistrationTokenTable") Dim getOrCreateMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable), MethodSymbol) Debug.Assert(getOrCreateMethod IsNot Nothing, "Checked during initial binding") Debug.Assert(TypeSymbol.Equals(getOrCreateMethod.ReturnType, fieldType.OriginalDefinition, TypeCompareKind.ConsiderEverything), "Shape of well-known member") getOrCreateMethod = getOrCreateMethod.AsMember(fieldType) Dim invocationListProperty As PropertySymbol = Nothing If TryGetWellknownMember(invocationListProperty, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, syntax) Then Dim invocationListAccessor As MethodSymbol = invocationListProperty.GetMethod If invocationListAccessor IsNot Nothing Then invocationListAccessor = invocationListAccessor.AsMember(fieldType) ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable) Dim getOrCreateCall = New BoundCall(syntax:=syntax, method:=getOrCreateMethod, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray.Create(Of BoundExpression)(rewrittenReceiver), constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=getOrCreateMethod.ReturnType).MakeCompilerGenerated() ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable).InvocationList Dim invocationListAccessorCall = New BoundCall(syntax:=syntax, method:=invocationListAccessor, methodGroupOpt:=Nothing, receiverOpt:=getOrCreateCall, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=invocationListAccessor.ReturnType).MakeCompilerGenerated() Return invocationListAccessorCall End If Dim memberDescriptor As MemberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList) ' isWinMd only matters for set accessors, we can safely say false here Dim accessorName As String = Binder.GetAccessorName(invocationListProperty.Name, MethodKind.PropertyGet, isWinMd:=False) Dim info = GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, accessorName, _compilationState.Compilation.Options.EmbedVbCoreRuntime) _diagnostics.Add(info, syntax.GetLocation()) End If Return New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(rewrittenReceiver), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode Dim syntax = node.Syntax Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) ' in the absence of errors invocation must be a call '(could also be BadExpression, but that would have errors) Dim raiseCallExpression = DirectCast(node.EventInvocation, BoundCall) Dim result As BoundStatement Dim receiver = raiseCallExpression.ReceiverOpt If receiver Is Nothing OrElse receiver.IsMeReference Then result = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Else Debug.Assert(receiver.Kind = BoundKind.FieldAccess) #If DEBUG Then ' NOTE: The receiver is always as lowered as it's going to get (generally, a MeReference), so there's no need to Visit it. Dim fieldAccess As BoundFieldAccess = DirectCast(receiver, BoundFieldAccess) Dim fieldAccessReceiver = fieldAccess.ReceiverOpt Debug.Assert(fieldAccessReceiver Is Nothing OrElse fieldAccessReceiver.Kind = BoundKind.MeReference) #End If If node.EventSymbol.IsWindowsRuntimeEvent Then receiver = GetWindowsRuntimeEventReceiver(syntax, receiver) End If ' Need to null-check the receiver before invoking raise - ' ' eventField.raiseCallExpression === becomes ===> ' ' Block ' Dim temp = eventField ' if temp is Nothing GoTo skipEventRaise ' Call temp.raiseCallExpression ' skipEventRaise: ' End Block ' Dim temp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, receiver.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As BoundLocal = New BoundLocal(syntax, temp, temp.Type).MakeCompilerGenerated Dim tempInit = New BoundExpressionStatement(syntax, New BoundAssignmentOperator(syntax, tempAccess, receiver, True, receiver.Type)).MakeCompilerGenerated ' replace receiver with temp. raiseCallExpression = raiseCallExpression.Update(raiseCallExpression.Method, raiseCallExpression.MethodGroupOpt, tempAccess, raiseCallExpression.Arguments, raiseCallExpression.DefaultArguments, raiseCallExpression.ConstantValueOpt, isLValue:=raiseCallExpression.IsLValue, suppressObjectClone:=raiseCallExpression.SuppressObjectClone, type:=raiseCallExpression.Type) Dim invokeStatement = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Dim condition = New BoundBinaryOperator(syntax, BinaryOperatorKind.Is, tempAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, Me.Compilation.GetSpecialType(SpecialType.System_Object)), False, Me.Compilation.GetSpecialType(SpecialType.System_Boolean)).MakeCompilerGenerated Dim skipEventRaise As New GeneratedLabelSymbol("skipEventRaise") Dim ifNullSkip = New BoundConditionalGoto(syntax, condition, True, skipEventRaise).MakeCompilerGenerated result = New BoundBlock(syntax, Nothing, ImmutableArray.Create(temp), ImmutableArray.Create(Of BoundStatement)( tempInit, ifNullSkip, invokeStatement, New BoundLabelStatement(syntax, skipEventRaise))) End If RestoreUnstructuredExceptionHandlingContext(node, saveState) If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then result = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, result, canThrow:=True) End If If Instrument(node, result) Then result = _instrumenterOpt.InstrumentRaiseEventStatement(node, result) End If Return result End Function ' If the event is a WinRT event, then the backing field is actually an EventRegistrationTokenTable, ' rather than a delegate. If this is the case, then we replace the receiver with ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(eventField).InvocationList. Private Function GetWindowsRuntimeEventReceiver(syntax As SyntaxNode, rewrittenReceiver As BoundExpression) As BoundExpression Dim fieldType As NamedTypeSymbol = DirectCast(rewrittenReceiver.Type, NamedTypeSymbol) Debug.Assert(fieldType.Name = "EventRegistrationTokenTable") Dim getOrCreateMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable), MethodSymbol) Debug.Assert(getOrCreateMethod IsNot Nothing, "Checked during initial binding") Debug.Assert(TypeSymbol.Equals(getOrCreateMethod.ReturnType, fieldType.OriginalDefinition, TypeCompareKind.ConsiderEverything), "Shape of well-known member") getOrCreateMethod = getOrCreateMethod.AsMember(fieldType) Dim invocationListProperty As PropertySymbol = Nothing If TryGetWellknownMember(invocationListProperty, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, syntax) Then Dim invocationListAccessor As MethodSymbol = invocationListProperty.GetMethod If invocationListAccessor IsNot Nothing Then invocationListAccessor = invocationListAccessor.AsMember(fieldType) ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable) Dim getOrCreateCall = New BoundCall(syntax:=syntax, method:=getOrCreateMethod, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray.Create(Of BoundExpression)(rewrittenReceiver), constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=getOrCreateMethod.ReturnType).MakeCompilerGenerated() ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable).InvocationList Dim invocationListAccessorCall = New BoundCall(syntax:=syntax, method:=invocationListAccessor, methodGroupOpt:=Nothing, receiverOpt:=getOrCreateCall, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=invocationListAccessor.ReturnType).MakeCompilerGenerated() Return invocationListAccessorCall End If Dim memberDescriptor As MemberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList) ' isWinMd only matters for set accessors, we can safely say false here Dim accessorName As String = Binder.GetAccessorName(invocationListProperty.Name, MethodKind.PropertyGet, isWinMd:=False) Dim info = GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, accessorName, _compilationState.Compilation.Options.EmbedVbCoreRuntime) _diagnostics.Add(info, syntax.GetLocation()) End If Return New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(rewrittenReceiver), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End Function End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/Lsif/Generator/Graph/IdFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// A little class which holds onto the next ID to be produced. Avoids static state in unit testing. /// </summary> internal sealed class IdFactory { /// <summary> /// The next numberic ID that will be used for an object. Accessed only with Interlocked.Increment. /// </summary> private int _globalId = 0; public Id<T> Create<T>() where T : Element { var id = Interlocked.Increment(ref _globalId); return new Id<T>(id); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// A little class which holds onto the next ID to be produced. Avoids static state in unit testing. /// </summary> internal sealed class IdFactory { /// <summary> /// The next numberic ID that will be used for an object. Accessed only with Interlocked.Increment. /// </summary> private int _globalId = 0; public Id<T> Create<T>() where T : Element { var id = Interlocked.Increment(ref _globalId); return new Id<T>(id); } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_Declarations_AllDeclarations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { /// <summary> /// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name. /// </summary> public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync( Project project, string name, bool ignoreCase, CancellationToken cancellationToken = default) { using var query = SearchQuery.Create(name, ignoreCase); var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, query, SymbolFilter.All, cancellationToken).ConfigureAwait(false); return declarations; } /// <summary> /// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name. /// </summary> public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync( Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken = default) { using var query = SearchQuery.Create(name, ignoreCase); var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, query, filter, cancellationToken).ConfigureAwait(false); return declarations; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { /// <summary> /// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name. /// </summary> public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync( Project project, string name, bool ignoreCase, CancellationToken cancellationToken = default) { using var query = SearchQuery.Create(name, ignoreCase); var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, query, SymbolFilter.All, cancellationToken).ConfigureAwait(false); return declarations; } /// <summary> /// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name. /// </summary> public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync( Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken = default) { using var query = SearchQuery.Create(name, ignoreCase); var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, query, filter, cancellationToken).ConfigureAwait(false); return declarations; } } }
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_BinaryOperators.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class LocalRewriter Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode If _inExpressionLambda Then Return node.Update(node.OperatorKind, DirectCast(Visit(node.UnderlyingExpression), BoundExpression), node.Checked, node.Type) End If If (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then Return RewriteLiftedUserDefinedBinaryOperator(node) End If Return Visit(node.UnderlyingExpression) End Function Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode If _inExpressionLambda Then ' If we are inside expression lambda we need to rewrite it into just a bitwise operator call Dim placeholder As BoundRValuePlaceholder = node.LeftOperandPlaceholder Dim leftOperand As BoundExpression = node.LeftOperand If placeholder IsNot Nothing Then Debug.Assert(leftOperand IsNot Nothing) AddPlaceholderReplacement(placeholder, VisitExpression(leftOperand)) End If Dim rewritten = DirectCast(VisitExpression(node.BitwiseOperator), BoundUserDefinedBinaryOperator) If placeholder IsNot Nothing Then RemovePlaceholderReplacement(placeholder) End If ' NOTE: Everything but 'rewritten' will be discarded by ExpressionLambdaRewriter ' we keep the node only to make sure we can replace 'And' with 'AndAlso' ' and 'Or' with 'OrElse' when generating proper factory calls. Return node.Update(node.LeftOperand, node.LeftOperandPlaceholder, node.LeftTest, rewritten, node.Type) End If ' The rewrite that should happen here is: ' If(LeftTest(temp = left), temp, BitwiseOperator) Dim temp As New SynthesizedLocal(_currentMethodOrLambda, node.LeftOperand.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As New BoundLocal(node.Syntax, temp, True, temp.Type) AddPlaceholderReplacement(node.LeftOperandPlaceholder, New BoundAssignmentOperator(node.Syntax, tempAccess, VisitExpressionNode(node.LeftOperand), True, temp.Type)) Dim rewrittenTest = VisitExpressionNode(node.LeftTest) tempAccess = tempAccess.MakeRValue() UpdatePlaceholderReplacement(node.LeftOperandPlaceholder, tempAccess) Dim rewrittenBitwise = VisitExpressionNode(node.BitwiseOperator) RemovePlaceholderReplacement(node.LeftOperandPlaceholder) Return New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(temp), ImmutableArray(Of BoundExpression).Empty, MakeTernaryConditionalExpression(node.Syntax, rewrittenTest, tempAccess, rewrittenBitwise), temp.Type) End Function Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode ' Do not blow the stack due to a deep recursion on the left. Dim optimizeForConditionalBranch As Boolean = (node.OperatorKind And BinaryOperatorKind.OptimizableForConditionalBranch) <> 0 Dim optimizeChildForConditionalBranch As Boolean = optimizeForConditionalBranch Dim child As BoundExpression = GetLeftOperand(node, optimizeChildForConditionalBranch) If child.Kind <> BoundKind.BinaryOperator Then Return RewriteBinaryOperatorSimple(node, optimizeForConditionalBranch) End If Dim stack = ArrayBuilder(Of (Binary As BoundBinaryOperator, OptimizeForConditionalBranch As Boolean)).GetInstance() stack.Push((node, optimizeForConditionalBranch)) Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator) Do If optimizeChildForConditionalBranch Then Select Case (binary.OperatorKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse Exit Select Case Else optimizeChildForConditionalBranch = False End Select End If stack.Push((binary, optimizeChildForConditionalBranch)) child = GetLeftOperand(binary, optimizeChildForConditionalBranch) If child.Kind <> BoundKind.BinaryOperator Then Exit Do End If binary = DirectCast(child, BoundBinaryOperator) Loop Dim left = VisitExpressionNode(child) Do Dim tuple As (Binary As BoundBinaryOperator, OptimizeForConditionalBranch As Boolean) = stack.Pop() binary = tuple.Binary Dim right = VisitExpression(GetRightOperand(binary, tuple.OptimizeForConditionalBranch)) If (binary.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then left = FinishRewriteOfLiftedIntrinsicBinaryOperator(binary, left, right, tuple.OptimizeForConditionalBranch) Else left = TransformRewrittenBinaryOperator(binary.Update(binary.OperatorKind, left, right, binary.Checked, binary.ConstantValueOpt, Me.VisitType(binary.Type))) End If Loop While binary IsNot node Debug.Assert(stack.Count = 0) stack.Free() Return left End Function Private Shared Function GetLeftOperand(binary As BoundBinaryOperator, ByRef optimizeForConditionalBranch As Boolean) As BoundExpression If optimizeForConditionalBranch AndAlso (binary.OperatorKind And BinaryOperatorKind.OpMask) <> BinaryOperatorKind.OrElse Then Debug.Assert((binary.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.AndAlso) ' If left operand is evaluated to Null, three-valued Boolean logic dictates that the right operand of AndAlso ' should still be evaluated. So, we cannot simply snap the left operand to Boolean. optimizeForConditionalBranch = False End If Return binary.Left.GetMostEnclosedParenthesizedExpression() End Function Private Shared Function GetRightOperand(binary As BoundBinaryOperator, adjustIfOptimizableForConditionalBranch As Boolean) As BoundExpression If adjustIfOptimizableForConditionalBranch Then Return LocalRewriter.AdjustIfOptimizableForConditionalBranch(binary.Right, Nothing) Else Return binary.Right End If End Function Private Function RewriteBinaryOperatorSimple(node As BoundBinaryOperator, optimizeForConditionalBranch As Boolean) As BoundNode If (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then Return RewriteLiftedIntrinsicBinaryOperatorSimple(node, optimizeForConditionalBranch) End If Return TransformRewrittenBinaryOperator(DirectCast(MyBase.VisitBinaryOperator(node), BoundBinaryOperator)) End Function Private Function ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(operand As BoundExpression) As BoundExpression If operand.HasErrors Then Return operand End If ' See Semantics::AlterForMyGroup ' "goo.Form1 IS something" is translated to "goo.m_Form1 IS something" when ' Form1 is a property generated by MyGroupCollection ' Otherwise 'goo.Form1 IS Nothing" would be always false because 'goo.Form1' ' property call creates an instance on the fly. Select Case operand.Kind Case BoundKind.DirectCast ' Dig through possible DirectCast conversions Dim cast = DirectCast(operand, BoundDirectCast) Return cast.Update(ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(cast.Operand), cast.ConversionKind, cast.SuppressVirtualCalls, cast.ConstantValueOpt, cast.RelaxationLambdaOpt, cast.Type) Case BoundKind.Conversion ' Dig through possible conversion. For example, in context of an expression tree it is not changed to DirectCast conversion. Dim cast = DirectCast(operand, BoundConversion) Return cast.Update(ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(cast.Operand), cast.ConversionKind, cast.Checked, cast.ExplicitCastInCode, cast.ConstantValueOpt, cast.ExtendedInfoOpt, cast.Type) Case BoundKind.Call Dim boundCall = DirectCast(operand, BoundCall) If boundCall.Method.MethodKind = MethodKind.PropertyGet AndAlso boundCall.Method.AssociatedSymbol IsNot Nothing AndAlso boundCall.Method.AssociatedSymbol.IsMyGroupCollectionProperty Then Return New BoundFieldAccess(boundCall.Syntax, boundCall.ReceiverOpt, DirectCast(boundCall.Method.AssociatedSymbol, PropertySymbol).AssociatedField, isLValue:=False, type:=boundCall.Type) End If Case BoundKind.PropertyAccess ' Can get here when we are inside a lambda converted to an expression tree. Debug.Assert(_inExpressionLambda) Dim propertyAccess = DirectCast(operand, BoundPropertyAccess) If propertyAccess.AccessKind = PropertyAccessKind.Get AndAlso propertyAccess.PropertySymbol.IsMyGroupCollectionProperty Then Return New BoundFieldAccess(propertyAccess.Syntax, propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol.AssociatedField, isLValue:=False, type:=propertyAccess.Type) End If Case Else Debug.Assert(operand.Kind <> BoundKind.Parenthesized) ' Must have been removed by now. End Select Return operand End Function Private Function TransformRewrittenBinaryOperator(node As BoundBinaryOperator) As BoundExpression Dim opKind = node.OperatorKind Debug.Assert((opKind And BinaryOperatorKind.Lifted) = 0) Select Case (opKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.Is, BinaryOperatorKind.IsNot node = node.Update(node.OperatorKind, ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(node.Left), ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(node.Right), node.Checked, node.ConstantValueOpt, node.Type) If (node.Left.Type IsNot Nothing AndAlso node.Left.Type.IsNullableType) OrElse (node.Right.Type IsNot Nothing AndAlso node.Right.Type.IsNullableType) Then Return RewriteNullableIsOrIsNotOperator(node) End If Case BinaryOperatorKind.Concatenate ' Concat needs to be done before expr trees, so in LocalRewriter instead of VBSemanticsRewriter If node.Type.IsObjectType() Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject) Else Return RewriteConcatenateOperator(node) End If Case BinaryOperatorKind.Like If node.Left.Type.IsObjectType() Then Return RewriteLikeOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod) Else Return RewriteLikeOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod) End If Case BinaryOperatorKind.Equals Dim leftType = node.Left.Type ' NOTE: For some reason Dev11 seems to still ignore inside the expression tree the fact that the target ' type of the binary operator is Boolean and used Object op Object => Object helpers even in this case ' despite what is said in comments in RuntimeMembers CodeGenerator::GetHelperForObjRelOp ' TODO: Recheck If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.NotEquals Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.LessThanOrEqual Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.GreaterThanOrEqual Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.LessThan Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.GreaterThan Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.Add If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__AddDecimalDecimal) End If Case BinaryOperatorKind.Subtract If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__SubtractDecimalDecimal) End If Case BinaryOperatorKind.Multiply If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__MultiplyDecimalDecimal) End If Case BinaryOperatorKind.Modulo If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__RemainderDecimalDecimal) End If Case BinaryOperatorKind.Divide If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__DivideDecimalDecimal) End If Case BinaryOperatorKind.IntegerDivide If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject) End If Case BinaryOperatorKind.Power If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject) Else Return RewritePowOperator(node) End If Case BinaryOperatorKind.LeftShift If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject) End If Case BinaryOperatorKind.RightShift If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject) End If Case BinaryOperatorKind.OrElse, BinaryOperatorKind.AndAlso If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectShortCircuitOperator(node) End If Case BinaryOperatorKind.Xor If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject) End If Case BinaryOperatorKind.Or If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject) End If Case BinaryOperatorKind.And If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject) End If End Select Return node End Function Private Function RewriteDateComparisonOperator(node As BoundBinaryOperator) As BoundExpression If _inExpressionLambda Then Return node End If Debug.Assert(node.Left.Type.IsDateTimeType()) Debug.Assert(node.Right.Type.IsDateTimeType()) Debug.Assert(node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If left.Type.IsDateTimeType() AndAlso right.Type.IsDateTimeType() Then ' Rewrite as follows: ' DateTime.Compare(left, right) [Operator] 0 Const memberId As SpecialMember = SpecialMember.System_DateTime__CompareDateTimeDateTime Dim memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.SpecialType = SpecialType.System_Int32) Dim compare = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) result = New BoundBinaryOperator(node.Syntax, node.OperatorKind And BinaryOperatorKind.OpMask, compare, New BoundLiteral(node.Syntax, ConstantValue.Create(0I), memberSymbol.ReturnType), False, node.Type) End If End If Return result End Function Private Function RewriteDecimalComparisonOperator(node As BoundBinaryOperator) As BoundExpression If _inExpressionLambda Then Return node End If Debug.Assert(node.Left.Type.IsDecimalType()) Debug.Assert(node.Right.Type.IsDecimalType()) Debug.Assert(node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If left.Type.IsDecimalType() AndAlso right.Type.IsDecimalType() Then ' Rewrite as follows: ' Decimal.Compare(left, right) [Operator] 0 Const memberId As SpecialMember = SpecialMember.System_Decimal__CompareDecimalDecimal Dim memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.SpecialType = SpecialType.System_Int32) Dim compare = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) result = New BoundBinaryOperator(node.Syntax, node.OperatorKind And BinaryOperatorKind.OpMask, compare, New BoundLiteral(node.Syntax, ConstantValue.Create(0I), memberSymbol.ReturnType), False, node.Type) End If End If Return result End Function Private Function RewriteObjectShortCircuitOperator(node As BoundBinaryOperator) As BoundExpression Debug.Assert(node.Type.IsObjectType()) Dim result As BoundExpression = node Dim rewrittenLeft As BoundExpression = node.Left Dim rewrittenRight As BoundExpression = node.Right If rewrittenLeft.Type.IsObjectType() AndAlso rewrittenRight.Type.IsObjectType() Then ' This operator translates into: ' DirectCast(ToBoolean(left) OrElse/AndAlso ToBoolean(right), Object) ' Result is boxed Boolean. ' Dev10 uses complex routine in IL gen that emits the calls and also avoids boxing+calling the helper ' for result of nested OrElse/AndAlso. I will try to achieve the same effect by digging into DirectCast node ' on each side. Since, expressions are rewritten bottom-up, we don't need to look deeper than one level. ' Note, we may unwrap unnecessary DirectCast node that wasn't created by this function for nested OrElse/AndAlso, ' but this should not have any negative or observable side effect. Dim left As BoundExpression = rewrittenLeft Dim right As BoundExpression = rewrittenRight If left.Kind = BoundKind.DirectCast Then Dim cast = DirectCast(left, BoundDirectCast) If cast.Operand.Type.IsBooleanType() Then ' Just get rid of DirectCast node. left = cast.Operand End If End If If right.Kind = BoundKind.DirectCast Then Dim cast = DirectCast(right, BoundDirectCast) If cast.Operand.Type.IsBooleanType() Then ' Just get rid of DirectCast node. right = cast.Operand End If End If If left Is rewrittenLeft OrElse right Is rewrittenRight Then ' Need to call ToBoolean Const memberId As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.IsBooleanType()) Debug.Assert(memberSymbol.Parameters(0).Type.IsObjectType()) If left Is rewrittenLeft Then left = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left), Nothing, memberSymbol.ReturnType) End If If right Is rewrittenRight Then right = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(right), Nothing, memberSymbol.ReturnType) End If End If End If If left IsNot rewrittenLeft AndAlso right IsNot rewrittenRight Then ' left and right are successfully rewritten Debug.Assert(left.Type.IsBooleanType() AndAlso right.Type.IsBooleanType()) Dim op = New BoundBinaryOperator(node.Syntax, node.OperatorKind And BinaryOperatorKind.OpMask, left, right, False, left.Type) ' Box result of the operator result = New BoundDirectCast(node.Syntax, op, ConversionKind.WideningValue, node.Type, Nothing) End If Else Throw ExceptionUtilities.Unreachable End If Return result End Function Private Function RewritePowOperator(node As BoundBinaryOperator) As BoundExpression If _inExpressionLambda Then Return node End If Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If node.Type.IsDoubleType() AndAlso left.Type.IsDoubleType() AndAlso right.Type.IsDoubleType() Then ' Rewrite as follows: ' Math.Pow(left, right) Const memberId As WellKnownMember = WellKnownMember.System_Math__PowDoubleDouble Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.IsDoubleType()) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteDecimalBinaryOperator(node As BoundBinaryOperator, member As SpecialMember) As BoundExpression If _inExpressionLambda Then Return node End If Debug.Assert(node.Left.Type.IsDecimalType()) Debug.Assert(node.Right.Type.IsDecimalType()) Debug.Assert(node.Type.IsDecimalType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If left.Type.IsDecimalType() AndAlso right.Type.IsDecimalType() Then ' Call Decimal.member(left, right) Dim memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.IsDecimalType()) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteStringComparisonOperator(node As BoundBinaryOperator) As BoundExpression Debug.Assert(node.Left.Type.IsStringType()) Debug.Assert(node.Right.Type.IsStringType()) Debug.Assert(node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Dim compareText As Boolean = (node.OperatorKind And BinaryOperatorKind.CompareText) <> 0 ' Rewrite as follows: ' Operators.CompareString(left, right, compareText) [Operator] 0 ' Prefer embedded version of the member if present Dim embeddedOperatorsType As NamedTypeSymbol = Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators) Dim compareStringMember As WellKnownMember = If(embeddedOperatorsType.IsErrorType AndAlso TypeOf embeddedOperatorsType Is MissingMetadataTypeSymbol, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(compareStringMember), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, compareStringMember, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.SpecialType = SpecialType.System_Int32) Debug.Assert(memberSymbol.Parameters(2).Type.IsBooleanType()) Dim compare = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right, New BoundLiteral(node.Syntax, ConstantValue.Create(compareText), memberSymbol.Parameters(2).Type)), Nothing, memberSymbol.ReturnType) result = New BoundBinaryOperator(node.Syntax, (node.OperatorKind And BinaryOperatorKind.OpMask), compare, New BoundLiteral(node.Syntax, ConstantValue.Create(0I), memberSymbol.ReturnType), False, node.Type) End If Return result End Function Private Function RewriteObjectComparisonOperator(node As BoundBinaryOperator, member As WellKnownMember) As BoundExpression Debug.Assert(node.Left.Type.IsObjectType()) Debug.Assert(node.Right.Type.IsObjectType()) Debug.Assert(node.Type.IsObjectType() OrElse node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Dim compareText As Boolean = (node.OperatorKind And BinaryOperatorKind.CompareText) <> 0 ' Call member(left, right, compareText) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType Is node.Type OrElse Me._inExpressionLambda AndAlso memberSymbol.ReturnType.IsObjectType) Debug.Assert(memberSymbol.Parameters(2).Type.IsBooleanType()) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right, New BoundLiteral(node.Syntax, ConstantValue.Create(compareText), memberSymbol.Parameters(2).Type)), Nothing, memberSymbol.ReturnType, suppressObjectClone:=True) If Me._inExpressionLambda AndAlso memberSymbol.ReturnType.IsObjectType AndAlso node.Type.IsBooleanType Then result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), ConversionKind.NarrowingBoolean, node.Checked, False, node.Type) End If End If Return result End Function Private Function RewriteLikeOperator(node As BoundBinaryOperator, member As WellKnownMember) As BoundExpression Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Debug.Assert((node.Type.IsObjectType() AndAlso left.Type.IsObjectType() AndAlso right.Type.IsObjectType()) OrElse (node.Type.IsBooleanType() AndAlso left.Type.IsStringType() AndAlso right.Type.IsStringType())) Dim result As BoundExpression = node Dim compareText As Boolean = (node.OperatorKind And BinaryOperatorKind.CompareText) <> 0 ' Call member(left, right, if (compareText, 1, 0)) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType Is node.Type) Debug.Assert(memberSymbol.Parameters(2).Type.IsEnumType()) Debug.Assert(memberSymbol.Parameters(2).Type.GetEnumUnderlyingTypeOrSelf().SpecialType = SpecialType.System_Int32) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right, New BoundLiteral(node.Syntax, ConstantValue.Create(If(compareText, 1I, 0I)), memberSymbol.Parameters(2).Type)), Nothing, memberSymbol.ReturnType, suppressObjectClone:=True) End If Return result End Function Private Function RewriteObjectBinaryOperator(node As BoundBinaryOperator, member As WellKnownMember) As BoundExpression Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Debug.Assert(left.Type.IsObjectType()) Debug.Assert(right.Type.IsObjectType()) Debug.Assert(node.Type.IsObjectType()) Dim result As BoundExpression = node ' Call member(left, right) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType, suppressObjectClone:=True) End If Return result End Function Private Function RewriteLiftedIntrinsicBinaryOperatorSimple(node As BoundBinaryOperator, optimizeForConditionalBranch As Boolean) As BoundNode Dim left As BoundExpression = VisitExpressionNode(node.Left) Dim right As BoundExpression = VisitExpressionNode(GetRightOperand(node, optimizeForConditionalBranch)) Return FinishRewriteOfLiftedIntrinsicBinaryOperator(node, left, right, optimizeForConditionalBranch) End Function Private Function FinishRewriteOfLiftedIntrinsicBinaryOperator(node As BoundBinaryOperator, left As BoundExpression, right As BoundExpression, optimizeForConditionalBranch As Boolean) As BoundExpression Debug.Assert((node.OperatorKind And BinaryOperatorKind.Lifted) <> 0) Debug.Assert(Not optimizeForConditionalBranch OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.AndAlso) Dim leftHasValue = HasValue(left) Dim rightHasValue = HasValue(right) Dim leftHasNoValue = HasNoValue(left) Dim rightHasNoValue = HasNoValue(right) ' The goal of optimization is to eliminate the need to deal with instances of Nullable(Of Boolean) type as early as possible, ' and, as a result, simplify evaluation of built-in OrElse/AndAlso operators by eliminating the need to use three-valued Boolean logic. ' The optimization is possible because when an entire Boolean Expression is evaluated to Null, that has the same effect as if result ' of evaluation was False. However, we do want to preserve the original order of evaluation, according to language rules. If optimizeForConditionalBranch AndAlso node.Type.IsNullableOfBoolean() AndAlso left.Type.IsNullableOfBoolean() AndAlso right.Type.IsNullableOfBoolean() AndAlso (leftHasValue OrElse Not Me._inExpressionLambda OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse) Then Return RewriteAndOptimizeLiftedIntrinsicLogicalShortCircuitingOperator(node, left, right, leftHasNoValue, leftHasValue, rightHasNoValue, rightHasValue) End If If Me._inExpressionLambda Then Return node.Update(node.OperatorKind, left, right, node.Checked, node.ConstantValueOpt, node.Type) End If ' Check for trivial (no nulls, two nulls) Cases '== TWO NULLS If leftHasNoValue And rightHasNoValue Then ' return new R?() Return NullableNull(left, node.Type) End If '== NO NULLS If leftHasValue And rightHasValue Then ' return new R?(UnliftedOp(left, right)) Dim unliftedOp = ApplyUnliftedBinaryOp(node, NullableValueOrDefault(left), NullableValueOrDefault(right)) Return WrapInNullable(unliftedOp, node.Type) End If ' non-trivial cases rewrite differently when operands are boolean If node.Left.Type.IsNullableOfBoolean Then Select Case (node.OperatorKind And BinaryOperatorKind.OpMask) 'boolean context makes no difference for Xor. Case BinaryOperatorKind.And, BinaryOperatorKind.Or, BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse Return RewriteLiftedBooleanBinaryOperator(node, left, right, leftHasNoValue, rightHasNoValue, leftHasValue, rightHasValue) End Select End If '== ONE NULL ' result is null. No need to do the Op, even if checked. If leftHasNoValue Or rightHasNoValue Then 'Reducing to {[left | right] ; Null } Dim notNullOperand = If(leftHasNoValue, right, left) Dim nullOperand = NullableNull(If(leftHasNoValue, left, right), node.Type) Return MakeSequence(notNullOperand, nullOperand) End If ' At this point both operands are not known to be nulls, both may need to be evaluated ' We may also statically know if one is definitely not a null ' we cannot know, though, if whole operator yields null or not. If rightHasValue Then Dim whenNotNull As BoundExpression = Nothing Dim whenNull As BoundExpression = Nothing If IsConditionalAccess(left, whenNotNull, whenNull) Then Dim rightValue = NullableValueOrDefault(right) If (rightValue.IsConstant OrElse rightValue.Kind = BoundKind.Local OrElse rightValue.Kind = BoundKind.Parameter) AndAlso HasValue(whenNotNull) AndAlso HasNoValue(whenNull) Then Return UpdateConditionalAccess(left, WrapInNullable(ApplyUnliftedBinaryOp(node, NullableValueOrDefault(whenNotNull), rightValue), node.Type), NullableNull(whenNull, node.Type)) End If End If End If Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing Dim inits As ArrayBuilder(Of BoundExpression) = Nothing Dim leftHasValueExpr As BoundExpression = Nothing Dim rightHasValueExpr As BoundExpression = Nothing Dim processedLeft = ProcessNullableOperand(left, leftHasValueExpr, temps, inits, RightCantChangeLeftLocal(left, right), leftHasValue) ' left is done when right is running, so right cannot change if it is a local Dim processedRight = ProcessNullableOperand(right, rightHasValueExpr, temps, inits, doNotCaptureLocals:=True, operandHasValue:=rightHasValue) Dim value As BoundExpression = Nothing Dim operatorHasValue As BoundExpression = MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.And, leftHasValueExpr, rightHasValueExpr) Dim unliftedOpOnCaptured = ApplyUnliftedBinaryOp(node, processedLeft, processedRight) value = MakeTernaryConditionalExpression(node.Syntax, operatorHasValue, WrapInNullable(unliftedOpOnCaptured, node.Type), NullableNull(node.Syntax, node.Type)) ' if we used temps, arrange a sequence for them. If temps IsNot Nothing Then value = New BoundSequence(node.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, value, value.Type) End If Return value End Function ''' <summary> ''' The goal of optimization is to eliminate the need to deal with instances of Nullable(Of Boolean) type as early as possible, ''' and, as a result, simplify evaluation of built-in OrElse/AndAlso operators by eliminating the need to use three-valued Boolean logic. ''' The optimization is possible because when an entire Boolean Expression is evaluated to Null, that has the same effect as if result ''' of evaluation was False. However, we do want to preserve the original order of evaluation, according to language rules. ''' This method returns an expression that still has Nullable(Of Boolean) type, but that expression is much simpler and can be ''' further simplified by the consumer. ''' </summary> Private Function RewriteAndOptimizeLiftedIntrinsicLogicalShortCircuitingOperator(node As BoundBinaryOperator, left As BoundExpression, right As BoundExpression, leftHasNoValue As Boolean, leftHasValue As Boolean, rightHasNoValue As Boolean, rightHasValue As Boolean) As BoundExpression Debug.Assert(leftHasValue OrElse Not Me._inExpressionLambda OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse) Dim booleanResult As BoundExpression = Nothing If Not Me._inExpressionLambda Then If leftHasNoValue And rightHasNoValue Then ' return new R?(), the consumer will take care of optimizing it out if possible. Return NullableNull(left, node.Type) End If If (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse Then If leftHasNoValue Then ' There is nothing to evaluate on the left, the result is True only if Right is True Return right ElseIf rightHasNoValue Then ' There is nothing to evaluate on the right, the result is True only if Left is True Return left End If Else Debug.Assert((node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.AndAlso) If leftHasNoValue Then ' We can return False in this case. There is nothing to evaluate on the left, but we still need to evaluate the right booleanResult = EvaluateOperandAndReturnFalse(node, right, rightHasValue) ElseIf rightHasNoValue Then ' We can return False in this case. There is nothing to evaluate on the right, but we still need to evaluate the left booleanResult = EvaluateOperandAndReturnFalse(node, left, leftHasValue) ElseIf Not leftHasValue Then ' We cannot tell whether Left is Null or not. ' For [x AndAlso y] we can produce Boolean result as follows: ' ' tempX = x ' (Not tempX.HasValue OrElse tempX.GetValueOrDefault()) AndAlso ' (y.GetValueOrDefault() AndAlso tempX.HasValue) ' Dim leftTemp As SynthesizedLocal = Nothing Dim leftInit As BoundExpression = Nothing ' Right may be a method that takes Left byref - " local AndAlso TakesArgByref(local) " ' So in general we must capture Left even if it is a local. Dim capturedLeft = CaptureNullableIfNeeded(left, leftTemp, leftInit, RightCantChangeLeftLocal(left, right)) booleanResult = MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.AndAlso, MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.OrElse, New BoundUnaryOperator(node.Syntax, UnaryOperatorKind.Not, NullableHasValue(capturedLeft), False, node.Type.GetNullableUnderlyingType()), NullableValueOrDefault(capturedLeft)), MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.AndAlso, NullableValueOrDefault(right), NullableHasValue(capturedLeft))) ' if we used temp, put it in a sequence Debug.Assert((leftTemp Is Nothing) = (leftInit Is Nothing)) If leftTemp IsNot Nothing Then booleanResult = New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(leftTemp), ImmutableArray.Create(Of BoundExpression)(leftInit), booleanResult, booleanResult.Type) End If End If End If End If If booleanResult Is Nothing Then ' UnliftedOp(left.GetValueOrDefault(), right.GetValueOrDefault())) ' For AndAlso, this optimization is valid only when we know that left has value Debug.Assert(leftHasValue OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse) booleanResult = ApplyUnliftedBinaryOp(node, NullableValueOrDefault(left, leftHasValue), NullableValueOrDefault(right, rightHasValue)) End If ' return new R?(booleanResult), the consumer will take care of optimizing out the creation of this Nullable(Of Boolean) instance, if possible. Return WrapInNullable(booleanResult, node.Type) End Function Private Function EvaluateOperandAndReturnFalse(node As BoundBinaryOperator, operand As BoundExpression, operandHasValue As Boolean) As BoundExpression Debug.Assert(node.Type.IsNullableOfBoolean()) Debug.Assert(operand.Type.IsNullableOfBoolean()) Dim result = New BoundLiteral(node.Syntax, ConstantValue.False, node.Type.GetNullableUnderlyingType()) Return New BoundSequence(node.Syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(If(operandHasValue, NullableValueOrDefault(operand), operand)), result, result.Type) End Function Private Function NullableValueOrDefault(operand As BoundExpression, operandHasValue As Boolean) As BoundExpression Debug.Assert(operand.Type.IsNullableOfBoolean()) If Not Me._inExpressionLambda OrElse operandHasValue Then Return NullableValueOrDefault(operand) Else ' In expression tree this will be shown as Coalesce, which is preferred over a GetValueOrDefault call Return New BoundNullableIsTrueOperator(operand.Syntax, operand, operand.Type.GetNullableUnderlyingType()) End If End Function Private Function RewriteLiftedBooleanBinaryOperator(node As BoundBinaryOperator, left As BoundExpression, right As BoundExpression, leftHasNoValue As Boolean, rightHasNoValue As Boolean, leftHasValue As Boolean, rightHasValue As Boolean) As BoundExpression Debug.Assert(left.Type.IsNullableOfBoolean AndAlso right.Type.IsNullableOfBoolean AndAlso node.Type.IsNullableOfBoolean) Debug.Assert(Not (leftHasNoValue And rightHasNoValue)) Debug.Assert(Not (leftHasValue And rightHasValue)) Dim nullableOfBoolean = node.Type Dim booleanType = nullableOfBoolean.GetNullableUnderlyingType Dim op = node.OperatorKind And BinaryOperatorKind.OpMask Dim isOr As Boolean = (op = BinaryOperatorKind.OrElse) OrElse (op = BinaryOperatorKind.Or) '== ONE NULL If leftHasNoValue Or rightHasNoValue Then Dim notNullOperand As BoundExpression Dim nullOperand As BoundExpression Dim operandHasValue As Boolean If rightHasNoValue Then notNullOperand = left nullOperand = right operandHasValue = leftHasValue Else notNullOperand = right nullOperand = left operandHasValue = rightHasValue End If If operandHasValue Then ' reduce "Operand [And | AndAlso] NULL" ---> "If(Operand, NULL, False)". ' reduce "Operand [Or | OrElse] NULL" ---> "If(Operand, True, NULL)". Dim syntax = notNullOperand.Syntax Dim condition = NullableValueOrDefault(notNullOperand) Return MakeTernaryConditionalExpression(node.Syntax, condition, If(isOr, NullableTrue(syntax, nullableOfBoolean), NullableNull(nullOperand, nullableOfBoolean)), If(isOr, NullableNull(nullOperand, nullableOfBoolean), NullableFalse(syntax, nullableOfBoolean))) Else ' Dev10 uses AndAlso, but since operands are captured and hasValue is basically an access to a local ' so it makes sense to use And and avoid branching. ' reduce "Operand [And | AndAlso] NULL" --> "If(Operand.HasValue And Not Operand.GetValueOrDefault, Operand, NULL)". ' reduce "Operand [Or | OrElse] NULL" --> "If(Operand.GetValueOrDefault, Operand, NULL)". Dim temp As SynthesizedLocal = Nothing Dim tempInit As BoundExpression = Nothing ' we have only one operand to evaluate, do not capture locals. Dim capturedOperand = CaptureNullableIfNeeded(notNullOperand, temp, tempInit, doNotCaptureLocals:=True) Dim syntax = notNullOperand.Syntax Dim capturedOperandValue = NullableValueOrDefault(capturedOperand) Dim condition = If(isOr, NullableValueOrDefault(capturedOperand), MakeBooleanBinaryExpression(syntax, BinaryOperatorKind.And, NullableHasValue(capturedOperand), New BoundUnaryOperator(syntax, UnaryOperatorKind.Not, NullableValueOrDefault(capturedOperand), False, booleanType))) Dim result As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, condition, capturedOperand, NullableNull(nullOperand, nullableOfBoolean)) ' if we used a temp, arrange a sequence for it and its initialization If temp IsNot Nothing Then result = New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(temp), ImmutableArray.Create(tempInit), result, result.Type) End If Return result End If End If '== GENERAL CASE ' x And y is rewritten into: ' ' tempX = x ' [tempY = y] ' if not short-circuiting ' If (tempX.HasValue AndAlso Not tempX.GetValueOrDefault(), ' False?, ' result based on the left operand ' If ((tempY = y).HasValue, ' if short-circuiting, otherwise just "y.HasValue" ' If (tempY.GetValueOrDefault(), ' innermost If ' tempX, ' False?), ' Null?) ' ' Other operators rewrite using the same template, but constants and conditions are slightly different. ' Additionally we observe if HasValue is known statically or capturing may not be needed ' so some of the Ifs may be folded Dim IsShortCircuited = (op = BinaryOperatorKind.AndAlso Or op = BinaryOperatorKind.OrElse) Dim leftTemp As SynthesizedLocal = Nothing Dim leftInit As BoundExpression = Nothing Dim capturedLeft As BoundExpression = left ' Capture left operand if we do not know whether it has value (so that we could call HasValue and ValueOrDefault). If Not leftHasValue Then ' Right may be a method that takes Left byref - " local And TakesArgByref(local) " ' So in general we must capture Left even if it is a local. capturedLeft = CaptureNullableIfNeeded(left, leftTemp, leftInit, RightCantChangeLeftLocal(left, right)) End If Dim rightTemp As SynthesizedLocal = Nothing Dim rightInit As BoundExpression = Nothing Dim capturedRight As BoundExpression = right ' Capture right operand if we do not know whether it has value and we are not short-circuiting ' on optimized left operand (in which case right operand is used only once). ' When we are short circuiting, the right operand will be captured at the point where it is ' evaluated (notice "tempY = y" in the template). If Not rightHasValue AndAlso Not (leftHasValue AndAlso IsShortCircuited) Then ' when evaluating Right, left is already evaluated so we leave right local as-is. ' nothing can change it. capturedRight = CaptureNullableIfNeeded(capturedRight, rightTemp, rightInit, doNotCaptureLocals:=True) End If Dim OperandValue As BoundExpression = If(leftHasValue, capturedRight, capturedLeft) Dim ConstValue As BoundExpression = NullableOfBooleanValue(node.Syntax, isOr, nullableOfBoolean) ' innermost If Dim value As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, If(leftHasValue, NullableValueOrDefault(capturedLeft), NullableValueOrDefault(capturedRight)), If(isOr, ConstValue, OperandValue), If(isOr, OperandValue, ConstValue)) If Not leftHasValue Then If Not rightHasValue Then ' second nested if - when need to look at Right ' ' If (right.HasValue, ' nestedIf, ' Null) ' ' note that we use init of the Right as a target of HasValue when short-circuiting ' it will run only if we do not get result after looking at left ' ' NOTE: when not short circuiting we use captured right and evaluate init ' unconditionally before all the ifs. Dim conditionOperand As BoundExpression If IsShortCircuited Then ' use init if we have one. ' if Right is trivial local or const, may not have init, just use capturedRight conditionOperand = If(rightInit, capturedRight) ' make sure init can no longer be used rightInit = Nothing Else conditionOperand = capturedRight End If value = MakeTernaryConditionalExpression(node.Syntax, NullableHasValue(conditionOperand), value, NullableNull(node.Syntax, nullableOfBoolean)) End If If Not rightHasValue OrElse IsShortCircuited Then Dim capturedLeftValue As BoundExpression = NullableValueOrDefault(capturedLeft) Dim leftCapturedOrInit As BoundExpression If rightInit IsNot Nothing OrElse leftInit Is Nothing Then leftCapturedOrInit = capturedLeft Else leftCapturedOrInit = leftInit leftInit = Nothing End If ' Outermost If (do we know result after looking at first operand ?): ' ' Or - ' If (left.HasValue AndAlso left.Value, ... ' And - ' If (left.HasValue AndAlso Not left.Value, ... ' 'TODO: when not initializing right temp, can use And. (fewer branches) value = MakeTernaryConditionalExpression(node.Syntax, MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.AndAlso, NullableHasValue(leftCapturedOrInit), If(isOr, capturedLeftValue, New BoundUnaryOperator(node.Syntax, UnaryOperatorKind.Not, capturedLeftValue, False, booleanType))), NullableOfBooleanValue(node.Syntax, isOr, nullableOfBoolean), value) End If End If ' if we used temps, and did not embed inits, put them in a sequence If leftTemp IsNot Nothing OrElse rightTemp IsNot Nothing Then Dim temps = ArrayBuilder(Of LocalSymbol).GetInstance Dim inits = ArrayBuilder(Of BoundExpression).GetInstance If leftTemp IsNot Nothing Then temps.Add(leftTemp) If leftInit IsNot Nothing Then inits.Add(leftInit) End If End If If rightTemp IsNot Nothing Then temps.Add(rightTemp) If rightInit IsNot Nothing Then inits.Add(rightInit) End If End If value = New BoundSequence(node.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, value, value.Type) End If Return value End Function Private Function RewriteNullableIsOrIsNotOperator(node As BoundBinaryOperator) As BoundExpression Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Debug.Assert(left.IsNothingLiteral OrElse right.IsNothingLiteral) Debug.Assert(node.OperatorKind = BinaryOperatorKind.Is OrElse node.OperatorKind = BinaryOperatorKind.IsNot) If _inExpressionLambda Then Return node End If Return RewriteNullableIsOrIsNotOperator((node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Is, If(left.IsNothingLiteral, right, left), node.Type) End Function Private Function RewriteNullableIsOrIsNotOperator(isIs As Boolean, operand As BoundExpression, resultType As TypeSymbol) As BoundExpression Debug.Assert(resultType.IsBooleanType()) Debug.Assert(operand.Type.IsNullableType) If HasNoValue(operand) Then Return New BoundLiteral(operand.Syntax, If(isIs, ConstantValue.True, ConstantValue.False), resultType) ElseIf HasValue(operand) Then Return MakeSequence(operand, New BoundLiteral(operand.Syntax, If(isIs, ConstantValue.False, ConstantValue.True), resultType)) Else Dim whenNotNull As BoundExpression = Nothing Dim whenNull As BoundExpression = Nothing If IsConditionalAccess(operand, whenNotNull, whenNull) Then If HasNoValue(whenNull) Then Return UpdateConditionalAccess(operand, RewriteNullableIsOrIsNotOperator(isIs, whenNotNull, resultType), RewriteNullableIsOrIsNotOperator(isIs, whenNull, resultType)) End If End If Dim result As BoundExpression result = NullableHasValue(operand) If isIs Then result = New BoundUnaryOperator(result.Syntax, UnaryOperatorKind.Not, result, False, resultType) End If Return result End If End Function Private Function RewriteLiftedUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode ' ' Lifted user defined operator has structure as the following: ' ' | ' [implicit wrap] ' | ' CALL ' /\ ' [implicit unwrap] [implicit unwrap] ' | | ' LEFT RIGHT ' ' Implicit left/right unwrapping conversions if present are always L? -> L and R? -> R ' They are encoded as a disparity between CALL argument types and parameter types of the call symbol. ' ' Implicit wrapping conversion of the result, if present, is always T -> T? ' ' The rewrite is: ' If (LEFT.HasValue And RIGHT.HasValue, CALL(LEFT, RIGHT), Null) ' ' Note that the result of the operator is nullable type. Dim left = Me.VisitExpressionNode(node.Left) Dim right = Me.VisitExpressionNode(node.Right) Dim operatorCall = node.Call Dim resultType = operatorCall.Type Debug.Assert(resultType.IsNullableType()) Dim whenHasNoValue = NullableNull(node.Syntax, resultType) Debug.Assert(left.Type.IsNullableType() AndAlso right.Type.IsNullableType(), "left and right must be nullable") Dim leftHasNoValue As Boolean = HasNoValue(left) Dim rightHasNoValue As Boolean = HasNoValue(right) ' TWO NULLS If (leftHasNoValue And rightHasNoValue) Then Return whenHasNoValue End If ' ONE NULL If (leftHasNoValue Or rightHasNoValue) Then Return MakeSequence(If(leftHasNoValue, right, left), whenHasNoValue) End If Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing Dim inits As ArrayBuilder(Of BoundExpression) = Nothing ' PREPARE OPERANDS Dim leftHasValue As Boolean = HasValue(left) Dim rightHasValue As Boolean = HasValue(right) Dim leftCallInput As BoundExpression Dim rightCallInput As BoundExpression Dim condition As BoundExpression = Nothing If leftHasValue Then leftCallInput = NullableValueOrDefault(left) If rightHasValue Then rightCallInput = NullableValueOrDefault(right) Else leftCallInput = CaptureNullableIfNeeded(leftCallInput, temps, inits, doNotCaptureLocals:=True) rightCallInput = ProcessNullableOperand(right, condition, temps, inits, doNotCaptureLocals:=True) End If ElseIf rightHasValue Then leftCallInput = ProcessNullableOperand(left, condition, temps, inits, doNotCaptureLocals:=True) rightCallInput = NullableValueOrDefault(right) rightCallInput = CaptureNullableIfNeeded(rightCallInput, temps, inits, doNotCaptureLocals:=True) Else Dim leftHasValueExpression As BoundExpression = Nothing Dim rightHasValueExpression As BoundExpression = Nothing leftCallInput = ProcessNullableOperand(left, leftHasValueExpression, temps, inits, doNotCaptureLocals:=True) rightCallInput = ProcessNullableOperand(right, rightHasValueExpression, temps, inits, doNotCaptureLocals:=True) condition = MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.And, leftHasValueExpression, rightHasValueExpression) End If Debug.Assert(leftCallInput.Type.IsSameTypeIgnoringAll(operatorCall.Method.Parameters(0).Type), "operator must take either unwrapped values or not-nullable left directly") Debug.Assert(rightCallInput.Type.IsSameTypeIgnoringAll(operatorCall.Method.Parameters(1).Type), "operator must take either unwrapped values or not-nullable right directly") Dim whenHasValue As BoundExpression = operatorCall.Update(operatorCall.Method, Nothing, operatorCall.ReceiverOpt, ImmutableArray.Create(Of BoundExpression)(leftCallInput, rightCallInput), Nothing, operatorCall.ConstantValueOpt, isLValue:=operatorCall.IsLValue, suppressObjectClone:=operatorCall.SuppressObjectClone, type:=operatorCall.Method.ReturnType) If Not whenHasValue.Type.IsSameTypeIgnoringAll(resultType) Then whenHasValue = WrapInNullable(whenHasValue, resultType) End If Debug.Assert(whenHasValue.Type.IsSameTypeIgnoringAll(resultType), "result type must be same as resultType") ' RESULT If leftHasValue And rightHasValue Then Debug.Assert(temps Is Nothing AndAlso inits Is Nothing AndAlso condition Is Nothing) Return whenHasValue Else Dim result As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, condition, whenHasValue, whenHasNoValue) ' if we used a temp, arrange a sequence for it If temps IsNot Nothing Then result = New BoundSequence(node.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, result, result.Type) End If Return result End If End Function Private Function ApplyUnliftedBinaryOp(originalOperator As BoundBinaryOperator, left As BoundExpression, right As BoundExpression) As BoundExpression Debug.Assert(Not left.Type.IsNullableType) Debug.Assert(Not right.Type.IsNullableType) 'return UnliftedOP(left, right) Dim unliftedOpKind = originalOperator.OperatorKind And (Not BinaryOperatorKind.Lifted) Return MakeBinaryExpression(originalOperator.Syntax, unliftedOpKind, left, right, originalOperator.Checked, originalOperator.Type.GetNullableUnderlyingType) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class LocalRewriter Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode If _inExpressionLambda Then Return node.Update(node.OperatorKind, DirectCast(Visit(node.UnderlyingExpression), BoundExpression), node.Checked, node.Type) End If If (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then Return RewriteLiftedUserDefinedBinaryOperator(node) End If Return Visit(node.UnderlyingExpression) End Function Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode If _inExpressionLambda Then ' If we are inside expression lambda we need to rewrite it into just a bitwise operator call Dim placeholder As BoundRValuePlaceholder = node.LeftOperandPlaceholder Dim leftOperand As BoundExpression = node.LeftOperand If placeholder IsNot Nothing Then Debug.Assert(leftOperand IsNot Nothing) AddPlaceholderReplacement(placeholder, VisitExpression(leftOperand)) End If Dim rewritten = DirectCast(VisitExpression(node.BitwiseOperator), BoundUserDefinedBinaryOperator) If placeholder IsNot Nothing Then RemovePlaceholderReplacement(placeholder) End If ' NOTE: Everything but 'rewritten' will be discarded by ExpressionLambdaRewriter ' we keep the node only to make sure we can replace 'And' with 'AndAlso' ' and 'Or' with 'OrElse' when generating proper factory calls. Return node.Update(node.LeftOperand, node.LeftOperandPlaceholder, node.LeftTest, rewritten, node.Type) End If ' The rewrite that should happen here is: ' If(LeftTest(temp = left), temp, BitwiseOperator) Dim temp As New SynthesizedLocal(_currentMethodOrLambda, node.LeftOperand.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As New BoundLocal(node.Syntax, temp, True, temp.Type) AddPlaceholderReplacement(node.LeftOperandPlaceholder, New BoundAssignmentOperator(node.Syntax, tempAccess, VisitExpressionNode(node.LeftOperand), True, temp.Type)) Dim rewrittenTest = VisitExpressionNode(node.LeftTest) tempAccess = tempAccess.MakeRValue() UpdatePlaceholderReplacement(node.LeftOperandPlaceholder, tempAccess) Dim rewrittenBitwise = VisitExpressionNode(node.BitwiseOperator) RemovePlaceholderReplacement(node.LeftOperandPlaceholder) Return New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(temp), ImmutableArray(Of BoundExpression).Empty, MakeTernaryConditionalExpression(node.Syntax, rewrittenTest, tempAccess, rewrittenBitwise), temp.Type) End Function Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode ' Do not blow the stack due to a deep recursion on the left. Dim optimizeForConditionalBranch As Boolean = (node.OperatorKind And BinaryOperatorKind.OptimizableForConditionalBranch) <> 0 Dim optimizeChildForConditionalBranch As Boolean = optimizeForConditionalBranch Dim child As BoundExpression = GetLeftOperand(node, optimizeChildForConditionalBranch) If child.Kind <> BoundKind.BinaryOperator Then Return RewriteBinaryOperatorSimple(node, optimizeForConditionalBranch) End If Dim stack = ArrayBuilder(Of (Binary As BoundBinaryOperator, OptimizeForConditionalBranch As Boolean)).GetInstance() stack.Push((node, optimizeForConditionalBranch)) Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator) Do If optimizeChildForConditionalBranch Then Select Case (binary.OperatorKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse Exit Select Case Else optimizeChildForConditionalBranch = False End Select End If stack.Push((binary, optimizeChildForConditionalBranch)) child = GetLeftOperand(binary, optimizeChildForConditionalBranch) If child.Kind <> BoundKind.BinaryOperator Then Exit Do End If binary = DirectCast(child, BoundBinaryOperator) Loop Dim left = VisitExpressionNode(child) Do Dim tuple As (Binary As BoundBinaryOperator, OptimizeForConditionalBranch As Boolean) = stack.Pop() binary = tuple.Binary Dim right = VisitExpression(GetRightOperand(binary, tuple.OptimizeForConditionalBranch)) If (binary.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then left = FinishRewriteOfLiftedIntrinsicBinaryOperator(binary, left, right, tuple.OptimizeForConditionalBranch) Else left = TransformRewrittenBinaryOperator(binary.Update(binary.OperatorKind, left, right, binary.Checked, binary.ConstantValueOpt, Me.VisitType(binary.Type))) End If Loop While binary IsNot node Debug.Assert(stack.Count = 0) stack.Free() Return left End Function Private Shared Function GetLeftOperand(binary As BoundBinaryOperator, ByRef optimizeForConditionalBranch As Boolean) As BoundExpression If optimizeForConditionalBranch AndAlso (binary.OperatorKind And BinaryOperatorKind.OpMask) <> BinaryOperatorKind.OrElse Then Debug.Assert((binary.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.AndAlso) ' If left operand is evaluated to Null, three-valued Boolean logic dictates that the right operand of AndAlso ' should still be evaluated. So, we cannot simply snap the left operand to Boolean. optimizeForConditionalBranch = False End If Return binary.Left.GetMostEnclosedParenthesizedExpression() End Function Private Shared Function GetRightOperand(binary As BoundBinaryOperator, adjustIfOptimizableForConditionalBranch As Boolean) As BoundExpression If adjustIfOptimizableForConditionalBranch Then Return LocalRewriter.AdjustIfOptimizableForConditionalBranch(binary.Right, Nothing) Else Return binary.Right End If End Function Private Function RewriteBinaryOperatorSimple(node As BoundBinaryOperator, optimizeForConditionalBranch As Boolean) As BoundNode If (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then Return RewriteLiftedIntrinsicBinaryOperatorSimple(node, optimizeForConditionalBranch) End If Return TransformRewrittenBinaryOperator(DirectCast(MyBase.VisitBinaryOperator(node), BoundBinaryOperator)) End Function Private Function ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(operand As BoundExpression) As BoundExpression If operand.HasErrors Then Return operand End If ' See Semantics::AlterForMyGroup ' "goo.Form1 IS something" is translated to "goo.m_Form1 IS something" when ' Form1 is a property generated by MyGroupCollection ' Otherwise 'goo.Form1 IS Nothing" would be always false because 'goo.Form1' ' property call creates an instance on the fly. Select Case operand.Kind Case BoundKind.DirectCast ' Dig through possible DirectCast conversions Dim cast = DirectCast(operand, BoundDirectCast) Return cast.Update(ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(cast.Operand), cast.ConversionKind, cast.SuppressVirtualCalls, cast.ConstantValueOpt, cast.RelaxationLambdaOpt, cast.Type) Case BoundKind.Conversion ' Dig through possible conversion. For example, in context of an expression tree it is not changed to DirectCast conversion. Dim cast = DirectCast(operand, BoundConversion) Return cast.Update(ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(cast.Operand), cast.ConversionKind, cast.Checked, cast.ExplicitCastInCode, cast.ConstantValueOpt, cast.ExtendedInfoOpt, cast.Type) Case BoundKind.Call Dim boundCall = DirectCast(operand, BoundCall) If boundCall.Method.MethodKind = MethodKind.PropertyGet AndAlso boundCall.Method.AssociatedSymbol IsNot Nothing AndAlso boundCall.Method.AssociatedSymbol.IsMyGroupCollectionProperty Then Return New BoundFieldAccess(boundCall.Syntax, boundCall.ReceiverOpt, DirectCast(boundCall.Method.AssociatedSymbol, PropertySymbol).AssociatedField, isLValue:=False, type:=boundCall.Type) End If Case BoundKind.PropertyAccess ' Can get here when we are inside a lambda converted to an expression tree. Debug.Assert(_inExpressionLambda) Dim propertyAccess = DirectCast(operand, BoundPropertyAccess) If propertyAccess.AccessKind = PropertyAccessKind.Get AndAlso propertyAccess.PropertySymbol.IsMyGroupCollectionProperty Then Return New BoundFieldAccess(propertyAccess.Syntax, propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol.AssociatedField, isLValue:=False, type:=propertyAccess.Type) End If Case Else Debug.Assert(operand.Kind <> BoundKind.Parenthesized) ' Must have been removed by now. End Select Return operand End Function Private Function TransformRewrittenBinaryOperator(node As BoundBinaryOperator) As BoundExpression Dim opKind = node.OperatorKind Debug.Assert((opKind And BinaryOperatorKind.Lifted) = 0) Select Case (opKind And BinaryOperatorKind.OpMask) Case BinaryOperatorKind.Is, BinaryOperatorKind.IsNot node = node.Update(node.OperatorKind, ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(node.Left), ReplaceMyGroupCollectionPropertyGetWithUnderlyingField(node.Right), node.Checked, node.ConstantValueOpt, node.Type) If (node.Left.Type IsNot Nothing AndAlso node.Left.Type.IsNullableType) OrElse (node.Right.Type IsNot Nothing AndAlso node.Right.Type.IsNullableType) Then Return RewriteNullableIsOrIsNotOperator(node) End If Case BinaryOperatorKind.Concatenate ' Concat needs to be done before expr trees, so in LocalRewriter instead of VBSemanticsRewriter If node.Type.IsObjectType() Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject) Else Return RewriteConcatenateOperator(node) End If Case BinaryOperatorKind.Like If node.Left.Type.IsObjectType() Then Return RewriteLikeOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod) Else Return RewriteLikeOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod) End If Case BinaryOperatorKind.Equals Dim leftType = node.Left.Type ' NOTE: For some reason Dev11 seems to still ignore inside the expression tree the fact that the target ' type of the binary operator is Boolean and used Object op Object => Object helpers even in this case ' despite what is said in comments in RuntimeMembers CodeGenerator::GetHelperForObjRelOp ' TODO: Recheck If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.NotEquals Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.LessThanOrEqual Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.GreaterThanOrEqual Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.LessThan Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.GreaterThan Dim leftType = node.Left.Type ' NOTE: See comment above If node.Type.IsObjectType() OrElse Me._inExpressionLambda AndAlso leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean) ElseIf node.Type.IsBooleanType() Then If leftType.IsObjectType() Then Return RewriteObjectComparisonOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean) ElseIf leftType.IsStringType() Then Return RewriteStringComparisonOperator(node) ElseIf leftType.IsDecimalType() Then Return RewriteDecimalComparisonOperator(node) ElseIf leftType.IsDateTimeType() Then Return RewriteDateComparisonOperator(node) End If End If Case BinaryOperatorKind.Add If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__AddDecimalDecimal) End If Case BinaryOperatorKind.Subtract If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__SubtractDecimalDecimal) End If Case BinaryOperatorKind.Multiply If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__MultiplyDecimalDecimal) End If Case BinaryOperatorKind.Modulo If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__RemainderDecimalDecimal) End If Case BinaryOperatorKind.Divide If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject) ElseIf node.Type.IsDecimalType() Then Return RewriteDecimalBinaryOperator(node, SpecialMember.System_Decimal__DivideDecimalDecimal) End If Case BinaryOperatorKind.IntegerDivide If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject) End If Case BinaryOperatorKind.Power If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject) Else Return RewritePowOperator(node) End If Case BinaryOperatorKind.LeftShift If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject) End If Case BinaryOperatorKind.RightShift If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject) End If Case BinaryOperatorKind.OrElse, BinaryOperatorKind.AndAlso If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectShortCircuitOperator(node) End If Case BinaryOperatorKind.Xor If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject) End If Case BinaryOperatorKind.Or If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject) End If Case BinaryOperatorKind.And If node.Type.IsObjectType() AndAlso Not _inExpressionLambda Then Return RewriteObjectBinaryOperator(node, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject) End If End Select Return node End Function Private Function RewriteDateComparisonOperator(node As BoundBinaryOperator) As BoundExpression If _inExpressionLambda Then Return node End If Debug.Assert(node.Left.Type.IsDateTimeType()) Debug.Assert(node.Right.Type.IsDateTimeType()) Debug.Assert(node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If left.Type.IsDateTimeType() AndAlso right.Type.IsDateTimeType() Then ' Rewrite as follows: ' DateTime.Compare(left, right) [Operator] 0 Const memberId As SpecialMember = SpecialMember.System_DateTime__CompareDateTimeDateTime Dim memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.SpecialType = SpecialType.System_Int32) Dim compare = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) result = New BoundBinaryOperator(node.Syntax, node.OperatorKind And BinaryOperatorKind.OpMask, compare, New BoundLiteral(node.Syntax, ConstantValue.Create(0I), memberSymbol.ReturnType), False, node.Type) End If End If Return result End Function Private Function RewriteDecimalComparisonOperator(node As BoundBinaryOperator) As BoundExpression If _inExpressionLambda Then Return node End If Debug.Assert(node.Left.Type.IsDecimalType()) Debug.Assert(node.Right.Type.IsDecimalType()) Debug.Assert(node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If left.Type.IsDecimalType() AndAlso right.Type.IsDecimalType() Then ' Rewrite as follows: ' Decimal.Compare(left, right) [Operator] 0 Const memberId As SpecialMember = SpecialMember.System_Decimal__CompareDecimalDecimal Dim memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.SpecialType = SpecialType.System_Int32) Dim compare = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) result = New BoundBinaryOperator(node.Syntax, node.OperatorKind And BinaryOperatorKind.OpMask, compare, New BoundLiteral(node.Syntax, ConstantValue.Create(0I), memberSymbol.ReturnType), False, node.Type) End If End If Return result End Function Private Function RewriteObjectShortCircuitOperator(node As BoundBinaryOperator) As BoundExpression Debug.Assert(node.Type.IsObjectType()) Dim result As BoundExpression = node Dim rewrittenLeft As BoundExpression = node.Left Dim rewrittenRight As BoundExpression = node.Right If rewrittenLeft.Type.IsObjectType() AndAlso rewrittenRight.Type.IsObjectType() Then ' This operator translates into: ' DirectCast(ToBoolean(left) OrElse/AndAlso ToBoolean(right), Object) ' Result is boxed Boolean. ' Dev10 uses complex routine in IL gen that emits the calls and also avoids boxing+calling the helper ' for result of nested OrElse/AndAlso. I will try to achieve the same effect by digging into DirectCast node ' on each side. Since, expressions are rewritten bottom-up, we don't need to look deeper than one level. ' Note, we may unwrap unnecessary DirectCast node that wasn't created by this function for nested OrElse/AndAlso, ' but this should not have any negative or observable side effect. Dim left As BoundExpression = rewrittenLeft Dim right As BoundExpression = rewrittenRight If left.Kind = BoundKind.DirectCast Then Dim cast = DirectCast(left, BoundDirectCast) If cast.Operand.Type.IsBooleanType() Then ' Just get rid of DirectCast node. left = cast.Operand End If End If If right.Kind = BoundKind.DirectCast Then Dim cast = DirectCast(right, BoundDirectCast) If cast.Operand.Type.IsBooleanType() Then ' Just get rid of DirectCast node. right = cast.Operand End If End If If left Is rewrittenLeft OrElse right Is rewrittenRight Then ' Need to call ToBoolean Const memberId As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.IsBooleanType()) Debug.Assert(memberSymbol.Parameters(0).Type.IsObjectType()) If left Is rewrittenLeft Then left = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left), Nothing, memberSymbol.ReturnType) End If If right Is rewrittenRight Then right = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(right), Nothing, memberSymbol.ReturnType) End If End If End If If left IsNot rewrittenLeft AndAlso right IsNot rewrittenRight Then ' left and right are successfully rewritten Debug.Assert(left.Type.IsBooleanType() AndAlso right.Type.IsBooleanType()) Dim op = New BoundBinaryOperator(node.Syntax, node.OperatorKind And BinaryOperatorKind.OpMask, left, right, False, left.Type) ' Box result of the operator result = New BoundDirectCast(node.Syntax, op, ConversionKind.WideningValue, node.Type, Nothing) End If Else Throw ExceptionUtilities.Unreachable End If Return result End Function Private Function RewritePowOperator(node As BoundBinaryOperator) As BoundExpression If _inExpressionLambda Then Return node End If Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If node.Type.IsDoubleType() AndAlso left.Type.IsDoubleType() AndAlso right.Type.IsDoubleType() Then ' Rewrite as follows: ' Math.Pow(left, right) Const memberId As WellKnownMember = WellKnownMember.System_Math__PowDoubleDouble Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.IsDoubleType()) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteDecimalBinaryOperator(node As BoundBinaryOperator, member As SpecialMember) As BoundExpression If _inExpressionLambda Then Return node End If Debug.Assert(node.Left.Type.IsDecimalType()) Debug.Assert(node.Right.Type.IsDecimalType()) Debug.Assert(node.Type.IsDecimalType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right If left.Type.IsDecimalType() AndAlso right.Type.IsDecimalType() Then ' Call Decimal.member(left, right) Dim memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.IsDecimalType()) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteStringComparisonOperator(node As BoundBinaryOperator) As BoundExpression Debug.Assert(node.Left.Type.IsStringType()) Debug.Assert(node.Right.Type.IsStringType()) Debug.Assert(node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Dim compareText As Boolean = (node.OperatorKind And BinaryOperatorKind.CompareText) <> 0 ' Rewrite as follows: ' Operators.CompareString(left, right, compareText) [Operator] 0 ' Prefer embedded version of the member if present Dim embeddedOperatorsType As NamedTypeSymbol = Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators) Dim compareStringMember As WellKnownMember = If(embeddedOperatorsType.IsErrorType AndAlso TypeOf embeddedOperatorsType Is MissingMetadataTypeSymbol, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(compareStringMember), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, compareStringMember, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType.SpecialType = SpecialType.System_Int32) Debug.Assert(memberSymbol.Parameters(2).Type.IsBooleanType()) Dim compare = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right, New BoundLiteral(node.Syntax, ConstantValue.Create(compareText), memberSymbol.Parameters(2).Type)), Nothing, memberSymbol.ReturnType) result = New BoundBinaryOperator(node.Syntax, (node.OperatorKind And BinaryOperatorKind.OpMask), compare, New BoundLiteral(node.Syntax, ConstantValue.Create(0I), memberSymbol.ReturnType), False, node.Type) End If Return result End Function Private Function RewriteObjectComparisonOperator(node As BoundBinaryOperator, member As WellKnownMember) As BoundExpression Debug.Assert(node.Left.Type.IsObjectType()) Debug.Assert(node.Right.Type.IsObjectType()) Debug.Assert(node.Type.IsObjectType() OrElse node.Type.IsBooleanType()) Dim result As BoundExpression = node Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Dim compareText As Boolean = (node.OperatorKind And BinaryOperatorKind.CompareText) <> 0 ' Call member(left, right, compareText) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType Is node.Type OrElse Me._inExpressionLambda AndAlso memberSymbol.ReturnType.IsObjectType) Debug.Assert(memberSymbol.Parameters(2).Type.IsBooleanType()) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right, New BoundLiteral(node.Syntax, ConstantValue.Create(compareText), memberSymbol.Parameters(2).Type)), Nothing, memberSymbol.ReturnType, suppressObjectClone:=True) If Me._inExpressionLambda AndAlso memberSymbol.ReturnType.IsObjectType AndAlso node.Type.IsBooleanType Then result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), ConversionKind.NarrowingBoolean, node.Checked, False, node.Type) End If End If Return result End Function Private Function RewriteLikeOperator(node As BoundBinaryOperator, member As WellKnownMember) As BoundExpression Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Debug.Assert((node.Type.IsObjectType() AndAlso left.Type.IsObjectType() AndAlso right.Type.IsObjectType()) OrElse (node.Type.IsBooleanType() AndAlso left.Type.IsStringType() AndAlso right.Type.IsStringType())) Dim result As BoundExpression = node Dim compareText As Boolean = (node.OperatorKind And BinaryOperatorKind.CompareText) <> 0 ' Call member(left, right, if (compareText, 1, 0)) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Debug.Assert(memberSymbol.ReturnType Is node.Type) Debug.Assert(memberSymbol.Parameters(2).Type.IsEnumType()) Debug.Assert(memberSymbol.Parameters(2).Type.GetEnumUnderlyingTypeOrSelf().SpecialType = SpecialType.System_Int32) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right, New BoundLiteral(node.Syntax, ConstantValue.Create(If(compareText, 1I, 0I)), memberSymbol.Parameters(2).Type)), Nothing, memberSymbol.ReturnType, suppressObjectClone:=True) End If Return result End Function Private Function RewriteObjectBinaryOperator(node As BoundBinaryOperator, member As WellKnownMember) As BoundExpression Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Debug.Assert(left.Type.IsObjectType()) Debug.Assert(right.Type.IsObjectType()) Debug.Assert(node.Type.IsObjectType()) Dim result As BoundExpression = node ' Call member(left, right) Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(left, right), Nothing, memberSymbol.ReturnType, suppressObjectClone:=True) End If Return result End Function Private Function RewriteLiftedIntrinsicBinaryOperatorSimple(node As BoundBinaryOperator, optimizeForConditionalBranch As Boolean) As BoundNode Dim left As BoundExpression = VisitExpressionNode(node.Left) Dim right As BoundExpression = VisitExpressionNode(GetRightOperand(node, optimizeForConditionalBranch)) Return FinishRewriteOfLiftedIntrinsicBinaryOperator(node, left, right, optimizeForConditionalBranch) End Function Private Function FinishRewriteOfLiftedIntrinsicBinaryOperator(node As BoundBinaryOperator, left As BoundExpression, right As BoundExpression, optimizeForConditionalBranch As Boolean) As BoundExpression Debug.Assert((node.OperatorKind And BinaryOperatorKind.Lifted) <> 0) Debug.Assert(Not optimizeForConditionalBranch OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.AndAlso) Dim leftHasValue = HasValue(left) Dim rightHasValue = HasValue(right) Dim leftHasNoValue = HasNoValue(left) Dim rightHasNoValue = HasNoValue(right) ' The goal of optimization is to eliminate the need to deal with instances of Nullable(Of Boolean) type as early as possible, ' and, as a result, simplify evaluation of built-in OrElse/AndAlso operators by eliminating the need to use three-valued Boolean logic. ' The optimization is possible because when an entire Boolean Expression is evaluated to Null, that has the same effect as if result ' of evaluation was False. However, we do want to preserve the original order of evaluation, according to language rules. If optimizeForConditionalBranch AndAlso node.Type.IsNullableOfBoolean() AndAlso left.Type.IsNullableOfBoolean() AndAlso right.Type.IsNullableOfBoolean() AndAlso (leftHasValue OrElse Not Me._inExpressionLambda OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse) Then Return RewriteAndOptimizeLiftedIntrinsicLogicalShortCircuitingOperator(node, left, right, leftHasNoValue, leftHasValue, rightHasNoValue, rightHasValue) End If If Me._inExpressionLambda Then Return node.Update(node.OperatorKind, left, right, node.Checked, node.ConstantValueOpt, node.Type) End If ' Check for trivial (no nulls, two nulls) Cases '== TWO NULLS If leftHasNoValue And rightHasNoValue Then ' return new R?() Return NullableNull(left, node.Type) End If '== NO NULLS If leftHasValue And rightHasValue Then ' return new R?(UnliftedOp(left, right)) Dim unliftedOp = ApplyUnliftedBinaryOp(node, NullableValueOrDefault(left), NullableValueOrDefault(right)) Return WrapInNullable(unliftedOp, node.Type) End If ' non-trivial cases rewrite differently when operands are boolean If node.Left.Type.IsNullableOfBoolean Then Select Case (node.OperatorKind And BinaryOperatorKind.OpMask) 'boolean context makes no difference for Xor. Case BinaryOperatorKind.And, BinaryOperatorKind.Or, BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse Return RewriteLiftedBooleanBinaryOperator(node, left, right, leftHasNoValue, rightHasNoValue, leftHasValue, rightHasValue) End Select End If '== ONE NULL ' result is null. No need to do the Op, even if checked. If leftHasNoValue Or rightHasNoValue Then 'Reducing to {[left | right] ; Null } Dim notNullOperand = If(leftHasNoValue, right, left) Dim nullOperand = NullableNull(If(leftHasNoValue, left, right), node.Type) Return MakeSequence(notNullOperand, nullOperand) End If ' At this point both operands are not known to be nulls, both may need to be evaluated ' We may also statically know if one is definitely not a null ' we cannot know, though, if whole operator yields null or not. If rightHasValue Then Dim whenNotNull As BoundExpression = Nothing Dim whenNull As BoundExpression = Nothing If IsConditionalAccess(left, whenNotNull, whenNull) Then Dim rightValue = NullableValueOrDefault(right) If (rightValue.IsConstant OrElse rightValue.Kind = BoundKind.Local OrElse rightValue.Kind = BoundKind.Parameter) AndAlso HasValue(whenNotNull) AndAlso HasNoValue(whenNull) Then Return UpdateConditionalAccess(left, WrapInNullable(ApplyUnliftedBinaryOp(node, NullableValueOrDefault(whenNotNull), rightValue), node.Type), NullableNull(whenNull, node.Type)) End If End If End If Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing Dim inits As ArrayBuilder(Of BoundExpression) = Nothing Dim leftHasValueExpr As BoundExpression = Nothing Dim rightHasValueExpr As BoundExpression = Nothing Dim processedLeft = ProcessNullableOperand(left, leftHasValueExpr, temps, inits, RightCantChangeLeftLocal(left, right), leftHasValue) ' left is done when right is running, so right cannot change if it is a local Dim processedRight = ProcessNullableOperand(right, rightHasValueExpr, temps, inits, doNotCaptureLocals:=True, operandHasValue:=rightHasValue) Dim value As BoundExpression = Nothing Dim operatorHasValue As BoundExpression = MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.And, leftHasValueExpr, rightHasValueExpr) Dim unliftedOpOnCaptured = ApplyUnliftedBinaryOp(node, processedLeft, processedRight) value = MakeTernaryConditionalExpression(node.Syntax, operatorHasValue, WrapInNullable(unliftedOpOnCaptured, node.Type), NullableNull(node.Syntax, node.Type)) ' if we used temps, arrange a sequence for them. If temps IsNot Nothing Then value = New BoundSequence(node.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, value, value.Type) End If Return value End Function ''' <summary> ''' The goal of optimization is to eliminate the need to deal with instances of Nullable(Of Boolean) type as early as possible, ''' and, as a result, simplify evaluation of built-in OrElse/AndAlso operators by eliminating the need to use three-valued Boolean logic. ''' The optimization is possible because when an entire Boolean Expression is evaluated to Null, that has the same effect as if result ''' of evaluation was False. However, we do want to preserve the original order of evaluation, according to language rules. ''' This method returns an expression that still has Nullable(Of Boolean) type, but that expression is much simpler and can be ''' further simplified by the consumer. ''' </summary> Private Function RewriteAndOptimizeLiftedIntrinsicLogicalShortCircuitingOperator(node As BoundBinaryOperator, left As BoundExpression, right As BoundExpression, leftHasNoValue As Boolean, leftHasValue As Boolean, rightHasNoValue As Boolean, rightHasValue As Boolean) As BoundExpression Debug.Assert(leftHasValue OrElse Not Me._inExpressionLambda OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse) Dim booleanResult As BoundExpression = Nothing If Not Me._inExpressionLambda Then If leftHasNoValue And rightHasNoValue Then ' return new R?(), the consumer will take care of optimizing it out if possible. Return NullableNull(left, node.Type) End If If (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse Then If leftHasNoValue Then ' There is nothing to evaluate on the left, the result is True only if Right is True Return right ElseIf rightHasNoValue Then ' There is nothing to evaluate on the right, the result is True only if Left is True Return left End If Else Debug.Assert((node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.AndAlso) If leftHasNoValue Then ' We can return False in this case. There is nothing to evaluate on the left, but we still need to evaluate the right booleanResult = EvaluateOperandAndReturnFalse(node, right, rightHasValue) ElseIf rightHasNoValue Then ' We can return False in this case. There is nothing to evaluate on the right, but we still need to evaluate the left booleanResult = EvaluateOperandAndReturnFalse(node, left, leftHasValue) ElseIf Not leftHasValue Then ' We cannot tell whether Left is Null or not. ' For [x AndAlso y] we can produce Boolean result as follows: ' ' tempX = x ' (Not tempX.HasValue OrElse tempX.GetValueOrDefault()) AndAlso ' (y.GetValueOrDefault() AndAlso tempX.HasValue) ' Dim leftTemp As SynthesizedLocal = Nothing Dim leftInit As BoundExpression = Nothing ' Right may be a method that takes Left byref - " local AndAlso TakesArgByref(local) " ' So in general we must capture Left even if it is a local. Dim capturedLeft = CaptureNullableIfNeeded(left, leftTemp, leftInit, RightCantChangeLeftLocal(left, right)) booleanResult = MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.AndAlso, MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.OrElse, New BoundUnaryOperator(node.Syntax, UnaryOperatorKind.Not, NullableHasValue(capturedLeft), False, node.Type.GetNullableUnderlyingType()), NullableValueOrDefault(capturedLeft)), MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.AndAlso, NullableValueOrDefault(right), NullableHasValue(capturedLeft))) ' if we used temp, put it in a sequence Debug.Assert((leftTemp Is Nothing) = (leftInit Is Nothing)) If leftTemp IsNot Nothing Then booleanResult = New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(leftTemp), ImmutableArray.Create(Of BoundExpression)(leftInit), booleanResult, booleanResult.Type) End If End If End If End If If booleanResult Is Nothing Then ' UnliftedOp(left.GetValueOrDefault(), right.GetValueOrDefault())) ' For AndAlso, this optimization is valid only when we know that left has value Debug.Assert(leftHasValue OrElse (node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.OrElse) booleanResult = ApplyUnliftedBinaryOp(node, NullableValueOrDefault(left, leftHasValue), NullableValueOrDefault(right, rightHasValue)) End If ' return new R?(booleanResult), the consumer will take care of optimizing out the creation of this Nullable(Of Boolean) instance, if possible. Return WrapInNullable(booleanResult, node.Type) End Function Private Function EvaluateOperandAndReturnFalse(node As BoundBinaryOperator, operand As BoundExpression, operandHasValue As Boolean) As BoundExpression Debug.Assert(node.Type.IsNullableOfBoolean()) Debug.Assert(operand.Type.IsNullableOfBoolean()) Dim result = New BoundLiteral(node.Syntax, ConstantValue.False, node.Type.GetNullableUnderlyingType()) Return New BoundSequence(node.Syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(If(operandHasValue, NullableValueOrDefault(operand), operand)), result, result.Type) End Function Private Function NullableValueOrDefault(operand As BoundExpression, operandHasValue As Boolean) As BoundExpression Debug.Assert(operand.Type.IsNullableOfBoolean()) If Not Me._inExpressionLambda OrElse operandHasValue Then Return NullableValueOrDefault(operand) Else ' In expression tree this will be shown as Coalesce, which is preferred over a GetValueOrDefault call Return New BoundNullableIsTrueOperator(operand.Syntax, operand, operand.Type.GetNullableUnderlyingType()) End If End Function Private Function RewriteLiftedBooleanBinaryOperator(node As BoundBinaryOperator, left As BoundExpression, right As BoundExpression, leftHasNoValue As Boolean, rightHasNoValue As Boolean, leftHasValue As Boolean, rightHasValue As Boolean) As BoundExpression Debug.Assert(left.Type.IsNullableOfBoolean AndAlso right.Type.IsNullableOfBoolean AndAlso node.Type.IsNullableOfBoolean) Debug.Assert(Not (leftHasNoValue And rightHasNoValue)) Debug.Assert(Not (leftHasValue And rightHasValue)) Dim nullableOfBoolean = node.Type Dim booleanType = nullableOfBoolean.GetNullableUnderlyingType Dim op = node.OperatorKind And BinaryOperatorKind.OpMask Dim isOr As Boolean = (op = BinaryOperatorKind.OrElse) OrElse (op = BinaryOperatorKind.Or) '== ONE NULL If leftHasNoValue Or rightHasNoValue Then Dim notNullOperand As BoundExpression Dim nullOperand As BoundExpression Dim operandHasValue As Boolean If rightHasNoValue Then notNullOperand = left nullOperand = right operandHasValue = leftHasValue Else notNullOperand = right nullOperand = left operandHasValue = rightHasValue End If If operandHasValue Then ' reduce "Operand [And | AndAlso] NULL" ---> "If(Operand, NULL, False)". ' reduce "Operand [Or | OrElse] NULL" ---> "If(Operand, True, NULL)". Dim syntax = notNullOperand.Syntax Dim condition = NullableValueOrDefault(notNullOperand) Return MakeTernaryConditionalExpression(node.Syntax, condition, If(isOr, NullableTrue(syntax, nullableOfBoolean), NullableNull(nullOperand, nullableOfBoolean)), If(isOr, NullableNull(nullOperand, nullableOfBoolean), NullableFalse(syntax, nullableOfBoolean))) Else ' Dev10 uses AndAlso, but since operands are captured and hasValue is basically an access to a local ' so it makes sense to use And and avoid branching. ' reduce "Operand [And | AndAlso] NULL" --> "If(Operand.HasValue And Not Operand.GetValueOrDefault, Operand, NULL)". ' reduce "Operand [Or | OrElse] NULL" --> "If(Operand.GetValueOrDefault, Operand, NULL)". Dim temp As SynthesizedLocal = Nothing Dim tempInit As BoundExpression = Nothing ' we have only one operand to evaluate, do not capture locals. Dim capturedOperand = CaptureNullableIfNeeded(notNullOperand, temp, tempInit, doNotCaptureLocals:=True) Dim syntax = notNullOperand.Syntax Dim capturedOperandValue = NullableValueOrDefault(capturedOperand) Dim condition = If(isOr, NullableValueOrDefault(capturedOperand), MakeBooleanBinaryExpression(syntax, BinaryOperatorKind.And, NullableHasValue(capturedOperand), New BoundUnaryOperator(syntax, UnaryOperatorKind.Not, NullableValueOrDefault(capturedOperand), False, booleanType))) Dim result As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, condition, capturedOperand, NullableNull(nullOperand, nullableOfBoolean)) ' if we used a temp, arrange a sequence for it and its initialization If temp IsNot Nothing Then result = New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(temp), ImmutableArray.Create(tempInit), result, result.Type) End If Return result End If End If '== GENERAL CASE ' x And y is rewritten into: ' ' tempX = x ' [tempY = y] ' if not short-circuiting ' If (tempX.HasValue AndAlso Not tempX.GetValueOrDefault(), ' False?, ' result based on the left operand ' If ((tempY = y).HasValue, ' if short-circuiting, otherwise just "y.HasValue" ' If (tempY.GetValueOrDefault(), ' innermost If ' tempX, ' False?), ' Null?) ' ' Other operators rewrite using the same template, but constants and conditions are slightly different. ' Additionally we observe if HasValue is known statically or capturing may not be needed ' so some of the Ifs may be folded Dim IsShortCircuited = (op = BinaryOperatorKind.AndAlso Or op = BinaryOperatorKind.OrElse) Dim leftTemp As SynthesizedLocal = Nothing Dim leftInit As BoundExpression = Nothing Dim capturedLeft As BoundExpression = left ' Capture left operand if we do not know whether it has value (so that we could call HasValue and ValueOrDefault). If Not leftHasValue Then ' Right may be a method that takes Left byref - " local And TakesArgByref(local) " ' So in general we must capture Left even if it is a local. capturedLeft = CaptureNullableIfNeeded(left, leftTemp, leftInit, RightCantChangeLeftLocal(left, right)) End If Dim rightTemp As SynthesizedLocal = Nothing Dim rightInit As BoundExpression = Nothing Dim capturedRight As BoundExpression = right ' Capture right operand if we do not know whether it has value and we are not short-circuiting ' on optimized left operand (in which case right operand is used only once). ' When we are short circuiting, the right operand will be captured at the point where it is ' evaluated (notice "tempY = y" in the template). If Not rightHasValue AndAlso Not (leftHasValue AndAlso IsShortCircuited) Then ' when evaluating Right, left is already evaluated so we leave right local as-is. ' nothing can change it. capturedRight = CaptureNullableIfNeeded(capturedRight, rightTemp, rightInit, doNotCaptureLocals:=True) End If Dim OperandValue As BoundExpression = If(leftHasValue, capturedRight, capturedLeft) Dim ConstValue As BoundExpression = NullableOfBooleanValue(node.Syntax, isOr, nullableOfBoolean) ' innermost If Dim value As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, If(leftHasValue, NullableValueOrDefault(capturedLeft), NullableValueOrDefault(capturedRight)), If(isOr, ConstValue, OperandValue), If(isOr, OperandValue, ConstValue)) If Not leftHasValue Then If Not rightHasValue Then ' second nested if - when need to look at Right ' ' If (right.HasValue, ' nestedIf, ' Null) ' ' note that we use init of the Right as a target of HasValue when short-circuiting ' it will run only if we do not get result after looking at left ' ' NOTE: when not short circuiting we use captured right and evaluate init ' unconditionally before all the ifs. Dim conditionOperand As BoundExpression If IsShortCircuited Then ' use init if we have one. ' if Right is trivial local or const, may not have init, just use capturedRight conditionOperand = If(rightInit, capturedRight) ' make sure init can no longer be used rightInit = Nothing Else conditionOperand = capturedRight End If value = MakeTernaryConditionalExpression(node.Syntax, NullableHasValue(conditionOperand), value, NullableNull(node.Syntax, nullableOfBoolean)) End If If Not rightHasValue OrElse IsShortCircuited Then Dim capturedLeftValue As BoundExpression = NullableValueOrDefault(capturedLeft) Dim leftCapturedOrInit As BoundExpression If rightInit IsNot Nothing OrElse leftInit Is Nothing Then leftCapturedOrInit = capturedLeft Else leftCapturedOrInit = leftInit leftInit = Nothing End If ' Outermost If (do we know result after looking at first operand ?): ' ' Or - ' If (left.HasValue AndAlso left.Value, ... ' And - ' If (left.HasValue AndAlso Not left.Value, ... ' 'TODO: when not initializing right temp, can use And. (fewer branches) value = MakeTernaryConditionalExpression(node.Syntax, MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.AndAlso, NullableHasValue(leftCapturedOrInit), If(isOr, capturedLeftValue, New BoundUnaryOperator(node.Syntax, UnaryOperatorKind.Not, capturedLeftValue, False, booleanType))), NullableOfBooleanValue(node.Syntax, isOr, nullableOfBoolean), value) End If End If ' if we used temps, and did not embed inits, put them in a sequence If leftTemp IsNot Nothing OrElse rightTemp IsNot Nothing Then Dim temps = ArrayBuilder(Of LocalSymbol).GetInstance Dim inits = ArrayBuilder(Of BoundExpression).GetInstance If leftTemp IsNot Nothing Then temps.Add(leftTemp) If leftInit IsNot Nothing Then inits.Add(leftInit) End If End If If rightTemp IsNot Nothing Then temps.Add(rightTemp) If rightInit IsNot Nothing Then inits.Add(rightInit) End If End If value = New BoundSequence(node.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, value, value.Type) End If Return value End Function Private Function RewriteNullableIsOrIsNotOperator(node As BoundBinaryOperator) As BoundExpression Dim left As BoundExpression = node.Left Dim right As BoundExpression = node.Right Debug.Assert(left.IsNothingLiteral OrElse right.IsNothingLiteral) Debug.Assert(node.OperatorKind = BinaryOperatorKind.Is OrElse node.OperatorKind = BinaryOperatorKind.IsNot) If _inExpressionLambda Then Return node End If Return RewriteNullableIsOrIsNotOperator((node.OperatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Is, If(left.IsNothingLiteral, right, left), node.Type) End Function Private Function RewriteNullableIsOrIsNotOperator(isIs As Boolean, operand As BoundExpression, resultType As TypeSymbol) As BoundExpression Debug.Assert(resultType.IsBooleanType()) Debug.Assert(operand.Type.IsNullableType) If HasNoValue(operand) Then Return New BoundLiteral(operand.Syntax, If(isIs, ConstantValue.True, ConstantValue.False), resultType) ElseIf HasValue(operand) Then Return MakeSequence(operand, New BoundLiteral(operand.Syntax, If(isIs, ConstantValue.False, ConstantValue.True), resultType)) Else Dim whenNotNull As BoundExpression = Nothing Dim whenNull As BoundExpression = Nothing If IsConditionalAccess(operand, whenNotNull, whenNull) Then If HasNoValue(whenNull) Then Return UpdateConditionalAccess(operand, RewriteNullableIsOrIsNotOperator(isIs, whenNotNull, resultType), RewriteNullableIsOrIsNotOperator(isIs, whenNull, resultType)) End If End If Dim result As BoundExpression result = NullableHasValue(operand) If isIs Then result = New BoundUnaryOperator(result.Syntax, UnaryOperatorKind.Not, result, False, resultType) End If Return result End If End Function Private Function RewriteLiftedUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode ' ' Lifted user defined operator has structure as the following: ' ' | ' [implicit wrap] ' | ' CALL ' /\ ' [implicit unwrap] [implicit unwrap] ' | | ' LEFT RIGHT ' ' Implicit left/right unwrapping conversions if present are always L? -> L and R? -> R ' They are encoded as a disparity between CALL argument types and parameter types of the call symbol. ' ' Implicit wrapping conversion of the result, if present, is always T -> T? ' ' The rewrite is: ' If (LEFT.HasValue And RIGHT.HasValue, CALL(LEFT, RIGHT), Null) ' ' Note that the result of the operator is nullable type. Dim left = Me.VisitExpressionNode(node.Left) Dim right = Me.VisitExpressionNode(node.Right) Dim operatorCall = node.Call Dim resultType = operatorCall.Type Debug.Assert(resultType.IsNullableType()) Dim whenHasNoValue = NullableNull(node.Syntax, resultType) Debug.Assert(left.Type.IsNullableType() AndAlso right.Type.IsNullableType(), "left and right must be nullable") Dim leftHasNoValue As Boolean = HasNoValue(left) Dim rightHasNoValue As Boolean = HasNoValue(right) ' TWO NULLS If (leftHasNoValue And rightHasNoValue) Then Return whenHasNoValue End If ' ONE NULL If (leftHasNoValue Or rightHasNoValue) Then Return MakeSequence(If(leftHasNoValue, right, left), whenHasNoValue) End If Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing Dim inits As ArrayBuilder(Of BoundExpression) = Nothing ' PREPARE OPERANDS Dim leftHasValue As Boolean = HasValue(left) Dim rightHasValue As Boolean = HasValue(right) Dim leftCallInput As BoundExpression Dim rightCallInput As BoundExpression Dim condition As BoundExpression = Nothing If leftHasValue Then leftCallInput = NullableValueOrDefault(left) If rightHasValue Then rightCallInput = NullableValueOrDefault(right) Else leftCallInput = CaptureNullableIfNeeded(leftCallInput, temps, inits, doNotCaptureLocals:=True) rightCallInput = ProcessNullableOperand(right, condition, temps, inits, doNotCaptureLocals:=True) End If ElseIf rightHasValue Then leftCallInput = ProcessNullableOperand(left, condition, temps, inits, doNotCaptureLocals:=True) rightCallInput = NullableValueOrDefault(right) rightCallInput = CaptureNullableIfNeeded(rightCallInput, temps, inits, doNotCaptureLocals:=True) Else Dim leftHasValueExpression As BoundExpression = Nothing Dim rightHasValueExpression As BoundExpression = Nothing leftCallInput = ProcessNullableOperand(left, leftHasValueExpression, temps, inits, doNotCaptureLocals:=True) rightCallInput = ProcessNullableOperand(right, rightHasValueExpression, temps, inits, doNotCaptureLocals:=True) condition = MakeBooleanBinaryExpression(node.Syntax, BinaryOperatorKind.And, leftHasValueExpression, rightHasValueExpression) End If Debug.Assert(leftCallInput.Type.IsSameTypeIgnoringAll(operatorCall.Method.Parameters(0).Type), "operator must take either unwrapped values or not-nullable left directly") Debug.Assert(rightCallInput.Type.IsSameTypeIgnoringAll(operatorCall.Method.Parameters(1).Type), "operator must take either unwrapped values or not-nullable right directly") Dim whenHasValue As BoundExpression = operatorCall.Update(operatorCall.Method, Nothing, operatorCall.ReceiverOpt, ImmutableArray.Create(Of BoundExpression)(leftCallInput, rightCallInput), Nothing, operatorCall.ConstantValueOpt, isLValue:=operatorCall.IsLValue, suppressObjectClone:=operatorCall.SuppressObjectClone, type:=operatorCall.Method.ReturnType) If Not whenHasValue.Type.IsSameTypeIgnoringAll(resultType) Then whenHasValue = WrapInNullable(whenHasValue, resultType) End If Debug.Assert(whenHasValue.Type.IsSameTypeIgnoringAll(resultType), "result type must be same as resultType") ' RESULT If leftHasValue And rightHasValue Then Debug.Assert(temps Is Nothing AndAlso inits Is Nothing AndAlso condition Is Nothing) Return whenHasValue Else Dim result As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, condition, whenHasValue, whenHasNoValue) ' if we used a temp, arrange a sequence for it If temps IsNot Nothing Then result = New BoundSequence(node.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, result, result.Type) End If Return result End If End Function Private Function ApplyUnliftedBinaryOp(originalOperator As BoundBinaryOperator, left As BoundExpression, right As BoundExpression) As BoundExpression Debug.Assert(Not left.Type.IsNullableType) Debug.Assert(Not right.Type.IsNullableType) 'return UnliftedOP(left, right) Dim unliftedOpKind = originalOperator.OperatorKind And (Not BinaryOperatorKind.Lifted) Return MakeBinaryExpression(originalOperator.Syntax, unliftedOpKind, left, right, originalOperator.Checked, originalOperator.Type.GetNullableUnderlyingType) End Function End Class End Namespace
-1
dotnet/roslyn
55,773
Drop active statements when exiting break mode
Fixes https://github.com/dotnet/roslyn/issues/54347
tmat
2021-08-20T22:51:41Z
2021-08-23T16:48:09Z
9703b3728af153ae49f239278aac823f3da1b768
f852e2a4e9da49077d4ebb241d4dd8ced3353942
Drop active statements when exiting break mode. Fixes https://github.com/dotnet/roslyn/issues/54347
./src/Features/VisualBasic/Portable/CodeFixes/MoveToTopOfFile/MoveToTopOfFileCodeFixProvider.MoveToLineCodeAction.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.MoveToTopOfFile Partial Friend Class MoveToTopOfFileCodeFixProvider Private Class MoveToLineCodeAction Inherits CodeAction Private ReadOnly _destinationLine As Integer Private ReadOnly _document As Document Private ReadOnly _token As SyntaxToken Private ReadOnly _title As String Public Sub New(document As Document, token As SyntaxToken, destinationLine As Integer, title As String) _document = document _token = token _destinationLine = destinationLine _title = title End Sub Public Overrides ReadOnly Property Title As String Get Return _title End Get End Property Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim text = Await _document.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim destinationLineSpan = text.Lines(_destinationLine).Start Dim lineToMove = _token.GetLocation().GetLineSpan().StartLinePosition.Line Dim textLineToMove = text.Lines(lineToMove) Dim textWithoutLine = text.WithChanges(New TextChange(textLineToMove.SpanIncludingLineBreak, "")) Dim textWithMovedLine = textWithoutLine.WithChanges(New TextChange(TextSpan.FromBounds(destinationLineSpan, destinationLineSpan), textLineToMove.ToString().TrimStart() + vbCrLf)) Return _document.WithText(textWithMovedLine) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.MoveToTopOfFile Partial Friend Class MoveToTopOfFileCodeFixProvider Private Class MoveToLineCodeAction Inherits CodeAction Private ReadOnly _destinationLine As Integer Private ReadOnly _document As Document Private ReadOnly _token As SyntaxToken Private ReadOnly _title As String Public Sub New(document As Document, token As SyntaxToken, destinationLine As Integer, title As String) _document = document _token = token _destinationLine = destinationLine _title = title End Sub Public Overrides ReadOnly Property Title As String Get Return _title End Get End Property Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) Dim text = Await _document.GetTextAsync(cancellationToken).ConfigureAwait(False) Dim destinationLineSpan = text.Lines(_destinationLine).Start Dim lineToMove = _token.GetLocation().GetLineSpan().StartLinePosition.Line Dim textLineToMove = text.Lines(lineToMove) Dim textWithoutLine = text.WithChanges(New TextChange(textLineToMove.SpanIncludingLineBreak, "")) Dim textWithMovedLine = textWithoutLine.WithChanges(New TextChange(TextSpan.FromBounds(destinationLineSpan, destinationLineSpan), textLineToMove.ToString().TrimStart() + vbCrLf)) Return _document.WithText(textWithMovedLine) End Function End Class End Class End Namespace
-1