public static Diagnostic ToDiagnostics(this RazorError error, string filePath) { if (error == null) { throw new ArgumentNullException(nameof(error)); } if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } var descriptor = new DiagnosticDescriptor( id: "Razor", title: "Razor parsing error", messageFormat: error.Message.Replace("{", "{{").Replace("}", "}}"), category: "Razor.Parser", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); var location = error.Location; if (location.Equals(SourceLocation.Undefined)) { location = SourceLocation.Zero; } var length = Math.Max(0, error.Length); var textSpan = new TextSpan(location.AbsoluteIndex, length); var linePositionStart = new LinePosition(location.LineIndex, location.CharacterIndex); var linePositionEnd = new LinePosition(location.LineIndex, location.CharacterIndex + length); var linePositionSpan = new LinePositionSpan(linePositionStart, linePositionEnd); return Diagnostic.Create(descriptor, Location.Create(filePath, textSpan, linePositionSpan)); }
public void BeforeCompile(IBeforeCompileContext context) { string keyPath = Environment.GetEnvironmentVariable("NUGET_BUILD_KEY_PATH"); string delaySignString = Environment.GetEnvironmentVariable("NUGET_BUILD_DELAY_SIGN"); if (!string.IsNullOrEmpty(keyPath)) { FileInfo keyFile = new FileInfo(keyPath); if (keyFile.Exists) { bool delaySign = delaySignString != null && StringComparer.OrdinalIgnoreCase.Equals("true", delaySignString); // Console.WriteLine("Signing assembly with: {0} Delay sign: {1}", keyFile.FullName, delaySign ? "true" : "false"); var parms = new CspParameters(); parms.KeyNumber = 2; var provider = new RSACryptoServiceProvider(parms); byte[] array = provider.ExportCspBlob(!provider.PublicOnly); var strongNameProvider = new DesktopStrongNameProvider(); var options = context.Compilation.Options.WithStrongNameProvider(strongNameProvider) .WithCryptoKeyFile(keyFile.FullName) .WithDelaySign(delaySign); // Enfore viral strong naming var specificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(options.SpecificDiagnosticOptions); specificDiagnosticOptions["CS8002"] = ReportDiagnostic.Error; options = options.WithSpecificDiagnosticOptions(specificDiagnosticOptions); context.Compilation = context.Compilation.WithOptions(options); } else { // The key was not found. Throw a compile error. var descriptor = new DiagnosticDescriptor( id: "SN1001", title: "Missing key file", messageFormat: "Key file '{0}' could not be found", category: "CA1001: \"StrongNaming\"", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); // TODO: what should this reference for the location? var textSpan = new TextSpan(); var position = new LinePosition(0, 0); var span = new LinePositionSpan(position, position); var location = Location.Create(context.ProjectContext.ProjectFilePath, textSpan, span); var diagnsotic = Diagnostic.Create(descriptor, location, keyPath); context.Diagnostics.Add(diagnsotic); } } }
public async Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync(ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken) { if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (peekResultFactory == null) { throw new ArgumentNullException(nameof(peekResultFactory)); } var results = new List<IPeekableItem>(); var solution = project.Solution; var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false); // And if our definition actually is from source, then let's re-figure out what project it came from if (sourceDefinition != null) { var originatingProject = solution.GetProject(sourceDefinition.ContainingAssembly, cancellationToken); project = originatingProject ?? project; } string filePath; int lineNumber; int charOffset; var symbolNavigationService = solution.Workspace.Services.GetService<ISymbolNavigationService>(); if (symbolNavigationService.WouldNavigateToSymbol(symbol, solution, out filePath, out lineNumber, out charOffset)) { var position = new LinePosition(lineNumber, charOffset); results.Add(new ExternalFilePeekableItem(new FileLinePositionSpan(filePath, position, position), PredefinedPeekRelationships.Definitions, peekResultFactory)); } else { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbolKey = SymbolKey.Create(symbol, compilation, cancellationToken); var firstLocation = symbol.Locations.FirstOrDefault(); if (firstLocation != null) { if (firstLocation.IsInSource || _metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { results.Add(new DefinitionPeekableItem(solution.Workspace, project.Id, symbolKey, peekResultFactory, _metadataAsSourceFileService)); } } } return results; }
public static Diagnostic CreateDiagnostic(IToken offendingSymbol, int line, int charPositionInLine, string msg, string filePath) { var linePosition = new LinePosition(line-1, charPositionInLine); var textExtent = TextExtent.Missing; if (offendingSymbol != null) { textExtent = TextExtent.FromBounds(offendingSymbol.StartIndex, offendingSymbol.StopIndex + 1); } var location = new Location(textExtent, linePosition, filePath); var diagnostic = new Diagnostic(location, DiagnosticDescriptors.NewSyntaxError(msg)); return diagnostic; }
public void SaneHashCode() { var hash1 = new LinePosition(1, 1).GetHashCode(); var hash2 = new LinePosition(2, 2).GetHashCode(); var hash3 = new LinePosition(1, 2).GetHashCode(); var hash4 = new LinePosition(2, 1).GetHashCode(); Assert.NotEqual(hash1, hash2); Assert.NotEqual(hash1, hash3); Assert.NotEqual(hash1, hash4); Assert.NotEqual(hash2, hash3); Assert.NotEqual(hash2, hash4); Assert.NotEqual(hash3, hash4); }
public async Task TestConstantMessage_Local_PassWrongTypeAsync() { LinePosition linePosition = new LinePosition(6, 32); DiagnosticResult[] expected = { new DiagnosticResult { Id = "CS0029", Message = "Cannot implicitly convert type 'int' to 'string'", Severity = DiagnosticSeverity.Error, Spans = new[] { new FileLinePositionSpan("Test0.cs", linePosition, linePosition) } } }; await this.TestConstantMessage_Local_PassAsync("3", expected).ConfigureAwait(false); }
public DiagnosticDescription( object code, string squiggledText, object[] arguments, LinePosition? startLocation, Func<SyntaxNode, bool> syntaxNodePredicate, bool argumentOrderDoesNotMatter, Type errorCodeType = null) { _code = code; _isWarningAsError = false; _squiggledText = squiggledText; _arguments = arguments; _startPosition = startLocation; _syntaxPredicate = syntaxNodePredicate; _argumentOrderDoesNotMatter = argumentOrderDoesNotMatter; _errorCodeType = errorCodeType ?? code.GetType(); }
public async Task <HoverModel> Handle(HoverParams request, CancellationToken cancellationToken) { if (request is null) { throw new ArgumentNullException(nameof(request)); } var document = await _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync(() => { _documentResolver.TryResolveDocument(request.TextDocument.Uri.GetAbsoluteOrUNCPath(), out var documentSnapshot); return(documentSnapshot); }, cancellationToken).ConfigureAwait(false); if (document is null) { return(null); } var codeDocument = await document.GetGeneratedOutputAsync(); if (codeDocument.IsUnsupported()) { return(null); } var sourceText = await document.GetTextAsync(); var linePosition = new LinePosition((int)request.Position.Line, (int)request.Position.Character); var hostDocumentIndex = sourceText.Lines.GetPosition(linePosition); var location = new SourceLocation(hostDocumentIndex, (int)request.Position.Line, (int)request.Position.Character); var clientCapabilities = _languageServer.ClientSettings.Capabilities; var hoverItem = _hoverInfoService.GetHoverInfo(codeDocument, location, clientCapabilities); _logger.LogTrace($"Found hover info items."); return(hoverItem); }
public async Task <HoverViewModel> ProvideHoverAsync( SourceText sourceText, LinePosition linePosition, CancellationToken cancellationToken) { var hover = new HoverViewModel(); var position = sourceText.Lines.GetPosition(linePosition); if (position <= 0) { return(hover); } var document = compilationWorkspace.GetSubmissionDocument(sourceText.Container); var root = await document.GetSyntaxRootAsync(cancellationToken); var syntaxToken = root.FindToken(position); var expression = syntaxToken.Parent as ExpressionSyntax; if (expression == null) { return(hover); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var symbolInfo = semanticModel.GetSymbolInfo(expression); if (symbolInfo.Symbol == null) { return(hover); } hover.Contents = new [] { symbolInfo.Symbol.ToDisplayString(Constants.SymbolDisplayFormat) }; hover.Range = syntaxToken.GetLocation().GetLineSpan().Span; return(hover); }
public JoinPreviousParagraphCommand( ITextEditingCommandController <TContext> controller, LinePosition line) : base(true, false) { // Establish our code contracts. if (line.Index <= 0) { throw new InvalidOperationException( "Cannot join the paragraph on the first line."); } // Joining a paragraph consists of inserting the text of the current // paragraph into the previous one with a space and then moving the // cursor to the end of the original first paragraph (and space). // Insert the text from the line into the prvious line. var joinedLine = new LinePosition((int)line - 1); IInsertTextFromTextRangeCommand <TContext> insertCommand = controller.CreateInsertTextFromTextRangeCommand( new TextPosition(joinedLine, CharacterPosition.End), new SingleLineTextRange( line, CharacterPosition.Begin, CharacterPosition.End)); insertCommand.UpdateTextPosition = DoTypes.All; // Finally, delete the current line since we merged it. IDeleteLineCommand <TContext> deleteCommand = controller.CreateDeleteLineCommand(line); deleteCommand.UpdateTextPosition = DoTypes.None; // Add the commands into the composite and indicate that the whitespace // command controls where the text position will end up. Commands.Add(insertCommand); Commands.Add(deleteCommand); }
/// <summary> /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location /// in the expected DiagnosticResult. /// </summary> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="diagnostic">The diagnostic that was found in the code</param> /// <param name="actual">The Location of the Diagnostic found in the code</param> /// <param name="expected">The DiagnosticResultLocation that should have been found</param> private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected) { FileLinePositionSpan actualSpan = actual.GetLineSpan(); Assert.IsTrue( actualSpan.Path == expected.Path || actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test."), string.Format( "Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic))); LinePosition actualLinePosition = actualSpan.StartLinePosition; // Only check line position if there is an actual line in the real diagnostic if (actualLinePosition.Line > 0) { if (actualLinePosition.Line + 1 != expected.Line) { Assert.IsTrue(false, string.Format( "Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); } } // Only check column position if there is an actual column position in the real diagnostic if (actualLinePosition.Character > 0) { if (actualLinePosition.Character + 1 != expected.Column) { Assert.IsTrue(false, string.Format( "Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); } } }
public async Task <HoverModel> Handle(HoverParams request, CancellationToken cancellationToken) { if (request is null) { throw new ArgumentNullException(nameof(request)); } var document = await Task.Factory.StartNew(() => { _documentResolver.TryResolveDocument(request.TextDocument.Uri.GetAbsoluteOrUNCPath(), out var documentSnapshot); return(documentSnapshot); }, cancellationToken, TaskCreationOptions.None, _foregroundDispatcher.ForegroundScheduler); if (document is null) { return(null); } var codeDocument = await document.GetGeneratedOutputAsync(); if (codeDocument.IsUnsupported()) { return(null); } var sourceText = await document.GetTextAsync(); var linePosition = new LinePosition((int)request.Position.Line, (int)request.Position.Character); var hostDocumentIndex = sourceText.Lines.GetPosition(linePosition); var location = new SourceLocation(hostDocumentIndex, (int)request.Position.Line, (int)request.Position.Character); var hoverItem = _hoverInfoService.GetHoverInfo(codeDocument, location); _logger.LogTrace($"Found hover info items."); return(hoverItem); }
public static async Task Verify( string code, LinePosition codeProvidingRefactorPosition, string expectedRefactoredCode, string expectedRefactoringTitle) { var test = new CSharpCodeRefactoringTest <TCodeRefactoringProvider, XUnitVerifier>() { TestCode = code, FixedCode = expectedRefactoredCode, CodeActionValidationMode = CodeActionValidationMode.None, CodeActionVerifier = (codeAction, verifier) => { verifier.Equal(codeAction.Title, expectedRefactoringTitle); } }; test.ExpectedDiagnostics.Add(new DiagnosticResult("Refactoring", DiagnosticSeverity.Hidden) .WithSpan(codeProvidingRefactorPosition.Line, codeProvidingRefactorPosition.Character, codeProvidingRefactorPosition.Line, codeProvidingRefactorPosition.Character)); test.OffersEmptyRefactoring = true; test.TestState.AdditionalReferences.AddRange(new[]
object ProvideCompletionItems( string modelId, LinePosition linePosition, CancellationToken cancellationToken) { sourceTextContent = getSourceTextByModelId(modelId); var sourcePosition = sourceTextContent.Lines.GetPosition(linePosition); var rules = compilationWorkspace.CompletionService.GetRules(); StopComputation(); StartNewComputation(sourcePosition, rules, filterItems: true); var currentComputation = computation; cancellationToken.Register(() => currentComputation.Stop()); return(context.ToMonacoPromise( computation.ModelTask, ToMonacoCompletionItems, MainThread.TaskScheduler, raiseErrors: false)); }
public static int GetAbsoluteIndex(this Position position, SourceText sourceText) { if (position is null) { throw new ArgumentNullException(nameof(position)); } if (sourceText is null) { throw new ArgumentNullException(nameof(sourceText)); } var linePosition = new LinePosition(position.Line, position.Character); if (linePosition.Line >= sourceText.Lines.Count) { throw new ArgumentOutOfRangeException(Resources.FormatPositionIndex_Outside_Range( position.Line, nameof(sourceText), sourceText.Lines.Count)); } var index = sourceText.Lines.GetPosition(linePosition); return(index); }
public async Task <IEnumerable <IPeekableItem> > GetPeekableItemsAsync(ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken) { if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (peekResultFactory == null) { throw new ArgumentNullException(nameof(peekResultFactory)); } var results = new List <IPeekableItem>(); var solution = project.Solution; var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false); // And if our definition actually is from source, then let's re-figure out what project it came from if (sourceDefinition != null) { var originatingProject = solution.GetProject(sourceDefinition.ContainingAssembly, cancellationToken); project = originatingProject ?? project; } var symbolNavigationService = solution.Workspace.Services.GetService <ISymbolNavigationService>(); if (symbolNavigationService.WouldNavigateToSymbol(symbol, solution, out var filePath, out var lineNumber, out var charOffset)) { var position = new LinePosition(lineNumber, charOffset); results.Add(new ExternalFilePeekableItem(new FileLinePositionSpan(filePath, position, position), PredefinedPeekRelationships.Definitions, peekResultFactory)); }
public void Do( ICommand <OperationContext> command, OperationContext context) { // Every command needs a full write lock on the blocks. using (Project.Blocks.AcquireLock(RequestLock.Write)) { // Create the context for the block commands. var blockContext = new BlockCommandContext(Project); LinePosition linePosition = context.Position.LinePosition; int lineIndex = linePosition.GetLineIndex(Project.Blocks.Count); Block currentBlock = Project.Blocks[lineIndex]; blockContext.Position = new BlockPosition( currentBlock, context.Position.CharacterPosition); // Wrap the command with our wrappers. IWrappedCommand wrappedCommand = WrapCommand(command, context); Project.Commands.Do(wrappedCommand, blockContext); // Set the operation context from the block context. if (blockContext.Position.HasValue) { // Grab the block position and figure out the index. BlockPosition blockPosition = blockContext.Position.Value; int blockIndex = Project.Blocks.IndexOf(blockPosition.BlockKey); var position = new TextPosition(blockIndex, (int)blockPosition.TextIndex); // Set the context results. context.Results = new LineBufferOperationResults(position); } // Make sure we process our wrapped command. wrappedCommand.PostDo(context); } }
protected FileLinePositionSpan TranslateSpan( LineMappingEntry entry, string treeFilePath, LinePosition unmappedStartPos, LinePosition unmappedEndPos ) { string path = entry.MappedPathOpt ?? treeFilePath; int mappedStartLine = unmappedStartPos.Line - entry.UnmappedLine + entry.MappedLine; int mappedEndLine = unmappedEndPos.Line - entry.UnmappedLine + entry.MappedLine; return(new FileLinePositionSpan( path, new LinePositionSpan( (mappedStartLine == -1) ? new LinePosition(unmappedStartPos.Character) : new LinePosition(mappedStartLine, unmappedStartPos.Character), (mappedEndLine == -1) ? new LinePosition(unmappedEndPos.Character) : new LinePosition(mappedEndLine, unmappedEndPos.Character) ), hasMappedPath: entry.MappedPathOpt != null )); }
// Internal for testing internal SourceText ApplyContentChanges(IEnumerable <TextDocumentContentChangeEvent> contentChanges, SourceText sourceText) { foreach (var change in contentChanges) { if (change.Range is null) { throw new ArgumentNullException(nameof(change.Range), "Range of change should not be null."); } var linePosition = new LinePosition(change.Range.Start.Line, change.Range.Start.Character); var position = sourceText.Lines.GetPosition(linePosition); var textSpan = new TextSpan(position, change.RangeLength); var textChange = new TextChange(textSpan, change.Text); _logger.LogTrace("Applying " + textChange); // If there happens to be multiple text changes we generate a new source text for each one. Due to the // differences in VSCode and Roslyn's representation we can't pass in all changes simultaneously because // ordering may differ. sourceText = sourceText.WithChanges(textChange); } return(sourceText); }
internal XSharpSourceLocation(XSharpParserRuleContext context) { var start = context.Start as XSharpToken; var stop = context.Stop as XSharpToken; if (start.SourceSymbol != null) { start = start.SourceSymbol; } if (stop.SourceSymbol != null) { stop = stop.SourceSymbol; } if (stop.Type == XSharpLexer.Eof) { var cu = context.CompilationUnit; if (cu != null) { var stream = cu.XTokens as BufferedTokenStream; var tokens = stream.GetTokens(); var last = tokens.Count - 1; if (tokens[last].Type == XSharpLexer.Eof && last > 0) { stop = (XSharpToken)tokens[last - 1]; } } } var width = stop.StopIndex - start.StartIndex; var lp1 = new LinePosition(start.Line - 1, start.Column); var lp2 = new LinePosition(stop.Line - 1, stop.Column + stop.Text.Length - 1); _context = context; _sourceSpan = new TextSpan(start.StartIndex, width); _lineSpan = new FileLinePositionSpan(context.SourceFileName, new LinePositionSpan(lp1, lp2)); }
public async Task <BraceCompletionResult?> GetBraceCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken) { var closingPoint = braceCompletionContext.ClosingPoint; if (closingPoint < 1) { return(null); } var openingPoint = braceCompletionContext.OpeningPoint; var document = braceCompletionContext.Document; var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (sourceText[openingPoint] != OpeningBrace) { return(null); } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(openingPoint, findInsideTrivia: true); var validOpeningPoint = await IsValidOpenBraceTokenAtPositionAsync(token, openingPoint, document, cancellationToken).ConfigureAwait(false); if (!validOpeningPoint) { return(null); } var braceTextEdit = new TextChange(TextSpan.FromBounds(closingPoint, closingPoint), ClosingBrace.ToString()); // The caret location should be in between the braces. var originalOpeningLinePosition = sourceText.Lines.GetLinePosition(openingPoint); var caretLocation = new LinePosition(originalOpeningLinePosition.Line, originalOpeningLinePosition.Character + 1); return(new BraceCompletionResult(ImmutableArray.Create(braceTextEdit), caretLocation)); }
public DiagnosticResult WithLocation(LinePosition location) => WithLocation(path: string.Empty, location);
public NavigateReplHistoryEvent(IEditor source, LinePosition cursor, bool navigatePrevious) : base(source, cursor) => NavigatePrevious = navigatePrevious;
/// <summary> /// Gets <see cref="DiagnosticData"/> objects for selected error list entries. /// For remove suppression, the method also returns selected external source diagnostics. /// </summary> public async Task <ImmutableArray <DiagnosticData> > GetSelectedItemsAsync(bool isAddSuppression, CancellationToken cancellationToken) { var builder = ImmutableArray.CreateBuilder <DiagnosticData>(); Dictionary <string, Project> projectNameToProjectMapOpt = null; Dictionary <Project, ImmutableDictionary <string, Document> > filePathToDocumentMapOpt = null; foreach (var entryHandle in _tableControl.SelectedEntries) { cancellationToken.ThrowIfCancellationRequested(); DiagnosticData diagnosticData = null; int index; var roslynSnapshot = GetEntriesSnapshot(entryHandle, out index); if (roslynSnapshot != null) { diagnosticData = roslynSnapshot.GetItem(index)?.Primary; } else if (!isAddSuppression) { // For suppression removal, we also need to handle FxCop entries. bool isSuppressedEntry; if (!IsNonRoslynEntrySupportingSuppressionState(entryHandle, out isSuppressedEntry) || !isSuppressedEntry) { continue; } string errorCode = null, category = null, message = null, filePath = null, projectName = null; int line = -1; // FxCop only supports line, not column. DiagnosticDataLocation location = null; if (entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCode, out errorCode) && !string.IsNullOrEmpty(errorCode) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCategory, out category) && !string.IsNullOrEmpty(category) && entryHandle.TryGetValue(StandardTableColumnDefinitions.Text, out message) && !string.IsNullOrEmpty(message) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ProjectName, out projectName) && !string.IsNullOrEmpty(projectName)) { if (projectNameToProjectMapOpt == null) { projectNameToProjectMapOpt = new Dictionary <string, Project>(); foreach (var p in _workspace.CurrentSolution.Projects) { projectNameToProjectMapOpt[p.Name] = p; } } cancellationToken.ThrowIfCancellationRequested(); Project project; if (!projectNameToProjectMapOpt.TryGetValue(projectName, out project)) { // bail out continue; } Document document = null; var hasLocation = (entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out filePath) && !string.IsNullOrEmpty(filePath)) && (entryHandle.TryGetValue(StandardTableColumnDefinitions.Line, out line) && line >= 0); if (hasLocation) { if (string.IsNullOrEmpty(filePath) || line < 0) { // bail out continue; } ImmutableDictionary <string, Document> filePathMap; filePathToDocumentMapOpt = filePathToDocumentMapOpt ?? new Dictionary <Project, ImmutableDictionary <string, Document> >(); if (!filePathToDocumentMapOpt.TryGetValue(project, out filePathMap)) { filePathMap = await GetFilePathToDocumentMapAsync(project, cancellationToken).ConfigureAwait(false); filePathToDocumentMapOpt[project] = filePathMap; } if (!filePathMap.TryGetValue(filePath, out document)) { // bail out continue; } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var linePosition = new LinePosition(line, 0); var linePositionSpan = new LinePositionSpan(start: linePosition, end: linePosition); var textSpan = (await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)).Lines.GetTextSpan(linePositionSpan); location = new DiagnosticDataLocation(document.Id, textSpan, filePath, originalStartLine: linePosition.Line, originalStartColumn: linePosition.Character, originalEndLine: linePosition.Line, originalEndColumn: linePosition.Character); } Contract.ThrowIfNull(project); Contract.ThrowIfFalse((document != null) == (location != null)); // Create a diagnostic with correct values for fields we care about: id, category, message, isSuppressed, location // and default values for the rest of the fields (not used by suppression fixer). diagnosticData = new DiagnosticData( id: errorCode, category: category, message: message, enuMessageForBingSearch: message, severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 1, isSuppressed: isSuppressedEntry, title: message, location: location, customTags: SuppressionHelpers.SynthesizedExternalSourceDiagnosticCustomTags, properties: ImmutableDictionary <string, string> .Empty, workspace: _workspace, projectId: project.Id); } } if (IsEntryWithConfigurableSuppressionState(diagnosticData)) { builder.Add(diagnosticData); } } return(builder.ToImmutable()); }
///<summary>Overload for LineObject.</summary> public ReportObject(string name,string sectionName,Color color,float lineThickness,LineOrientation lineOrientation,LinePosition linePosition,int linePercent,int offSetX,int offSetY) { _name=name; _sectionName=sectionName; _foreColor=color; _floatLineThickness=lineThickness; _lineOrientation=lineOrientation; _linePosition=linePosition; _intLinePercent=linePercent; _offSetX=offSetX; _offSetY=offSetY; _reportObjectKind=ReportObjectKind.LineObject; }
public string GetLineText(LinePosition line) { int lineIndex = line.GetLineIndex(this); return(GetLineText(lineIndex, LineContexts.Unformatted)); }
public DiagnosticResult WithLineOffset(int offset) { DiagnosticResult result = this; Array.Resize(ref result.spans, result.spans?.Length ?? 0); for (int i = 0; i < result.spans.Length; i++) { var newStartLinePosition = new LinePosition(result.spans[i].StartLinePosition.Line + offset, result.spans[i].StartLinePosition.Character); var newEndLinePosition = new LinePosition(result.spans[i].EndLinePosition.Line + offset, result.spans[i].EndLinePosition.Character); result.spans[i] = new FileLinePositionSpan(result.spans[i].Path, newStartLinePosition, newEndLinePosition); } return result; }
/// <summary>Adds a line to a section.</summary> public void AddLine(string name,string sectionName,Color color,float floatLineThickness,LineOrientation lineOrientation,LinePosition linePosition,int linePercentValue,int offSetX,int offSetY) { _reportObjects.Add(new ReportObject(name,sectionName,color,floatLineThickness,lineOrientation,linePosition,linePercentValue,offSetX,offSetY)); }
public void RegisterCall_WithoutFirstArgumentNameOfExpression_ShouldReport() { var brokenSource = @" using System.Windows; public class ClassWithDependencyProperty : DependencyObject { public static readonly DependencyProperty DependencyPropertyNameProperty = DependencyProperty.Register( ""DependencyPropertyName"", typeof(string), typeof(ClassWithDependencyProperty), new PropertyMetadata(default(string))); public string DependencyPropertyName { get { return (string)GetValue(DependencyPropertyNameProperty); } set { SetValue(DependencyPropertyNameProperty, value); } } }"; var expectedLocation = new LinePosition(8, 17); var expected = new DiagnosticResult { Id = "DependencyPropertyWithoutNameOfOperatorAnalyzer", Message = "Dependency property 'DependencyPropertyName' can use nameof() operator for DependencyProperty.Register() call", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", expectedLocation.Line, expectedLocation.Character) } }; VerifyCSharpDiagnostic(brokenSource, WpfReferences, expected); }
public TitlePageIndicator(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { if(IsInEditMode) return; var res = Resources; //Load defaults from resources var defaultFooterColor = res.GetColor(Resource.Color.default_title_indicator_footer_color); var defaultFooterLineHeight = res.GetDimension(Resource.Dimension.default_title_indicator_footer_line_height); var defaultFooterIndicatorStyle = res.GetInteger(Resource.Integer.default_title_indicator_footer_indicator_style); var defaultFooterIndicatorHeight = res.GetDimension(Resource.Dimension.default_title_indicator_footer_indicator_height); var defaultFooterIndicatorUnderlinePadding = res.GetDimension(Resource.Dimension.default_title_indicator_footer_indicator_underline_padding); var defaultFooterPadding = res.GetDimension(Resource.Dimension.default_title_indicator_footer_padding); var defaultLinePosition = res.GetInteger(Resource.Integer.default_title_indicator_line_position); var defaultSelectedColor = res.GetColor(Resource.Color.default_title_indicator_selected_color); var defaultSelectedBold = res.GetBoolean(Resource.Boolean.default_title_indicator_selected_bold); var defaultTextColor = res.GetColor(Resource.Color.default_title_indicator_text_color); var defaultTextSize = res.GetDimension(Resource.Dimension.default_title_indicator_text_size); var defaultTitlePadding = res.GetDimension(Resource.Dimension.default_title_indicator_title_padding); var defaultClipPadding = res.GetDimension(Resource.Dimension.default_title_indicator_clip_padding); var defaultTopPadding = res.GetDimension(Resource.Dimension.default_title_indicator_top_padding); var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.TitlePageIndicator, defStyle, 0); _footerLineHeight = a.GetDimension(Resource.Styleable.TitlePageIndicator_footerLineHeight, defaultFooterLineHeight); _footerIndicatorStyle = (IndicatorStyle)a.GetInteger(Resource.Styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle); _footerIndicatorHeight = a.GetDimension(Resource.Styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight); _footerIndicatorUnderlinePadding = a.GetDimension(Resource.Styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, defaultFooterIndicatorUnderlinePadding); _footerPadding = a.GetDimension(Resource.Styleable.TitlePageIndicator_footerPadding, defaultFooterPadding); _linePosition = (LinePosition)a.GetInteger(Resource.Styleable.TitlePageIndicator_linePosition, defaultLinePosition); _topPadding = a.GetDimension(Resource.Styleable.TitlePageIndicator_topPadding, defaultTopPadding); _titlePadding = a.GetDimension(Resource.Styleable.TitlePageIndicator_titlePadding, defaultTitlePadding); _clipPadding = a.GetDimension(Resource.Styleable.TitlePageIndicator_clipPadding, defaultClipPadding); _colorSelected = a.GetColor(Resource.Styleable.TitlePageIndicator_selectedColor, defaultSelectedColor); _colorText = a.GetColor(Resource.Styleable.TitlePageIndicator_android_textColor, defaultTextColor); _boldText = a.GetBoolean(Resource.Styleable.TitlePageIndicator_selectedBold, defaultSelectedBold); var textSize = a.GetDimension(Resource.Styleable.TitlePageIndicator_android_textSize, defaultTextSize); var footerColor = a.GetColor(Resource.Styleable.TitlePageIndicator_footerColor, defaultFooterColor); _paintText.TextSize = textSize; _paintFooterLine.SetStyle(Paint.Style.FillAndStroke); _paintFooterLine.StrokeWidth = _footerLineHeight; _paintFooterLine.Color = footerColor; _paintFooterIndicator.SetStyle(Paint.Style.FillAndStroke); _paintFooterIndicator.Color = footerColor; var background = a.GetDrawable(Resource.Styleable.TitlePageIndicator_android_background); if(null != background) Background = background; a.Recycle(); var configuration = ViewConfiguration.Get(context); _touchSlop = ViewConfigurationCompat.GetScaledPagingTouchSlop(configuration); }
public async Task TestDiagnosticDoesNotThrowNullReferenceForWrongConstantTypeAsync() { var testCode = @"public class Foo { [System.Diagnostics.CodeAnalysis.SuppressMessage(null, null, Justification = 5)] public void Bar() { } }"; var expectedLinePosition = new LinePosition(4, 82); DiagnosticResult[] expected = { this.CSharpDiagnostic().WithLocation(4, 66), new DiagnosticResult { Id = "CS0029", Message = "Cannot implicitly convert type 'int' to 'string'", Severity = DiagnosticSeverity.Error, Spans = new[] { new FileLinePositionSpan("Test0.cs", expectedLinePosition, expectedLinePosition) } } }; await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); }
public ProcessingResultDiagnosticLocation(LinePosition position) { Line = position.Line; Column = position.Character; }
public static TextSpan GetTextSpan(DiagnosticDataLocation dataLocation, SourceText text) { var lines = text.Lines; if (lines.Count == 0) { return default(TextSpan); } var originalStartLine = dataLocation?.OriginalStartLine ?? 0; if (originalStartLine >= lines.Count) { return new TextSpan(text.Length, 0); } int startLine, startColumn, endLine, endColumn; AdjustBoundaries(dataLocation, lines, out startLine, out startColumn, out endLine, out endColumn); var startLinePosition = new LinePosition(startLine, startColumn); var endLinePosition = new LinePosition(endLine, endColumn); SwapIfNeeded(ref startLinePosition, ref endLinePosition); var span = text.Lines.GetTextSpan(new LinePositionSpan(startLinePosition, endLinePosition)); return TextSpan.FromBounds(Math.Min(Math.Max(span.Start, 0), text.Length), Math.Min(Math.Max(span.End, 0), text.Length)); }
public async Task TestIncompleteMemberAsync() { // Tests that the analyzer does not crash on incomplete members string testCode = @"public interface OuterType { event System.Action TestEvent; public string public string } "; // We don't care about the syntax errors. var expectedLinePosition1 = new LinePosition(5, 5); var expectedLinePosition2 = new LinePosition(6, 1); var expected = new[] { new DiagnosticResult { Id = "CS1585", Message = "Member modifier 'public' must precede the member type and name", Severity = DiagnosticSeverity.Error, Spans = new[] { new FileLinePositionSpan("Test0.cs", expectedLinePosition1, expectedLinePosition1) } }, new DiagnosticResult { Id = "CS1519", Message = "Invalid token '}' in class, struct, or interface member declaration", Severity = DiagnosticSeverity.Error, Spans = new[] { new FileLinePositionSpan("Test0.cs", expectedLinePosition2, expectedLinePosition2) } } }; await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); }
public DiagnosticResult WithLocation(string path, int line, int column) { var linePosition = new LinePosition(line, column); return this.AppendSpan(new FileLinePositionSpan(path, linePosition, linePosition)); }
protected BlockKeyCommand(LinePosition line) { Line = line; UseBlockKey = false; UpdateTextPosition = DoTypes.All; }
internal static DiagnosticDescription Diagnostic( object code, XCData squiggledText, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false) { return Diagnostic( code, NormalizeDiagnosticString(squiggledText.Value), arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter); }
internal static DiagnosticDescription Diagnostic( object code, string squiggledText = null, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false) { Debug.Assert(code is ErrorCode || code is ERRID || code is int || code is string); return new DiagnosticDescription( code as string ?? (object)(int)code, false, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, code.GetType()); }
/// <summary>Line is drawn in 50% of the available space, black in color and in 2pt size.</summary> public void AddLine(string name,string sectionName,LineOrientation lineOrientation,LinePosition linePosition) { AddLine(name,sectionName,Color.Black,2,lineOrientation,linePosition,50,0,0); }
public void setLinePosition(LinePosition linePosition) { mLinePosition = linePosition; Invalidate(); }
/// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="start">The start line position.</param> /// <param name="end">The end line position.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePosition start, LinePosition end) : this(path, new LinePositionSpan(start, end)) { }
public TitlePageIndicator(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { if (IsInEditMode) return; //Load defaults from resources Android.Content.Res.Resources res = this.Resources; Color defaultFooterColor = res.GetColor(R.Color.default_title_indicator_footer_color); float defaultFooterLineHeight = res.GetDimension(R.Dimension.default_title_indicator_footer_line_height); int defaultFooterIndicatorStyle = res.GetInteger(R.Integer.default_title_indicator_footer_indicator_style); float defaultFooterIndicatorHeight = res.GetDimension(R.Dimension.default_title_indicator_footer_indicator_height); float defaultFooterIndicatorUnderlinePadding = res.GetDimension(R.Dimension.default_title_indicator_footer_indicator_underline_padding); float defaultFooterPadding = res.GetDimension(R.Dimension.default_title_indicator_footer_padding); int defaultLinePosition = res.GetInteger(R.Integer.default_title_indicator_line_position); Color defaultSelectedColor = res.GetColor(R.Color.default_title_indicator_selected_color); bool defaultSelectedBold = res.GetBoolean(R.Boolean.default_title_indicator_selected_bold); Color defaultTextColor = res.GetColor(R.Color.default_title_indicator_text_color); float defaultTextSize = res.GetDimension(R.Dimension.default_title_indicator_text_size); float defaultTitlePadding = res.GetDimension(R.Dimension.default_title_indicator_title_padding); float defaultClipPadding = res.GetDimension(R.Dimension.default_title_indicator_clip_padding); float defaultTopPadding = res.GetDimension(R.Dimension.default_title_indicator_top_padding); //Retrieve styles attributes TypedArray a = context.ObtainStyledAttributes(attrs, R.Styleable.TitlePageIndicator, defStyle, 0); //Retrieve the colors to be used for this view and apply them. mFooterLineHeight = a.GetDimension(R.Styleable.TitlePageIndicator_footerLineHeight, defaultFooterLineHeight); mFooterIndicatorStyle = (IndicatorStyle)(a.GetInteger(R.Styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle)); mFooterIndicatorHeight = a.GetDimension(R.Styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight); mFooterIndicatorUnderlinePadding = a.GetDimension(R.Styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, defaultFooterIndicatorUnderlinePadding); mFooterPadding = a.GetDimension(R.Styleable.TitlePageIndicator_footerPadding, defaultFooterPadding); mLinePosition = (LinePosition)(a.GetInteger(R.Styleable.TitlePageIndicator_linePosition, defaultLinePosition)); mTopPadding = a.GetDimension(R.Styleable.TitlePageIndicator_topPadding, defaultTopPadding); mTitlePadding = a.GetDimension(R.Styleable.TitlePageIndicator_titlePadding, defaultTitlePadding); mClipPadding = a.GetDimension(R.Styleable.TitlePageIndicator_clipPadding, defaultClipPadding); mColorSelected = a.GetColor(R.Styleable.TitlePageIndicator_selectedColor, defaultSelectedColor); mColorText = a.GetColor(R.Styleable.TitlePageIndicator_android_textColor, defaultTextColor); mBoldText = a.GetBoolean(R.Styleable.TitlePageIndicator_selectedBold, defaultSelectedBold); float textSize = a.GetDimension(R.Styleable.TitlePageIndicator_android_textSize, defaultTextSize); Color footerColor = a.GetColor(R.Styleable.TitlePageIndicator_footerColor, defaultFooterColor); mPaintText.TextSize = textSize; mPaintText.AntiAlias = true; mPaintFooterLine.SetStyle(Paint.Style.FillAndStroke); mPaintFooterLine.StrokeWidth = mFooterLineHeight; mPaintFooterLine.Color = footerColor; mPaintFooterIndicator.SetStyle(Paint.Style.FillAndStroke); mPaintFooterIndicator.Color = footerColor; Drawable background = a.GetDrawable(R.Styleable.TitlePageIndicator_android_background); if (background != null) { SetBackgroundDrawable(background); } a.Recycle(); ViewConfiguration configuration = ViewConfiguration.Get(context); mTouchSlop = ViewConfigurationCompat.GetScaledPagingTouchSlop(configuration); }
public void SetText( LinePosition line, string text) { SetText((int)line, text); }
private static bool TryFixUpNearestVisibleSpan( TextManager.Interop.IVsContainedLanguageHost containedLanguageHost, TextManager.Interop.IVsTextBufferCoordinator bufferCoordinator, int originalLine, int originalColumn, out LinePosition adjustedPosition) { // GetNearestVisibleToken gives us the position right at the end of visible span. // Move the position one position to the left so that squiggle can show up on last token. if (originalColumn > 1) { adjustedPosition = new LinePosition(originalLine, originalColumn - 1); return true; } if (originalLine > 1) { if (VSConstants.S_OK == bufferCoordinator.GetSecondaryBuffer(out var secondaryBuffer) && VSConstants.S_OK == secondaryBuffer.GetLengthOfLine(originalLine - 1, out var length)) { adjustedPosition = new LinePosition(originalLine - 1, length); return true; } } adjustedPosition = LinePosition.Zero; return false; }
static LineLocation ToLineLocation(this LinePosition pos) => new LineLocation(pos.Line, pos.Character);
private LinePositionSpan GetLinePositionSpan(LinePosition position1, LinePosition position2) { if (position1 <= position2) { return new LinePositionSpan(position1, position2); } return new LinePositionSpan(position2, position1); }
private static async Task <InvocationContext> GetInvocation(Document document, LinePosition linePosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken); var position = Math.Max(text.Lines.GetPosition(linePosition.ToCodeAnalysisLinePosition()) - 1, 0); // backtrack into the actual invocation var tree = await document.GetSyntaxTreeAsync(cancellationToken); var root = await tree.GetRootAsync(cancellationToken); var node = root.FindToken(position).Parent; // Walk up until we find a node that we're interested in. while (node is not null) { if (node is InvocationExpressionSyntax invocation && invocation.ArgumentList.Span.Contains(position)) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); return(new InvocationContext(semanticModel, position, invocation.Expression, invocation.ArgumentList, invocation.IsInStaticContext())); } if (node is ObjectCreationExpressionSyntax objectCreation && objectCreation.ArgumentList.Span.Contains(position)) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); return(new InvocationContext(semanticModel, position, objectCreation, objectCreation.ArgumentList, objectCreation.IsInStaticContext())); } if (node is AttributeSyntax attributeSyntax && attributeSyntax.ArgumentList.Span.Contains(position)) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); return(new InvocationContext(semanticModel, position, attributeSyntax, attributeSyntax.ArgumentList, attributeSyntax.IsInStaticContext())); } node = node.Parent; } return(null); }
private static LinePosition Max(LinePosition position1, LinePosition position2) { return position1 > position2 ? position1 : position2; }
public static async Task <int> GetPositionFromLinePositionAsync(this Document document, LinePosition linePosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); return(text.Lines.GetPosition(linePosition)); }
public MarkupText(string text) { var lines = new List<string>(); var positionsBuilder = ImmutableArray.CreateBuilder<LinePosition>(); var spansBuilder = ImmutableArray.CreateBuilder<LinePositionSpan>(); var spanStartsStack = new Stack<LinePosition>(); var reader = new StringReader(text); var lineNumber = 0; string line = null; while ((line = reader.ReadLine()) != null) { var lineBuilder = new StringBuilder(); var indexInLine = 0; foreach (Match match in s_regex.Matches(line)) { lineBuilder.Append(line, indexInLine, match.Index - indexInLine); if (match.Value == "$$") { positionsBuilder.Add(new LinePosition(lineNumber, lineBuilder.Length)); } else if (match.Value == "[|") { spanStartsStack.Push(new LinePosition(lineNumber, lineBuilder.Length)); } else { if (spanStartsStack.Count == 0) { var index = match.Index; string contextSnippet = GetExceptionContextSnippet(line, index); var exceptionMessage = $"Unmatched span end at line {lineNumber}, columm {index}: {contextSnippet}"; throw new ArgumentException(exceptionMessage, nameof(text)); } var spanStart = spanStartsStack.Pop(); var spanEnd = new LinePosition(lineNumber, lineBuilder.Length); spansBuilder.Add(new LinePositionSpan(spanStart, spanEnd)); } indexInLine = match.Index + match.Length; } lineBuilder.Append(line, indexInLine, line.Length - indexInLine); lines.Add(lineBuilder.ToString()); lineNumber = lineNumber + 1; } if (spanStartsStack.Count != 0) { var position = spanStartsStack.Peek(); var contextSnippet = GetExceptionContextSnippet(lines[position.Line], position.Character); var exceptionMessage = $"Unmatched span start at line {position.Line}, column {position.Character}: {contextSnippet}"; throw new ArgumentException(exceptionMessage, nameof(text)); } _text = string.Join(Environment.NewLine, lines); _positions = positionsBuilder.ToImmutable(); spansBuilder.Reverse(); _spans = spansBuilder.ToImmutable(); }
public DiagnosticResult WithLocation(string path, LinePosition location, DiagnosticLocationOptions options) => AppendSpan(new FileLinePositionSpan(path, location, location), options | DiagnosticLocationOptions.IgnoreLength);
private static void AnalyzeNode(SyntaxNodeAnalysisContext context, IUnitTestParser parser) { if (!parser.IsUnitTestMethod(context)) { return; } MethodDeclarationSyntax methodDeclaration = (MethodDeclarationSyntax)context.Node; IEnumerable <SyntaxNode> descendantNodes = methodDeclaration.Body.DescendantNodes(); if (!descendantNodes?.Any() ?? true) { return; } IEnumerable <MemberAccessExpressionSyntax> memberAccessExpressions = descendantNodes.OfType <MemberAccessExpressionSyntax>(); IEnumerable <ObjectCreationExpressionSyntax> ctorExpressions = descendantNodes.OfType <ObjectCreationExpressionSyntax>(); if (!memberAccessExpressions.Any() && !ctorExpressions.Any()) { return; } IEnumerable <SyntaxTrivia> singleLineComments = methodDeclaration.Body.DescendantTrivia().Where(trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)); IEnumerable <SyntaxTrivia> arrangeComments = singleLineComments.Where(comment => string.Equals("// Arrange.", comment.ToFullString())); IEnumerable <SyntaxTrivia> actComments = singleLineComments.Where(comment => string.Equals("// Act.", comment.ToFullString())); IEnumerable <SyntaxTrivia> assertComments = singleLineComments.Where(comment => string.Equals("// Assert.", comment.ToFullString())); Diagnostic diagnostic = null; LinePosition arrangeCommentLine = default(LinePosition); if (arrangeComments.Any()) { arrangeCommentLine = arrangeComments.First().GetLocation().GetLineSpan().StartLinePosition; } // Check to see whether each comment exists. Only a single instance of each comment should exist. if (arrangeComments.Count() != 1 || actComments.Count() != 1 || assertComments.Count() != 1) { diagnostic = Diagnostic.Create(AAACommentsRule, methodDeclaration.Identifier.GetLocation(), methodDeclaration.Identifier.ToString()); } else { // Check whether the comments appear with the expected order. LinePosition actCommentLine = actComments.First().GetLocation().GetLineSpan().StartLinePosition; LinePosition assertCommentLine = assertComments.First().GetLocation().GetLineSpan().StartLinePosition; if (arrangeCommentLine > actCommentLine || actCommentLine > assertCommentLine) { diagnostic = Diagnostic.Create(AAACommentsRule, methodDeclaration.Identifier.GetLocation(), methodDeclaration.Identifier.ToString()); } } if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } var methodOpenBrace = methodDeclaration.Body.ChildTokens().FirstOrDefault(token => token.IsKind(SyntaxKind.OpenBraceToken)); LinePosition openBraceLinePosition = methodOpenBrace.GetLocation().GetLineSpan().EndLinePosition; if (arrangeCommentLine.Line != openBraceLinePosition.Line + 1) { diagnostic = Diagnostic.Create(FirstLineArrangeRule, methodDeclaration.Identifier.GetLocation(), methodDeclaration.Identifier.ToString()); context.ReportDiagnostic(diagnostic); } }
/// <summary> /// Gets <see cref="DiagnosticData"/> objects for selected error list entries. /// For remove suppression, the method also returns selected external source diagnostics. /// </summary> public async Task<ImmutableArray<DiagnosticData>> GetSelectedItemsAsync(bool isAddSuppression, CancellationToken cancellationToken) { var builder = ImmutableArray.CreateBuilder<DiagnosticData>(); Dictionary<string, Project> projectNameToProjectMapOpt = null; Dictionary<Project, ImmutableDictionary<string, Document>> filePathToDocumentMapOpt = null; foreach (var entryHandle in _tableControl.SelectedEntries) { cancellationToken.ThrowIfCancellationRequested(); DiagnosticData diagnosticData = null; int index; var roslynSnapshot = GetEntriesSnapshot(entryHandle, out index); if (roslynSnapshot != null) { diagnosticData = roslynSnapshot.GetItem(index)?.Primary; } else if (!isAddSuppression) { // For suppression removal, we also need to handle FxCop entries. bool isSuppressedEntry; if (!IsNonRoslynEntrySupportingSuppressionState(entryHandle, out isSuppressedEntry) || !isSuppressedEntry) { continue; } string errorCode = null, category = null, message = null, filePath = null, projectName = null; int line = -1; // FxCop only supports line, not column. DiagnosticDataLocation location = null; if (entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCode, out errorCode) && !string.IsNullOrEmpty(errorCode) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCategory, out category) && !string.IsNullOrEmpty(category) && entryHandle.TryGetValue(StandardTableColumnDefinitions.Text, out message) && !string.IsNullOrEmpty(message) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ProjectName, out projectName) && !string.IsNullOrEmpty(projectName)) { if (projectNameToProjectMapOpt == null) { projectNameToProjectMapOpt = new Dictionary<string, Project>(); foreach (var p in _workspace.CurrentSolution.Projects) { projectNameToProjectMapOpt[p.Name] = p; } } cancellationToken.ThrowIfCancellationRequested(); Project project; if (!projectNameToProjectMapOpt.TryGetValue(projectName, out project)) { // bail out continue; } Document document = null; var hasLocation = (entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out filePath) && !string.IsNullOrEmpty(filePath)) && (entryHandle.TryGetValue(StandardTableColumnDefinitions.Line, out line) && line >= 0); if (hasLocation) { if (string.IsNullOrEmpty(filePath) || line < 0) { // bail out continue; } ImmutableDictionary<string, Document> filePathMap; filePathToDocumentMapOpt = filePathToDocumentMapOpt ?? new Dictionary<Project, ImmutableDictionary<string, Document>>(); if (!filePathToDocumentMapOpt.TryGetValue(project, out filePathMap)) { filePathMap = await GetFilePathToDocumentMapAsync(project, cancellationToken).ConfigureAwait(false); filePathToDocumentMapOpt[project] = filePathMap; } if (!filePathMap.TryGetValue(filePath, out document)) { // bail out continue; } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var linePosition = new LinePosition(line, 0); var linePositionSpan = new LinePositionSpan(start: linePosition, end: linePosition); var textSpan = (await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)).Lines.GetTextSpan(linePositionSpan); location = new DiagnosticDataLocation(document.Id, textSpan, filePath, originalStartLine: linePosition.Line, originalStartColumn: linePosition.Character, originalEndLine: linePosition.Line, originalEndColumn: linePosition.Character); } Contract.ThrowIfNull(project); Contract.ThrowIfFalse((document != null) == (location != null)); // Create a diagnostic with correct values for fields we care about: id, category, message, isSuppressed, location // and default values for the rest of the fields (not used by suppression fixer). diagnosticData = new DiagnosticData( id: errorCode, category: category, message: message, enuMessageForBingSearch: message, severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 1, isSuppressed: isSuppressedEntry, title: message, location: location, customTags: SuppressionHelpers.SynthesizedExternalSourceDiagnosticCustomTags, properties: ImmutableDictionary<string, string>.Empty, workspace: _workspace, projectId: project.Id); } } if (IsEntryWithConfigurableSuppressionState(diagnosticData)) { builder.Add(diagnosticData); } } return builder.ToImmutable(); }
public static string ReplaceToken(this string text, string token, string replacement, out LinePosition position) { var colOffset = -1; var lineOffset = -1; var reader = new StringReader(text); var builder = new StringBuilder(); var lineCount = 0; while (true) { var line = reader.ReadLine(); if (line == null) { break; } if (line.Contains(token)) { lineOffset = lineCount; colOffset = line.IndexOf(token); builder.AppendLine(line.Replace(token, replacement)); } else { builder.AppendLine(line); } lineCount++; } position = new LinePosition(lineOffset, colOffset); return(builder.ToString()); }
private static void Main(string[] args) { string assemblyName = "cls" + Guid.NewGuid().ToString("N"); //Path.GetRandomFileName(); var sourceCode = CreateSourceCode(assemblyName); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); var root = (CompilationUnitSyntax)syntaxTree.GetRoot(); NamespaceDeclarationSyntax namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(assemblyName)); var newCompilationUnit = SyntaxFactory.CompilationUnit() .AddMembers ( namespaceDeclaration .AddUsings(root.Usings.ToArray()) .AddMembers(root.Members[0]) ); syntaxTree = SyntaxFactory.SyntaxTree(newCompilationUnit); //CSharpSyntaxTree.Create(newCompilationUnit); var diagnostics = syntaxTree.GetDiagnostics().ToArray(); //if (root.Kind() == SyntaxKind.CompilationUnit) //{ // CompilationUnitSyntax compilationUnit = (CompilationUnitSyntax) root; // Do(compilationUnit.Members[0]); //} MetadataReference[] references = { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location) }; Compilation compilation = CSharpCompilation.Create ( assemblyName: assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.ConsoleApplication /*, mainTypeName: assemblyName + ".Program", usings: new[] { "System" }*/) ); byte[] bytes; var result = Emit(compilation, out bytes); if (result.Success) { Assembly assembly = Assembly.Load(/*ms.ToArray()*/ bytes); //var appType = assembly.GetType("App .Program"); //var mainMethod = appType.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, new Type[0], null); //var retVal = mainMethod.Invoke(null, null); assembly.EntryPoint.Invoke(null, new object[] { new[] { Environment.CurrentDirectory } }); } else { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { switch (diagnostic.Location.Kind) { case LocationKind.SourceFile: case LocationKind.XmlFile: case LocationKind.ExternalFile: FileLinePositionSpan lineSpan = diagnostic.Location.GetLineSpan(); FileLinePositionSpan mappedLineSpan = diagnostic.Location.GetMappedLineSpan(); if (lineSpan.IsValid && mappedLineSpan.IsValid) { string path; string basePath; if (mappedLineSpan.HasMappedPath) { path = mappedLineSpan.Path; basePath = lineSpan.Path; } else { path = lineSpan.Path; basePath = (string)null; } //return string.Format(formatter, "{0}{1}: {2}: {3}", (object)this.FormatSourcePath(path, basePath, formatter), (object)this.FormatSourceSpan(mappedLineSpan.Span, formatter), (object)this.GetMessagePrefix(diagnostic), (object)diagnostic.GetMessage((IFormatProvider)cultureInfo)); } break; } Location location = diagnostic.Location; LinePosition startPosition = location.GetMappedLineSpan().Span.Start; TextSpan sourceSpan = location.SourceSpan; var location1 = location.SourceTree.GetLineSpan(sourceSpan); var sourceText = location.SourceTree.GetText().Lines.GetLineFromPosition(location.SourceSpan.Start).ToString().Substring(8, 7); Console.Error.WriteLine($"({startPosition.Line + 1},{startPosition.Character + 1}) {diagnostic.Id} : {diagnostic.GetMessage()}"); } } }
public DiagnosticResult WithLocation(string path, LinePosition location) => AppendSpan(new FileLinePositionSpan(path, location, location));
/// <summary>Line is drawn in 50% of the available space.</summary> public void AddLine(string name,string sectionName,Color color,float floatLineThickness,LineOrientation lineOrientation,LinePosition linePosition) { AddLine(name,sectionName,color,floatLineThickness,lineOrientation,linePosition,50,0,0); }
public int Compile(List <ClassDefinition> classDefinitions) { if (programAsset.sourceCsScript == null) { throw new System.ArgumentException($"Asset '{AssetDatabase.GetAssetPath(programAsset)}' does not have a valid program source to compile from"); } Profiler.BeginSample("Compile Module"); programAsset.compileErrors.Clear(); sourceCode = File.ReadAllText(AssetDatabase.GetAssetPath(programAsset.sourceCsScript)); Profiler.BeginSample("Parse AST"); SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode); Profiler.EndSample(); int errorCount = 0; string errorString = ""; foreach (Diagnostic diagnostic in tree.GetDiagnostics()) { if (diagnostic.Severity == DiagnosticSeverity.Error) { errorCount++; LinePosition linePosition = diagnostic.Location.GetLineSpan().StartLinePosition; errorString = UdonSharpUtils.LogBuildError($"error {diagnostic.Descriptor.Id}: {diagnostic.GetMessage()}", AssetDatabase.GetAssetPath(programAsset.sourceCsScript).Replace("/", "\\"), linePosition.Line, linePosition.Character); programAsset.compileErrors.Add(errorString); } } if (errorCount > 0) { ErrorCount = errorCount; Profiler.EndSample(); return(errorCount); } Profiler.BeginSample("Visit"); UdonSharpFieldVisitor fieldVisitor = new UdonSharpFieldVisitor(fieldsWithInitializers); fieldVisitor.Visit(tree.GetRoot()); MethodVisitor methodVisitor = new MethodVisitor(resolver, moduleSymbols, moduleLabels); methodVisitor.Visit(tree.GetRoot()); UdonSharpSettings settings = UdonSharpSettings.GetSettings(); ClassDebugInfo debugInfo = null; if (settings == null || settings.buildDebugInfo) { debugInfo = new ClassDebugInfo(sourceCode, settings == null || settings.includeInlineCode); } ASTVisitor visitor = new ASTVisitor(resolver, moduleSymbols, moduleLabels, methodVisitor.definedMethods, classDefinitions, debugInfo); try { visitor.Visit(tree.GetRoot()); visitor.VerifyIntegrity(); } catch (System.Exception e) { SyntaxNode currentNode = visitor.visitorContext.currentNode; string logMessage = ""; if (currentNode != null) { FileLinePositionSpan lineSpan = currentNode.GetLocation().GetLineSpan(); logMessage = UdonSharpUtils.LogBuildError($"{e.GetType()}: {e.Message}", AssetDatabase.GetAssetPath(programAsset.sourceCsScript).Replace("/", "\\"), lineSpan.StartLinePosition.Line, lineSpan.StartLinePosition.Character); } else { logMessage = e.ToString(); Debug.LogException(e); } programAsset.compileErrors.Add(logMessage); errorCount++; } Profiler.EndSample(); if (errorCount == 0) { Profiler.BeginSample("Build assembly"); string dataBlock = BuildHeapDataBlock(); string codeBlock = visitor.GetCompiledUasm(); programAsset.SetUdonAssembly(dataBlock + codeBlock); Profiler.EndSample(); Profiler.BeginSample("Assemble Program"); programAsset.AssembleCsProgram((uint)(moduleSymbols.GetAllUniqueChildSymbols().Count + visitor.GetExternStrCount())); Profiler.EndSample(); programAsset.behaviourIDHeapVarName = visitor.GetIDHeapVarName(); programAsset.fieldDefinitions = visitor.visitorContext.localFieldDefinitions; if (debugInfo != null) { debugInfo.FinalizeDebugInfo(); } programAsset.debugInfo = debugInfo; } Profiler.EndSample(); return(errorCount); }
private static LinePosition Max(LinePosition position1, LinePosition position2) { return(position1 > position2 ? position1 : position2); }
private static void SwapIfNeeded(ref LinePosition startLinePosition, ref LinePosition endLinePosition) { if (endLinePosition < startLinePosition) { var temp = startLinePosition; startLinePosition = endLinePosition; endLinePosition = temp; } }