// Populate the treeview with the contents of the SyntaxTree corresponding to the code document // that is currently active in the editor. private void RefreshSyntaxVisualizer() { if (IsVisible && activeWpfTextView != null) { var snapshot = activeWpfTextView.TextBuffer.CurrentSnapshot; var contentType = snapshot.ContentType; if (contentType.IsOfType(ContentTypeNames.VisualBasicContentType) || contentType.IsOfType(ContentTypeNames.CSharpContentType)) { var text = snapshot.AsText(); IDocument document; // Get the Document corresponding to the currently active text snapshot. if (text.TryGetDocument(out document)) { // Get the SyntaxTree corresponding to the Document. activeSyntaxTree = document.GetSyntaxTree(); // Display the SyntaxTree. if (contentType.IsOfType(ContentTypeNames.VisualBasicContentType)) { syntaxVisualizer.DisplaySyntaxTree(activeSyntaxTree, LanguageNames.VisualBasic); } else if (contentType.IsOfType(ContentTypeNames.CSharpContentType)) { syntaxVisualizer.DisplaySyntaxTree(activeSyntaxTree, LanguageNames.CSharp); } NavigateFromSource(); } } } }
public AnalysisResult Analyze(CommonSyntaxTree syntaxTree, SemanticModel semanticModel) { List<ClassDeclarationSyntax> classDeclarations = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ToList(); List<ClassInfo> classInfos = InspectClassDeclarations(semanticModel, classDeclarations); List<Issue> issues = new List<Issue>(); foreach (ClassInfo classInfo in classInfos) { foreach (IAnalysisRule rule in _ruleProvider.Rules) { AnalysisResult result = rule.Analyze(syntaxTree, semanticModel, classInfo); if (!result.Success) { issues.AddRange(result.Issues); } } } if (issues.Count > 0) { return new AnalysisResult(issues); } else { return AnalysisResult.Succeeded; } }
/// <summary> /// Gets a document location from a tree node. /// </summary> /// <param name="tree">The tree.</param> /// <param name="node">The node.</param> /// <returns>A new document location.</returns> internal static DocumentLocation FromTreeNode(CommonSyntaxTree tree, CommonSyntaxNode node) { if (tree == null || node == null) return Default; return FromSpan(tree.GetLineSpan(node.Span, true)); }
internal static void ReplaceBasic() { IProject proj = ProtoTestProj; foreach (var doc in proj.Documents) { CommonSyntaxTree syntax = doc.GetSyntaxTree(); FileTree = syntax; FileRoot = (CompilationUnitSyntax)syntax.GetRoot(); bool containingMethodToReplace = true; while (containingMethodToReplace) { containingMethodToReplace = SearchAndReplaceMethodsForTextCSharp(doc, "thisTest.Verify"); FileTree = SyntaxTree.Create(FileRoot); FileRoot = (CompilationUnitSyntax)FileTree.GetRoot(); } var UsingStmtForDict = Syntax.QualifiedName(Syntax.IdentifierName("System.Collections"), Syntax.IdentifierName("Generic")); FileRoot = FileRoot.AddUsings(Syntax.UsingDirective(UsingStmtForDict).NormalizeWhitespace()).NormalizeWhitespace(); File.WriteAllText(doc.FilePath, FileRoot.ToString()); //Console.WriteLine(result); } }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { //TODO: Refactor this whole method later and make it more robust if (classInfo.GuardedFields.Count <= 1) { return AnalysisResult.Succeeded; } foreach (GuardedFieldInfo first in classInfo.GuardedFields) { foreach (GuardedFieldInfo second in classInfo.GuardedFields) { if (first == second) { continue; } if (LockHierarchy.Conflicts(first.DeclaredLockHierarchy, second.DeclaredLockHierarchy)) { return new AnalysisResult(new Issue( ErrorCode.GUARDED_FIELD_LOCK_HIERARCHY_DECLARATION_CONFLICT, second.Declaration, second.Symbol)); } } } return AnalysisResult.Succeeded; }
// explicit interface implementation void ISyntaxValidator.Validate(CommonSyntaxNode node, CommonSyntaxTree tree, CompilationResult result) { _currentTree = tree; _currentNode = node; _currentResult = result; Validate(node as T, tree, result); }
/// <summary> /// Creates a new exception, from a syntactic model. /// </summary> /// <param name="message">The error message.</param> /// <param name="model">The model.</param> public CompilationException(string message, ISyntacticModel model) : base(message) { if (model != null) { RelatedNode = model.OriginatingNode; RelatedTree = model.OriginatingTree; } }
public static List <ILocation> SourceLocation(CommonSyntaxTree tree, Microsoft.CodeAnalysis.CSharp.SyntaxToken token) { var s = new SourceLocationWrapper(tree, token.Span); var l = (ILocation)s; return(new List <ILocation> { l }); }
/// <summary> /// Gets a document location from a tree node. /// </summary> /// <param name="tree">The tree.</param> /// <param name="node">The node.</param> /// <returns>A new document location.</returns> internal static DocumentLocation FromTreeNode(CommonSyntaxTree tree, CommonSyntaxNode node) { if (tree == null || node == null) { return(Default); } return(FromSpan(tree.GetLineSpan(node.Span, true))); }
// If lazy is true then treeview items are populated on-demand. In other words, when lazy is true // the children for any given item are only populated when the item is selected. If lazy is // false then the entire tree is populated at once (and this can result in bad performance when // displaying large trees). public void DisplaySyntaxTree(CommonSyntaxTree tree, string language, bool lazy = true) { if (tree != null && !string.IsNullOrEmpty(language)) { SourceLanguage = language; IsLazy = lazy; SyntaxTree = tree; AddNode(null, SyntaxTree.Root); legendButton.Visibility = Visibility.Visible; } }
internal void Clear() { if (activeWpfTextView != null) { activeWpfTextView.Selection.SelectionChanged -= HandleSelectionChanged; activeWpfTextView.TextBuffer.Changed -= HandleTextBufferChanged; activeWpfTextView = null; } activeSyntaxTree = null; syntaxVisualizer.Clear(); }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { if (classInfo.HasThreadSafeAttribute == false && classInfo.GuardedFields.Count > 0) { return new AnalysisResult(new Issue( ErrorCode.GUARDED_FIELD_IN_A_NON_THREAD_SAFE_CLASS, classInfo.Declaration, classInfo.Symbol)); } return AnalysisResult.Succeeded; }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { if (classInfo.HasThreadSafeAttribute && classInfo.Declaration.Modifiers.Any(SyntaxKind.PartialKeyword)) { return new AnalysisResult(new Issue( ErrorCode.CLASS_CANNOT_BE_PARTIAL, classInfo.Declaration, classInfo.Symbol)); } return AnalysisResult.Succeeded; }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { if (classInfo.HasThreadSafeAttribute && classInfo.Symbol.IsAbstract) { return new AnalysisResult(new Issue( ErrorCode.CLASS_CANNOT_BE_ABSTRACT, classInfo.Declaration, classInfo.Symbol)); } return AnalysisResult.Succeeded; }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { foreach (GuardedFieldInfo guardedField in classInfo.GuardedFields) { if (guardedField.DeclaredLockHierarchy.Any() == false) { return new AnalysisResult(new Issue( ErrorCode.GUARDED_FIELD_NOT_ASSOCIATED_WITH_A_LOCK, guardedField.Declaration, guardedField.Symbol)); } } return AnalysisResult.Succeeded; }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { foreach (GuardedFieldInfo fieldInfo in classInfo.GuardedFields) { if (fieldInfo.Symbol.DeclaredAccessibility != Accessibility.Private) { return new AnalysisResult(new Issue( ErrorCode.GUARDED_FIELD_IS_NOT_PRIVATE, fieldInfo.Declaration, fieldInfo.Symbol)); } } return AnalysisResult.Succeeded; }
// If lazy is true then treeview items are populated on-demand. In other words, when lazy is true // the children for any given item are only populated when the item is selected. If lazy is // false then the entire tree is populated at once (and this can result in bad performance when // displaying large trees). public void DisplaySyntaxTree(CommonSyntaxTree tree, string language, bool lazy = true) { if (tree != null && !string.IsNullOrEmpty(language)) { SourceLanguage = language; IsLazy = lazy; SyntaxTree = tree; AddNode(root, SyntaxTree.GetRoot()); if (SyntaxTreeLoaded != null && SyntaxTree != null) { SyntaxTreeLoaded(this, new SyntaxLoadedArgs(SyntaxTree.GetRoot())); } } }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { foreach (GuardedFieldInfo guardedField in classInfo.GuardedFields) { if (guardedField.DeclaredLockHierarchy.Distinct().Count() != guardedField.DeclaredLockHierarchy.Count) { return new AnalysisResult(new Issue( ErrorCode.GUARDED_FIELD_USES_SAME_LOCK_MORE_THAN_ONCE, guardedField.Declaration, guardedField.Symbol)); } } return AnalysisResult.Succeeded; }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { foreach (LockInfo lockInfo in classInfo.Locks) { if (lockInfo.Symbol.Type.SpecialType != Roslyn.Compilers.SpecialType.System_Object) { return new AnalysisResult(new Issue( ErrorCode.LOCK_MUST_BE_SYSTEM_OBJECT, lockInfo.Declaration, lockInfo.Symbol)); } } return AnalysisResult.Succeeded; }
/// <summary> /// Validates the syntax node. /// </summary> /// <param name="node">The node to validate.</param> /// <param name="tree">The tree containing the node.</param> /// <param name="result">The compilation result.</param> public override void Validate(ClassDeclarationSyntax node, CommonSyntaxTree tree, CompilationResult result) { // check for overloaded constructors var ctors = node.Members.OfType <ConstructorDeclarationSyntax>(); var ctorCount = ctors.Count(); if (ctors.Any(c => c.Modifiers.Any(m => m.ValueText == "static"))) { ctorCount--; } if (ctorCount > 1) { AddError("Constructor overloading is not supported. Consider using optional parameters instead."); } }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { if (classInfo.HasThreadSafeAttribute) { if (classInfo.GuardedFields.Count == 0 || classInfo.Locks.Count == 0) { return new AnalysisResult(new Issue( ErrorCode.CLASS_MUST_HAVE_LOCKS_OR_GUARDED_FIELDS, classInfo.Declaration, classInfo.Symbol)); } } return AnalysisResult.Succeeded; }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { foreach (var guardedField in classInfo.GuardedFields) { //Check to see if all of the locks are actually declared foreach (string lockName in guardedField.DeclaredLockHierarchy) { if (classInfo.Locks.Any(@lock => @lock.Name == lockName) == false) { return new AnalysisResult(new Issue( ErrorCode.GUARDED_FIELD_REFERENCES_UNKNOWN_LOCK, guardedField.Declaration, guardedField.Symbol)); } } } return AnalysisResult.Succeeded; }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { //Get the list of all lock names that are declared on guarded fields IEnumerable<string> requiredLockNames = classInfo.GuardedFields.SelectMany(field => field.DeclaredLockHierarchy).ToList(); //Check that all locks actually protect something foreach (LockInfo lockInfo in classInfo.Locks) { //see if the current lock is used by any guarded members if (requiredLockNames.Any(rln => rln == lockInfo.Name) == false) { return new AnalysisResult(new Issue( ErrorCode.LOCK_PROTECTS_NOTHING, lockInfo.Declaration, lockInfo.Symbol)); } } return AnalysisResult.Succeeded; }
internal SyntaxTransporter(CommonSyntaxTree tree) { SyntaxStream = new MemoryStream(); if (tree is CSharp.SyntaxTree) { SourceLanguage = LanguageNames.CSharp; var csharpTree = (CSharp.SyntaxTree)tree; csharpTree.GetRoot().SerializeTo(SyntaxStream); } else { SourceLanguage = LanguageNames.VisualBasic; var vbTree = (VisualBasic.SyntaxTree)tree; vbTree.GetRoot().SerializeTo(SyntaxStream); } ItemSpan = tree.GetRoot().Span; ItemKind = tree.GetRoot().GetKind(SourceLanguage); ItemCategory = SyntaxCategory.SyntaxNode; }
//From http://www.dotnetexpertguide.com/2011/10/c-sharp-syntax-checker-aspnet-roslyn.html public override ValidateCodeResult ValidateCode(string code) { var result = new ValidateCodeResult(); result.IsSuccess = true; CommonSyntaxTree tree = this.ParseSyntaxTree(code); var syntaxDiagnostics = tree.GetDiagnostics().ToList(); var semanticTree = this.GetSemanticModelFromSyntaxTree(tree, code); var semanticDiagnostics = semanticTree.GetDiagnostics().ToList(); int numLines = code.Split('\n').Length; this.AddErrorsFromDiagnostics(syntaxDiagnostics, numLines, result); this.AddErrorsFromDiagnostics(semanticDiagnostics, numLines, result, true); return(result); }
// Populate the treeview with the contents of the SyntaxTree corresponding to the code document // that is currently active in the editor. protected virtual void RefreshSyntaxVisualizer() { if (IsVisible && activeWpfTextView != null && WorkspaceDiscoveryService != null) { var snapshot = activeWpfTextView.TextBuffer.CurrentSnapshot; var contentType = snapshot.ContentType; if (contentType.IsOfType(ContentTypeNames.VisualBasicContentType) || contentType.IsOfType(ContentTypeNames.CSharpContentType)) { var text = snapshot.AsText(); // Get the Workspace corresponding to the currently active text snapshot. var workspace = WorkspaceDiscoveryService.GetWorkspace(text.Container); if (workspace != null) { IDocument document; // Get the Document corresponding to the currently active text snapshot. if (workspace.TryGetDocumentFromInProgressSolution(text, out document) && document != null) { // Get the SyntaxTree corresponding to the Document. activeSyntaxTree = document.GetSyntaxTree(); // Display the SyntaxTree. if (contentType.IsOfType(ContentTypeNames.VisualBasicContentType)) { syntaxVisualizer.DisplaySyntaxTree(activeSyntaxTree, LanguageNames.VisualBasic); } else if (contentType.IsOfType(ContentTypeNames.CSharpContentType)) { syntaxVisualizer.DisplaySyntaxTree(activeSyntaxTree, LanguageNames.CSharp); } NavigateFromSource(); } } } } }
public AnalysisResult Analyze(CommonSyntaxTree tree, SemanticModel model, ClassInfo classInfo) { if (classInfo.HasThreadSafeAttribute == false || classInfo.GuardedFields.Count == 0 || classInfo.Locks.Count == 0) { return AnalysisResult.Succeeded; } foreach (MemberInfo memberInfo in classInfo.Members) { Issue issue = AnalyzeMember(memberInfo, model, classInfo); if (issue != null) { return new AnalysisResult(issue); } } return AnalysisResult.Succeeded; }
/// <summary> /// Creates a new exception, with a locatable message. /// </summary> /// <param name="message">The error message.</param> /// <param name="node">The related syntax node.</param> /// <param name="tree">The related syntax tree.</param> public CompilationException(string message, CommonSyntaxNode node, CommonSyntaxTree tree) : base(message) { RelatedNode = node; RelatedTree = tree; }
public override CommonCompilation CreateCompilation(string compilatioName, CommonSyntaxTree[] syntaxTrees, List<MetadataReference> metadataReferences) { var csharpSyntaxTrees = new List<SyntaxTree>(); foreach (var syntaxTree in syntaxTrees) csharpSyntaxTrees.Add((SyntaxTree) syntaxTree); Compilation compilation = Compilation.Create( compilatioName, syntaxTrees: csharpSyntaxTrees.ToArray(), references: metadataReferences); return compilation; }
private ISemanticModel GetSemanticModelFromSyntaxTree(CommonSyntaxTree syntaxTree, string code, bool includeDocumentation = false) { _systemXmlFilesDir = GetSystemXmlFilesDir(); MetadataReference mscorlib = CreateMetadataReference("mscorlib", includeDocumentation); var metaDllReferences = new List<MetadataReference> {mscorlib}; if (this.Language == Language.VbNet) { //Need to add vb or getting error //Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. MetadataReference vb = CreateMetadataReference("Microsoft.VisualBasic", includeDocumentation); metaDllReferences.Add(vb); } //Eric: this doesn't seem to work so using mscorlib only for now. List<string> gacDlls = GetGacDlls(code); foreach (string dllName in gacDlls) { string dllNameWithoutExtension = dllName.Substring(0, dllName.Length - 4); //remove .dll MetadataReference metaRef = CreateMetadataReference(dllNameWithoutExtension, includeDocumentation); metaDllReferences.Add(metaRef); } Dictionary <string, string> nugGetXmlFileNameToPath = new Dictionary<string, string>(); if (includeDocumentation) foreach (var nuGetxmlFilePath in NuGetXmlFileReferences) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(nuGetxmlFilePath); nugGetXmlFileNameToPath[fileNameWithoutExtension] = nuGetxmlFilePath; } foreach (var path in GetNonGacDlls()) { string fileName = Path.GetFileNameWithoutExtension(path); RoslynDocumentationProvider documentationProvider = null; if (includeDocumentation && nugGetXmlFileNameToPath.ContainsKey(fileName)) documentationProvider = new RoslynDocumentationProvider(nugGetXmlFileNameToPath[fileName]); var reference = new MetadataFileReference(path, MetadataReferenceProperties.Assembly, documentationProvider); metaDllReferences.Add(reference); } //http://msdn.microsoft.com/en-us/vstudio/hh500769.aspx#Toc306015688 CommonCompilation compilation = this.CreateCompilation("Compilation_For_AutoComplete", syntaxTrees: new[] {syntaxTree}, matadataReferences: metaDllReferences); ISemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree); return semanticModel; }
public abstract CommonCompilation CreateCompilation(string compilatioName, CommonSyntaxTree[] syntaxTrees, List<MetadataReference> matadataReferences);
/// <summary> /// Validates the syntax node. /// </summary> /// <param name="node">The node to validate.</param> /// <param name="tree">The tree containing the node.</param> /// <param name="result">The compilation result.</param> public override void Validate(StructDeclarationSyntax node, CommonSyntaxTree tree, CompilationResult result) { AddError("Struct declarations are not supported. Consider using a Class declaration instead."); }
public static List<ILocation> SourceLocation(CommonSyntaxTree tree, Microsoft.CodeAnalysis.CSharp.SyntaxToken token) { var s = new SourceLocationWrapper(tree, token.Span); var l = (ILocation)s; return new List<ILocation> { l }; }
public SourceLocationWrapper(CommonSyntaxTree tree, Microsoft.CodeAnalysis.Text.TextSpan span) { this.tree = tree; this.span = span; }
/// <summary> /// Validates the syntax node. /// </summary> /// <param name="node">The node to validate.</param> /// <param name="tree">The tree containing the node.</param> /// <param name="result">The compilation result.</param> public abstract void Validate(T node, CommonSyntaxTree tree, CompilationResult result);
private ISemanticModel GetSemanticModelFromSyntaxTree(CommonSyntaxTree syntaxTree, string code, bool includeDocumentation = false) { _systemXmlFilesDir = GetSystemXmlFilesDir(); MetadataReference mscorlib = CreateMetadataReference("mscorlib", includeDocumentation); var metaDllReferences = new List <MetadataReference> { mscorlib }; if (this.Language == Language.VbNet) { //Need to add vb or getting error //Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. MetadataReference vb = CreateMetadataReference("Microsoft.VisualBasic", includeDocumentation); metaDllReferences.Add(vb); } //Eric: this doesn't seem to work so using mscorlib only for now. List <string> gacDlls = GetGacDlls(code); foreach (string dllName in gacDlls) { string dllNameWithoutExtension = dllName.Substring(0, dllName.Length - 4); //remove .dll MetadataReference metaRef = CreateMetadataReference(dllNameWithoutExtension, includeDocumentation); metaDllReferences.Add(metaRef); } Dictionary <string, string> nugGetXmlFileNameToPath = new Dictionary <string, string>(); if (includeDocumentation) { foreach (var nuGetxmlFilePath in NuGetXmlFileReferences) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(nuGetxmlFilePath); nugGetXmlFileNameToPath[fileNameWithoutExtension] = nuGetxmlFilePath; } } foreach (var path in GetNonGacDlls()) { string fileName = Path.GetFileNameWithoutExtension(path); RoslynDocumentationProvider documentationProvider = null; if (includeDocumentation && nugGetXmlFileNameToPath.ContainsKey(fileName)) { documentationProvider = new RoslynDocumentationProvider(nugGetXmlFileNameToPath[fileName]); } var reference = new MetadataFileReference(path, MetadataReferenceProperties.Assembly, documentationProvider); metaDllReferences.Add(reference); } //http://msdn.microsoft.com/en-us/vstudio/hh500769.aspx#Toc306015688 CommonCompilation compilation = this.CreateCompilation("Compilation_For_AutoComplete", syntaxTrees: new[] { syntaxTree }, matadataReferences: metaDllReferences); ISemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree); return(semanticModel); }