コード例 #1
0
            static bool InAttributeContainingCSharp(
                Diagnostic d,
                SourceText sourceText,
                RazorSyntaxTree syntaxTree,
                Dictionary <TextSpan, bool> processedAttributes)
            {
                // Examine the _end_ of the diagnostic to see if we're at the
                // start of an (im/ex)plicit expression. Looking at the start
                // of the diagnostic isn't sufficient.
                var absoluteIndex = d.Range.End.GetAbsoluteIndex(sourceText);
                var change        = new SourceChange(absoluteIndex, 0, string.Empty);
                var owner         = syntaxTree.Root.LocateOwner(change);

                var markupAttributeNode = owner.FirstAncestorOrSelf <RazorSyntaxNode>(n =>
                                                                                      n is MarkupAttributeBlockSyntax ||
                                                                                      n is MarkupTagHelperAttributeSyntax ||
                                                                                      n is MarkupMiscAttributeContentSyntax);

                if (markupAttributeNode != null)
                {
                    if (!processedAttributes.TryGetValue(markupAttributeNode.FullSpan, out var doesAttributeContainNonMarkup))
                    {
                        doesAttributeContainNonMarkup = CheckIfAttributeContainsNonMarkupNodes(markupAttributeNode);
                        processedAttributes.Add(markupAttributeNode.FullSpan, doesAttributeContainNonMarkup);
                    }

                    return(doesAttributeContainNonMarkup);
                }

                return(false);
            }
コード例 #2
0
        public override bool IsTriggerCharacter(Microsoft.CodeAnalysis.Text.SourceText text, int position)
        {
            var ch = text [position];

            return(ch == '#' ||
                   ch == ' ' && position >= 1 && !char.IsWhiteSpace(text [position - 1]) ||
                   IsStartingNewWord(text, position));
        }
コード例 #3
0
 public void Execute(GeneratorExecutionContext context)
 {
     if (context.Compilation is CSharpCompilation compilation)
     {
         var cu = this.Generate(context);
         if (cu is object)
         {
             Microsoft.CodeAnalysis.Text.SourceText sourceText = cu.GetText(System.Text.Encoding.UTF8);
             context.AddSource("Property.generated.cs", sourceText);
         }
     }
 }
コード例 #4
0
        private static bool InCSharpLiteral(OmniSharpVSDiagnostic d, SourceText sourceText, RazorSyntaxTree syntaxTree)
        {
            if (d.Range is null)
            {
                return(false);
            }

            var owner = syntaxTree.GetOwner(sourceText, d.Range.End);

            if (owner is null)
            {
                return(false);
            }

            var isCSharp = owner.Kind is SyntaxKind.CSharpExpressionLiteral or SyntaxKind.CSharpStatementLiteral or SyntaxKind.CSharpEphemeralTextLiteral;

            return(isCSharp);
        }
コード例 #5
0
        private static OmniSharpVSDiagnostic[] FilterHTMLDiagnostics(
            OmniSharpVSDiagnostic[] unmappedDiagnostics,
            RazorCodeDocument codeDocument,
            SourceText sourceText)
        {
            var syntaxTree = codeDocument.GetSyntaxTree();

            var processedAttributes = new Dictionary <TextSpan, bool>();

            var filteredDiagnostics = unmappedDiagnostics
                                      .Where(d =>
                                             !InCSharpLiteral(d, sourceText, syntaxTree) &&
                                             !InAttributeContainingCSharp(d, sourceText, syntaxTree, processedAttributes) &&
                                             !AppliesToTagHelperTagName(d, sourceText, syntaxTree) &&
                                             !ShouldFilterHtmlDiagnosticBasedOnErrorCode(d, sourceText, syntaxTree))
                                      .ToArray();

            return(filteredDiagnostics);
        }
コード例 #6
0
        private static bool AppliesToTagHelperTagName(
            OmniSharpVSDiagnostic diagnostic,
            SourceText sourceText,
            RazorSyntaxTree syntaxTree,
            ILogger logger)
        {
            // Goal of this method is to filter diagnostics that touch TagHelper tag names. Reason being is TagHelpers can output anything. Meaning
            // If you have a TagHelper like:
            //
            // <Input>
            // </Input>
            //
            // HTML would see this as an error because the input element can't have a body; however, a TagHelper could respect this in a totally valid
            // way.

            if (diagnostic.Range is null)
            {
                return(false);
            }

            var owner = syntaxTree.GetOwner(sourceText, diagnostic.Range.End, logger);

            var startOrEndTag = owner?.FirstAncestorOrSelf <RazorSyntaxNode>(n => n is MarkupTagHelperStartTagSyntax || n is MarkupTagHelperEndTagSyntax);

            if (startOrEndTag is null)
            {
                return(false);
            }

            var tagName      = startOrEndTag is MarkupTagHelperStartTagSyntax startTag ? startTag.Name : ((MarkupTagHelperEndTagSyntax)startOrEndTag).Name;
            var tagNameRange = tagName.GetRange(syntaxTree.Source);

            if (!tagNameRange.IntersectsOrTouches(diagnostic.Range))
            {
                // The diagnostic doesn't touch the tag name
                return(false);
            }

            // Diagnostic is touching the start or end tag name range
            return(true);
        }
コード例 #7
0
        private static bool ShouldFilterHtmlDiagnosticBasedOnErrorCode(Diagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
        {
            if (!diagnostic.Code.HasValue)
            {
                return(false);
            }

            return(diagnostic.Code.Value.String switch
            {
                HtmlErrorCodes.InvalidNestingErrorCode => IsInvalidNestingWarningWithinComponent(diagnostic, sourceText, syntaxTree),
                HtmlErrorCodes.MissingEndTagErrorCode => FileKinds.IsComponent(syntaxTree.Options.FileKind), // Redundant with RZ9980 in Components
                _ => false,
            });
コード例 #8
0
        // static readonly ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders.NewKeywordRecommender nkr = new ICSharpCode.NRefactory6.CSharp.Completion.KeywordRecommenders.NewKeywordRecommender ();

        public override bool IsTriggerCharacter(Microsoft.CodeAnalysis.Text.SourceText text, int position)
        {
            return(IsTriggerAfterSpaceOrStartOfWordCharacter(text, position));
        }
コード例 #9
0
        /// <summary>
        /// Main scan method: resolve and load dependencies, run roslyn compiler, emit defs and refs
        /// </summary>
        /// <param name="context">Project context.</param>
        internal static async Task <Output> Graph(GraphContext context)
        {
            if (context.Project == null)
            {
                Project project;
                if (!Project.TryGetProject(context.ProjectDirectory, out project))
                {
                    //not a DNX project
                    DirectoryInfo di    = new DirectoryInfo(context.ProjectDirectory);
                    FileInfo[]    fis   = DepresolveConsoleCommand.FindSources(di);
                    string[]      files = new string[fis.Length];
                    for (int i = 0; i < fis.Length; i++)
                    {
                        files[i] = fis[i].FullName;
                    }
                    Microsoft.CodeAnalysis.Text.SourceText[] sources = new Microsoft.CodeAnalysis.Text.SourceText[files.Length];
                    SyntaxTree[] trees = new SyntaxTree[files.Length];
                    Dictionary <SyntaxTree, string> dict = new Dictionary <SyntaxTree, string>();
                    var compilation = CSharpCompilation.Create("name");
                    for (int i = 0; i < files.Length; i++)
                    {
                        try
                        {
                            FileStream source = new FileStream(files[i], FileMode.Open);
                            sources[i] = Microsoft.CodeAnalysis.Text.SourceText.From(source);
                            trees[i]   = CSharpSyntaxTree.ParseText(sources[i]);
                            if (trees[i] != null)
                            {
                                compilation    = compilation.AddSyntaxTrees(trees[i]);
                                dict[trees[i]] = files[i];
                            }
                            source.Dispose();
                        }
                        catch (Exception e)
                        {
                        }
                    }

                    var gr = new GraphRunner();
                    foreach (var st in compilation.SyntaxTrees)
                    {
                        var path = dict[st];
                        if (!string.IsNullOrWhiteSpace(path))
                        {
                            path = Utils.GetRelativePath(path, context.ProjectDirectory);
                            if (!string.IsNullOrWhiteSpace(path) && (path.Substring(0, 3) != ".." + Path.DirectorySeparatorChar) && !path.Equals("file://applyprojectinfo.cs/"))
                            {
                                // this is a source code file we want to grap
                                gr._sm   = compilation.GetSemanticModel(st, false);
                                gr._path = path;
                                var root = await st.GetRootAsync();

                                gr.Visit(root);
                            }
                        }
                    }
                    gr._sm   = null;
                    gr._path = null;
                    gr.RunTokens();
                    return(gr._output);
                }

                context.Project = project;
            }

            if (context.Project.GetTargetFrameworks().Count() == 0)
            {
                return(new Output());
            }
            context.ApplicationHostContext = new ApplicationHostContext
            {
                ProjectDirectory = context.ProjectDirectory,
                Project          = context.Project,
                TargetFramework  = context.Project.GetTargetFrameworks().First().FrameworkName
            };

            context.ApplicationEnvironment = new ApplicationEnvironment(
                context.Project,
                context.ApplicationHostContext.TargetFramework,
                "Debug",
                context.HostEnvironment);

            context.CompilationContext = new CompilationEngineContext(context.ApplicationEnvironment, context.RuntimeEnvironment, context.LoadContextAccessor.Default, new CompilationCache());

            context.CompilationEngine = new CompilationEngine(context.CompilationContext);
            context.LibraryExporter   = context.CompilationEngine.CreateProjectExporter(context.Project, context.ApplicationHostContext.TargetFramework, "Debug");
            context.Export            = context.LibraryExporter.GetExport(context.Project.Name);

            if (!(context.Export.MetadataReferences[0] is IRoslynMetadataReference))
            {
                return(new Output());
            }
            var roslynRef      = (IRoslynMetadataReference)context.Export.MetadataReferences[0];
            var compilationRef = (CompilationReference)roslynRef.MetadataReference;
            var csCompilation  = (CSharpCompilation)compilationRef.Compilation;

            context.Compilation = csCompilation;

            IEnumerable <LibraryDescription>      deps = DepresolveConsoleCommand.DepResolve(context.Project);
            HashSet <PortableExecutableReference> libs = new HashSet <PortableExecutableReference>();

            try
            {
                if (File.Exists(context.ProjectDirectory + "/global.log"))
                {
                    string[] ss = File.ReadAllLines(context.ProjectDirectory + "/global.log");
                    foreach (string s in ss)
                    {
                        libs.Add(MetadataReference.CreateFromFile(s));
                    }
                }
                libs.Add(MetadataReference.CreateFromFile("/opt/DNX_BRANCH/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin/mscorlib.dll"));
            }
            catch (Exception e)
            {
            }
            foreach (LibraryDescription ld in deps)
            {
                PortableExecutableReference r = null;
                try
                {
                    string path = "";
                    if (ld.Path.EndsWith("project.json") && (ld.Path.IndexOf("wrap") != -1))
                    {
                        if (File.Exists(ld.Path))
                        {
                            var content = File.ReadAllText(ld.Path);
                            var spec    = JsonConvert.DeserializeObject <Wrap>(content);
                            path = ld.Path.Substring(0, ld.Path.Length - 12) + spec.frameworks.net451.bin.assembly;
                        }
                    }
                    else
                    {
                        DirectoryInfo di = new DirectoryInfo(ld.Path);
                        path = DepresolveConsoleCommand.FindDll(di, ld.Identity.Name);
                        HandleNuspec(ld.Path, ld.Identity.Name);
                    }
                    r = MetadataReference.CreateFromFile(path);
                }
                catch (Exception e)
                {
                    try
                    {
                        string        name    = ld.Identity.Name;
                        string        path    = ld.Path;
                        string        cd      = path.Substring(0, path.LastIndexOf('/'));
                        DirectoryInfo di      = new DirectoryInfo(cd);
                        string        newpath = DepresolveConsoleCommand.FindDll(di, ld.Identity.Name);
                        HandleNuspec(cd, ld.Identity.Name);
                        r = MetadataReference.CreateFromFile(newpath);
                    }
                    catch (Exception ee)
                    {
                    }
                }
                if (r != null)
                {
                    libs.Add(r);
                }
            }
            context.Compilation = context.Compilation.WithReferences(libs);

            var runner = new GraphRunner();

            foreach (var st in context.Compilation.SyntaxTrees)
            {
                var path = st.FilePath;
                if (!string.IsNullOrWhiteSpace(path))
                {
                    path = Utils.GetRelativePath(path, context.RootPath);
                    if (!string.IsNullOrWhiteSpace(path) && (path.Substring(0, 3) != ".." + Path.DirectorySeparatorChar) && !path.Equals("file://applyprojectinfo.cs/"))
                    {
                        // this is a source code file we want to grap
                        runner._sm   = context.Compilation.GetSemanticModel(st, false);
                        runner._path = path;
                        var root = await st.GetRootAsync();

                        runner.Visit(root);
                    }
                }
            }

            runner._sm   = null;
            runner._path = null;
            runner.RunTokens();
            return(runner._output);
        }
コード例 #10
0
        public async Task <string> GetSourceTextAsync()
        {
            Microsoft.CodeAnalysis.Text.SourceText text = await GetDocument().GetTextAsync();

            return(text.ToString());
        }
コード例 #11
0
        internal static async Task<Output> Graph(GraphContext context)
        {
            if (context.Project == null)
            {
                Project project;
                if (!Project.TryGetProject(context.ProjectDirectory, out project))
                {
                    //not a DNX project
                    DirectoryInfo di = new DirectoryInfo(context.ProjectDirectory);
                    FileInfo[] fis = DepresolveConsoleCommand.FindSources(di);
                    string[] files = new string[fis.Length];
                    for (int i = 0; i < fis.Length; i++)
                    {
                        files[i] = fis[i].FullName;
                    }
                    Microsoft.CodeAnalysis.Text.SourceText[] sources = new Microsoft.CodeAnalysis.Text.SourceText[files.Length];
                    SyntaxTree[] trees = new SyntaxTree[files.Length];
                    Dictionary<SyntaxTree, string> dict = new Dictionary<SyntaxTree, string>();
                    var compilation = CSharpCompilation.Create("name");
                    for (int i = 0; i < files.Length; i++)
                    {
                        try
                        {
                            sources[i] = Microsoft.CodeAnalysis.Text.SourceText.From(new FileStream(files[i], FileMode.Open));
                            trees[i] = CSharpSyntaxTree.ParseText(sources[i]);
                            if (trees[i] != null)
                            {
                                compilation = compilation.AddSyntaxTrees(trees[i]);
                                dict[trees[i]] = files[i];
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }

                    var gr = new GraphRunner();
                    foreach (var st in compilation.SyntaxTrees)
                    {
                        var path = dict[st];
                        if (!string.IsNullOrWhiteSpace(path))
                        {
                            path = Utils.GetRelativePath(path, context.ProjectDirectory);
                            if (!string.IsNullOrWhiteSpace(path) && (path.Substring(0, 3) != ".." + Path.DirectorySeparatorChar) && !path.Equals("file://applyprojectinfo.cs/"))
                            {
                                // this is a source code file we want to grap
                                gr._sm = compilation.GetSemanticModel(st, false);
                                gr._path = path;
                                var root = await st.GetRootAsync();
                                gr.Visit(root);
                            }
                        }
                    }
                    gr._sm = null;
                    gr._path = null;
                    gr.RunTokens();
                    return gr._output;

                }

                context.Project = project;
            }

            context.ApplicationHostContext = new ApplicationHostContext
            {
                ProjectDirectory = context.ProjectDirectory,
                Project = context.Project,
                TargetFramework = context.Project.GetTargetFrameworks().First().FrameworkName
            };

            context.ApplicationEnvironment = new ApplicationEnvironment(
              context.Project,
              context.ApplicationHostContext.TargetFramework,
              "Debug",
              context.HostEnvironment);

            context.CompilationContext = new CompilationEngineContext(context.ApplicationEnvironment, context.RuntimeEnvironment, context.LoadContextAccessor.Default, new CompilationCache());

            context.CompilationEngine = new CompilationEngine(context.CompilationContext);
            context.LibraryExporter = context.CompilationEngine.CreateProjectExporter(context.Project, context.ApplicationHostContext.TargetFramework, "Debug");
            context.Export = context.LibraryExporter.GetExport(context.Project.Name);

            if (!(context.Export.MetadataReferences[0] is IRoslynMetadataReference))
            {
                return new Output();
            }
            var roslynRef = (IRoslynMetadataReference)context.Export.MetadataReferences[0];
            var compilationRef = (CompilationReference)roslynRef.MetadataReference;
            var csCompilation = (CSharpCompilation)compilationRef.Compilation;
            context.Compilation = csCompilation;

            IEnumerable<LibraryDescription> deps = DepresolveConsoleCommand.DepResolve(context.Project);
            HashSet<PortableExecutableReference> libs = new HashSet<PortableExecutableReference>();
            try
            {
                libs.Add(MetadataReference.CreateFromFile("/opt/DNX_BRANCH/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin/mscorlib.dll"));
            }
            catch (Exception e)
            {
            }
            foreach (LibraryDescription ld in deps)
            {
                PortableExecutableReference r = null;
                try
                {
                    string path = "";
                    if (ld.Path.EndsWith("project.json") && (ld.Path.IndexOf("wrap") != -1))
                    {
                        if (File.Exists(ld.Path))
                        {
                            var content = File.ReadAllText(ld.Path);
                            var spec = JsonConvert.DeserializeObject<Wrap>(content);
                            path = ld.Path.Substring(0, ld.Path.Length - 12) + spec.frameworks.net451.bin.assembly;
                        }
                    }
                    else
                    {
                        DirectoryInfo di = new DirectoryInfo(ld.Path);
                        path = DepresolveConsoleCommand.FindDll(di, ld.Identity.Name);
                        HandleNuspec(ld.Path, ld.Identity.Name);
                    }
                    r = MetadataReference.CreateFromFile(path);
                }
                catch (Exception e)
                {
                    try
                    {
                        string name = ld.Identity.Name;
                        string path = ld.Path;
                        string cd = path.Substring(0, path.LastIndexOf('/'));
                        DirectoryInfo di = new DirectoryInfo(cd);
                        string newpath = DepresolveConsoleCommand.FindDll(di, ld.Identity.Name);
                        HandleNuspec(cd, ld.Identity.Name);
                        r = MetadataReference.CreateFromFile(newpath);
                    }
                    catch (Exception ee)
                    {
                    }
                }
                if (r != null)
                {
                    libs.Add(r);
                }
            }
            context.Compilation = context.Compilation.WithReferences(libs);

            var runner = new GraphRunner();
            foreach (var st in context.Compilation.SyntaxTrees)
            {
                var path = st.FilePath;
                if (!string.IsNullOrWhiteSpace(path))
                {
                    path = Utils.GetRelativePath(path, context.RootPath);
                    if (!string.IsNullOrWhiteSpace(path) && (path.Substring(0, 3) != ".." + Path.DirectorySeparatorChar) && !path.Equals("file://applyprojectinfo.cs/"))
                    {
                        // this is a source code file we want to grap
                        runner._sm = context.Compilation.GetSemanticModel(st, false);
                        runner._path = path;
                        var root = await st.GetRootAsync();
                        runner.Visit(root);
                    }
                }
            }

            runner._sm = null;
            runner._path = null;
            runner.RunTokens();
            return runner._output;
        }
コード例 #12
0
        private static bool ShouldFilterHtmlDiagnosticBasedOnErrorCode(OmniSharpVSDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree, ILogger logger)
        {
            if (!diagnostic.Code.HasValue)
            {
                return(false);
            }

            return(diagnostic.Code.Value.String switch
            {
                CSSErrorCodes.MissingOpeningBrace => IsCSharpInStyleBlock(diagnostic, sourceText, syntaxTree, logger),
                CSSErrorCodes.MissingSelectorAfterCombinator => IsCSharpInStyleBlock(diagnostic, sourceText, syntaxTree, logger),
                CSSErrorCodes.MissingSelectorBeforeCombinatorCode => IsCSharpInStyleBlock(diagnostic, sourceText, syntaxTree, logger),
                HtmlErrorCodes.UnexpectedEndTagErrorCode => IsHtmlWithBangAndMatchingTags(diagnostic, sourceText, syntaxTree, logger),
                HtmlErrorCodes.InvalidNestingErrorCode => IsAnyFilteredInvalidNestingError(diagnostic, sourceText, syntaxTree, logger),
                HtmlErrorCodes.MissingEndTagErrorCode => FileKinds.IsComponent(syntaxTree.Options.FileKind), // Redundant with RZ9980 in Components
                HtmlErrorCodes.TooFewElementsErrorCode => IsAnyFilteredTooFewElementsError(diagnostic, sourceText, syntaxTree, logger),
                _ => false,
            });